MLIR 24.0.0git
Shape.cpp
Go to the documentation of this file.
1//===- Shape.cpp - MLIR Shape Operations ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
15#include "mlir/Dialect/Traits.h"
17#include "mlir/IR/Builders.h"
19#include "mlir/IR/Matchers.h"
24#include "llvm/ADT/SetOperations.h"
25#include "llvm/ADT/SmallVectorExtras.h"
26#include "llvm/Support/raw_ostream.h"
27#include <utility>
28
29using namespace mlir;
30using namespace mlir::shape;
31
32#include "mlir/Dialect/Shape/IR/ShapeOpsDialect.cpp.inc"
33
34namespace {
35#include "ShapeCanonicalization.inc"
36} // namespace
37
38RankedTensorType shape::getExtentTensorType(MLIRContext *ctx, int64_t rank) {
39 return RankedTensorType::get({rank}, IndexType::get(ctx));
40}
41
43 auto ranked = llvm::dyn_cast<RankedTensorType>(type);
44 return ranked && ranked.getRank() == 1 && ranked.getElementType().isIndex();
45}
46
47LogicalResult shape::getShapeVec(Value input,
48 SmallVectorImpl<int64_t> &shapeValues) {
49 if (auto inputOp = input.getDefiningOp<ShapeOfOp>()) {
50 auto type = llvm::cast<ShapedType>(inputOp.getArg().getType());
51 if (!type.hasRank())
52 return failure();
53 llvm::append_range(shapeValues, type.getShape());
54 return success();
55 }
57 if (matchPattern(input, m_Constant(&attr))) {
58 llvm::append_range(shapeValues, attr.getValues<int64_t>());
59 return success();
60 }
61 return failure();
62}
63
64static bool isErrorPropagationPossible(TypeRange operandTypes) {
65 return llvm::any_of(operandTypes,
66 llvm::IsaPred<SizeType, ShapeType, ValueShapeType>);
67}
68
69static LogicalResult verifySizeOrIndexOp(Operation *op) {
70 assert(op != nullptr && op->getNumResults() == 1);
71 Type resultTy = op->getResultTypes().front();
73 if (!llvm::isa<SizeType>(resultTy))
74 return op->emitOpError()
75 << "if at least one of the operands can hold error values then "
76 "the result must be of type `size` to propagate them";
77 }
78 return success();
79}
80
81static LogicalResult verifyShapeOrExtentTensorOp(Operation *op) {
82 assert(op != nullptr && op->getNumResults() == 1);
83 Type resultTy = op->getResultTypes().front();
85 if (!llvm::isa<ShapeType>(resultTy))
86 return op->emitOpError()
87 << "if at least one of the operands can hold error values then "
88 "the result must be of type `shape` to propagate them";
89 }
90 return success();
91}
92
93template <typename... Ty>
94static bool eachHasOnlyOneOfTypes(TypeRange typeRange) {
95 return typeRange.size() == 1 && llvm::isa<Ty...>(typeRange.front());
96}
97
98template <typename... Ty, typename... ranges>
99static bool eachHasOnlyOneOfTypes(TypeRange l, ranges... rs) {
100 return eachHasOnlyOneOfTypes<Ty...>(l) && eachHasOnlyOneOfTypes<Ty...>(rs...);
101}
102
103//===----------------------------------------------------------------------===//
104// InlinerInterface
105//===----------------------------------------------------------------------===//
106
107namespace {
108/// This class defines the interface for inlining shape dialect ops.
109struct ShapeInlinerInterface : public DialectInlinerInterface {
110 using DialectInlinerInterface::DialectInlinerInterface;
111
112 // Returns true if the given region 'src' can be inlined into the region
113 // 'dest' that is attached to an operation registered to the current dialect.
114 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
115 IRMapping &) const final {
116 return true;
117 }
118
119 // Returns true if the given operation 'op', that is registered to this
120 // dialect, can be inlined into the region 'dest' that is attached to an
121 // operation registered to the current dialect.
122 bool isLegalToInline(Operation *op, Region *dest, bool wouldBeCloned,
123 IRMapping &) const final {
124 return true;
125 }
126};
127} // namespace
128
129void ShapeDialect::initialize() {
130 addInterfaces<ShapeInlinerInterface>();
131 // Allow unknown operations during prototyping and testing. As the dialect is
132 // still evolving it makes it simple to start with an unregistered ops and
133 // try different variants before actually defining the op.
134 allowUnknownOperations();
135 declarePromisedInterfaces<bufferization::BufferizableOpInterface, AssumingOp,
136 AssumingYieldOp>();
137}
138
139Operation *ShapeDialect::materializeConstant(OpBuilder &builder,
140 Attribute value, Type type,
141 Location loc) {
142 if (auto poison = dyn_cast<ub::PoisonAttr>(value))
143 return ub::PoisonOp::create(builder, loc, type, poison);
144
145 if (llvm::isa<ShapeType>(type) || isExtentTensorType(type))
146 return ConstShapeOp::create(builder, loc, type,
147 llvm::cast<DenseIntElementsAttr>(value));
148 if (llvm::isa<SizeType>(type))
149 return ConstSizeOp::create(builder, loc, type,
150 llvm::cast<IntegerAttr>(value));
151 if (llvm::isa<WitnessType>(type))
152 return ConstWitnessOp::create(builder, loc, type,
153 llvm::cast<BoolAttr>(value));
154
155 return arith::ConstantOp::materialize(builder, value, type, loc);
156}
157
158LogicalResult ShapeDialect::verifyOperationAttribute(Operation *op,
159 NamedAttribute attribute) {
160 // Verify shape.lib attribute.
161 if (attribute.getName() == "shape.lib") {
162 if (!op->hasTrait<OpTrait::SymbolTable>())
163 return op->emitError(
164 "shape.lib attribute may only be on op implementing SymbolTable");
165
166 if (auto symbolRef = llvm::dyn_cast<SymbolRefAttr>(attribute.getValue())) {
167 auto *symbol = SymbolTable::lookupSymbolIn(op, symbolRef);
168 if (!symbol)
169 return op->emitError("shape function library ")
170 << symbolRef << " not found";
171 return isa<shape::FunctionLibraryOp>(symbol)
172 ? success()
173 : op->emitError()
174 << symbolRef << " required to be shape function library";
175 }
176
177 if (auto arr = llvm::dyn_cast<ArrayAttr>(attribute.getValue())) {
178 // Verify all entries are function libraries and mappings in libraries
179 // refer to unique ops.
181 for (auto it : arr) {
182 if (!llvm::isa<SymbolRefAttr>(it))
183 return op->emitError(
184 "only SymbolRefAttr allowed in shape.lib attribute array");
185
186 auto shapeFnLib = dyn_cast_or_null<shape::FunctionLibraryOp>(
187 SymbolTable::lookupSymbolIn(op, llvm::cast<SymbolRefAttr>(it)));
188 if (!shapeFnLib)
189 return op->emitError()
190 << it << " does not refer to FunctionLibraryOp";
191 for (auto mapping : shapeFnLib.getMapping()) {
192 if (!key.insert(mapping.getName()).second) {
193 return op->emitError("only one op to shape mapping allowed, found "
194 "multiple for `")
195 << mapping.getName() << "`";
196 }
197 }
198 }
199 return success();
200 }
201
202 return op->emitError("only SymbolRefAttr or array of SymbolRefAttrs "
203 "allowed as shape.lib attribute");
204 }
205 return success();
206}
207
208//===----------------------------------------------------------------------===//
209// AnyOp
210//===----------------------------------------------------------------------===//
211
212// TODO: Canonicalization should be implemented for shapes that can be
213// determined through mixtures of the known dimensions of the inputs.
214OpFoldResult AnyOp::fold(FoldAdaptor adaptor) {
215 // Only the last operand is checked because AnyOp is commutative.
216 if (adaptor.getInputs().back())
217 return adaptor.getInputs().back();
218
219 return nullptr;
220}
221
222//===----------------------------------------------------------------------===//
223// AssumingOp
224//===----------------------------------------------------------------------===//
225
226ParseResult AssumingOp::parse(OpAsmParser &parser, OperationState &result) {
227 result.regions.reserve(1);
228 Region *doRegion = result.addRegion();
229
230 auto &builder = parser.getBuilder();
232 if (parser.parseOperand(cond) ||
233 parser.resolveOperand(cond, builder.getType<WitnessType>(),
234 result.operands))
235 return failure();
236
237 // Parse optional results type list.
238 if (parser.parseOptionalArrowTypeList(result.types))
239 return failure();
240
241 // Parse the region and add a terminator if elided.
242 if (parser.parseRegion(*doRegion, /*arguments=*/{}, /*argTypes=*/{}))
243 return failure();
244 AssumingOp::ensureTerminator(*doRegion, parser.getBuilder(), result.location);
245
246 // Parse the optional attribute list.
247 if (parser.parseOptionalAttrDict(result.attributes))
248 return failure();
249 return success();
250}
251
252void AssumingOp::print(OpAsmPrinter &p) {
253 bool yieldsResults = !getResults().empty();
254
255 p << " " << getWitness();
256 if (yieldsResults)
257 p << " -> (" << getResultTypes() << ")";
258 p << ' ';
259 p.printRegion(getDoRegion(),
260 /*printEntryBlockArgs=*/false,
261 /*printBlockTerminators=*/yieldsResults);
262 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
263}
264
265namespace {
266// Removes AssumingOp with a passing witness and inlines the region.
267struct AssumingWithTrue : public OpRewritePattern<AssumingOp> {
268 using OpRewritePattern<AssumingOp>::OpRewritePattern;
269
270 LogicalResult matchAndRewrite(AssumingOp op,
271 PatternRewriter &rewriter) const override {
272 auto witness = op.getWitness().getDefiningOp<ConstWitnessOp>();
273 if (!witness || !witness.getPassingAttr())
274 return failure();
275
276 AssumingOp::inlineRegionIntoParent(op, rewriter);
277 return success();
278 }
279};
280
281struct AssumingOpRemoveUnusedResults : public OpRewritePattern<AssumingOp> {
282 using OpRewritePattern<AssumingOp>::OpRewritePattern;
283
284 LogicalResult matchAndRewrite(AssumingOp op,
285 PatternRewriter &rewriter) const override {
286 Block *body = op.getBody();
287 auto yieldOp = llvm::cast<AssumingYieldOp>(body->getTerminator());
288
289 // Find used values.
290 SmallVector<Value, 4> newYieldOperands;
291 for (auto [opResult, yieldOperand] :
292 llvm::zip(op.getResults(), yieldOp.getOperands())) {
293 if (!opResult.getUses().empty()) {
294 newYieldOperands.push_back(yieldOperand);
295 }
296 }
297
298 // Rewrite only if redundant results exist.
299 if (newYieldOperands.size() == yieldOp->getNumOperands())
300 return failure();
301
302 // Replace yield op in the old assuming op's body and move the entire region
303 // to the new assuming op.
304 rewriter.setInsertionPointToEnd(body);
305 auto newYieldOp =
306 rewriter.replaceOpWithNewOp<AssumingYieldOp>(yieldOp, newYieldOperands);
307 rewriter.setInsertionPoint(op);
308 auto newOp = AssumingOp::create(
309 rewriter, op.getLoc(), newYieldOp->getOperandTypes(), op.getWitness());
310 newOp.getDoRegion().takeBody(op.getDoRegion());
311
312 // Use the new results to replace the previously used ones.
313 SmallVector<Value, 4> replacementValues;
314 auto src = newOp.getResults().begin();
315 for (auto it : op.getResults()) {
316 if (it.getUses().empty())
317 replacementValues.push_back(nullptr);
318 else
319 replacementValues.push_back(*src++);
320 }
321 rewriter.replaceOp(op, replacementValues);
322 return success();
323 }
324};
325} // namespace
326
327void AssumingOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
328 MLIRContext *context) {
329 patterns.add<AssumingOpRemoveUnusedResults, AssumingWithTrue>(context);
330}
331
332// See RegionBranchOpInterface in Interfaces/ControlFlowInterfaces.td
333void AssumingOp::getSuccessorRegions(
335 // AssumingOp has unconditional control flow into the region and back to the
336 // parent, so return the correct RegionSuccessor purely based on the index
337 // being None or 0.
338 if (!point.isParent()) {
339 regions.push_back(RegionSuccessor(getOperation()));
340 return;
341 }
342
343 regions.push_back(RegionSuccessor(&getDoRegion()));
344}
345
346ValueRange AssumingOp::getSuccessorInputs(RegionSuccessor successor) {
347 return successor.isOperation() ? ValueRange(getResults()) : ValueRange();
348}
349
350void AssumingOp::inlineRegionIntoParent(AssumingOp &op,
351 PatternRewriter &rewriter) {
352 auto *blockBeforeAssuming = rewriter.getInsertionBlock();
353 auto *assumingBlock = op.getBody();
354 auto initPosition = rewriter.getInsertionPoint();
355 auto *blockAfterAssuming =
356 rewriter.splitBlock(blockBeforeAssuming, initPosition);
357
358 // Remove the AssumingOp and AssumingYieldOp.
359 auto &yieldOp = assumingBlock->back();
360 rewriter.inlineRegionBefore(op.getDoRegion(), blockAfterAssuming);
361 rewriter.replaceOp(op, yieldOp.getOperands());
362 rewriter.eraseOp(&yieldOp);
363
364 // Merge blocks together as there was no branching behavior from the
365 // AssumingOp.
366 rewriter.mergeBlocks(assumingBlock, blockBeforeAssuming);
367 rewriter.mergeBlocks(blockAfterAssuming, blockBeforeAssuming);
368}
369
370void AssumingOp::build(
371 OpBuilder &builder, OperationState &result, Value witness,
373 OpBuilder::InsertionGuard g(builder);
374
375 result.addOperands(witness);
376 Region *bodyRegion = result.addRegion();
377 builder.createBlock(bodyRegion);
378
379 // Build body.
380 SmallVector<Value, 2> yieldValues = bodyBuilder(builder, result.location);
381 AssumingYieldOp::create(builder, result.location, yieldValues);
382
383 SmallVector<Type, 2> assumingTypes;
384 for (Value v : yieldValues)
385 assumingTypes.push_back(v.getType());
386 result.addTypes(assumingTypes);
387}
388
389//===----------------------------------------------------------------------===//
390// AddOp
391//===----------------------------------------------------------------------===//
392
393LogicalResult mlir::shape::AddOp::inferReturnTypes(
394 MLIRContext *context, std::optional<Location> location,
395 AddOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
396 if (llvm::isa<SizeType>(adaptor.getLhs().getType()) ||
397 llvm::isa<SizeType>(adaptor.getRhs().getType()))
398 inferredReturnTypes.assign({SizeType::get(context)});
399 else
400 inferredReturnTypes.assign({IndexType::get(context)});
401 return success();
402}
403
404bool mlir::shape::AddOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
405 // SizeType is compatible with IndexType.
407}
408
409OpFoldResult mlir::shape::AddOp::fold(FoldAdaptor adaptor) {
410 // add(x, 0) -> x
411 if (matchPattern(getRhs(), m_Zero()))
412 return getLhs();
413
415 adaptor.getOperands(),
416 [](APInt a, const APInt &b) { return std::move(a) + b; });
417}
418
419LogicalResult shape::AddOp::verify() { return verifySizeOrIndexOp(*this); }
420
421//===----------------------------------------------------------------------===//
422// AssumingAllOp
423//===----------------------------------------------------------------------===//
424
425namespace {
426
427// Merge multiple `shape.assuming_all` operations together.
428//
429// %0 = shape.assuming_all %w0, %w1
430// %1 = shape.assuming_all %w2, %0
431//
432// to:
433//
434// %0 = shape.assuming_all %w0, %w2, %w2
435struct MergeAssumingAllOps : public OpRewritePattern<AssumingAllOp> {
436 using OpRewritePattern<AssumingAllOp>::OpRewritePattern;
437
438 LogicalResult matchAndRewrite(AssumingAllOp op,
439 PatternRewriter &rewriter) const override {
440 SmallVector<Value> operands;
441
442 for (Value operand : op.getInputs()) {
443 if (auto assumeAll = operand.getDefiningOp<AssumingAllOp>())
444 operands.append(assumeAll.operand_begin(), assumeAll->operand_end());
445 else
446 operands.push_back(operand);
447 }
448
449 // We didn't find any other `assuming_all` ops to merge with.
450 if (operands.size() == op.getNumOperands())
451 return failure();
452
453 // Replace with a new `assuming_all` operation with merged constraints.
454 rewriter.replaceOpWithNewOp<AssumingAllOp>(op, operands);
455 return success();
456 }
457};
458
459// Eliminate `cstr_broadcastable` operands from `assuming_all` operation that
460// are subsumed by others.
461//
462// %0 = shape.cstr_broadcastable %shape0, %shape1
463// %1 = shape.cstr_broadcastable %shape0, %shape1, %shape2
464//
465// %2 = shape.cstr_broadcastable %shape3, %shape4
466// %3 = shape.cstr_broadcastable %shape3, %shape4, %shape5
467//
468// %4 = shape.assuming_all %0, %1, %2, %3
469//
470// to:
471//
472// %0 = shape.cstr_broadcastable %shape0, %shape1, %shape2
473// %1 = shape.cstr_broadcastable %shape3, %shape4, %shape5
474// %2 = shape.assuming_all %0, %1
475//
476// In this example if shapes [0, 1, 2] are broadcastable, then it means that
477// shapes [0, 1] are broadcastable too, and can be removed from the list of
478// constraints. If shapes [0, 1, 2] are not broadcastable, then it doesn't
479// matter if shapes [0, 1] are broadcastable (same for shapes [3, 4, 5]).
480struct AssumingAllOfCstrBroadcastable : public OpRewritePattern<AssumingAllOp> {
481 using OpRewritePattern<AssumingAllOp>::OpRewritePattern;
482
483 LogicalResult matchAndRewrite(AssumingAllOp op,
484 PatternRewriter &rewriter) const override {
485 // Collect all `CstrBroadcastableOp` operands first.
487 for (Value operand : op.getInputs()) {
488 // TODO: Apply this optimization if some of the witnesses are not
489 // produced by the `cstr_broadcastable`.
490 auto broadcastable = operand.getDefiningOp<CstrBroadcastableOp>();
491 if (!broadcastable)
492 return failure();
493
494 operands.insert(broadcastable);
495 }
496
497 // Skip trivial `assuming_all` operations.
498 if (operands.size() <= 1)
499 return failure();
500
501 // Collect shapes checked by `cstr_broadcastable` operands.
502 SmallVector<std::pair<CstrBroadcastableOp, DenseSet<Value>>> shapes;
503 for (auto cstr : operands) {
504 DenseSet<Value> shapesSet(cstr->operand_begin(), cstr->operand_end());
505 shapes.emplace_back(cstr, std::move(shapesSet));
506 }
507
508 // Sort by the number of shape operands (larger to smaller).
509 llvm::sort(shapes, [](auto a, auto b) {
510 return a.first.getNumOperands() > b.first.getNumOperands();
511 });
512
513 // We start from the `cst_broadcastable` operations with largest number of
514 // shape operands, and remove redundant `cst_broadcastable` operations. We
515 // do this until we find a set of `cst_broadcastable` operations with
516 // non-overlapping constraints.
517 SmallVector<CstrBroadcastableOp> markedForErase;
518
519 for (unsigned i = 0; i < shapes.size(); ++i) {
520 auto isSubset = [&](auto pair) {
521 return llvm::set_is_subset(pair.second, shapes[i].second);
522 };
523
524 // Keep redundant `cstr_broadcastable` operations to be erased.
525 auto *it = std::remove_if(shapes.begin() + i + 1, shapes.end(), isSubset);
526 for (auto *it0 = it; it0 < shapes.end(); ++it0)
527 markedForErase.push_back(it0->first);
528 shapes.erase(it, shapes.end());
529 }
530
531 // We didn't find any operands that could be removed.
532 if (markedForErase.empty())
533 return failure();
534
535 // Collect non-overlapping `cst_broadcastable` constraints.
536 SmallVector<Value> uniqueConstraints;
537 for (auto &shape : shapes)
538 uniqueConstraints.push_back(shape.first.getResult());
539
540 // Replace with a new `assuming_all` operation ...
541 rewriter.replaceOpWithNewOp<AssumingAllOp>(op, uniqueConstraints);
542
543 // ... and maybe erase `cstr_broadcastable` ops without uses.
544 for (auto &op : markedForErase)
545 if (op->use_empty())
546 rewriter.eraseOp(op);
547
548 return success();
549 }
550};
551
552struct AssumingAllToCstrEqCanonicalization
553 : public OpRewritePattern<AssumingAllOp> {
554 using OpRewritePattern<AssumingAllOp>::OpRewritePattern;
555
556 LogicalResult matchAndRewrite(AssumingAllOp op,
557 PatternRewriter &rewriter) const override {
558 SmallVector<Value, 8> shapes;
559 for (Value w : op.getInputs()) {
560 auto cstrEqOp = w.getDefiningOp<CstrEqOp>();
561 if (!cstrEqOp)
562 return failure();
563 bool disjointShapes = llvm::none_of(cstrEqOp.getShapes(), [&](Value s) {
564 return llvm::is_contained(shapes, s);
565 });
566 if (!shapes.empty() && !cstrEqOp.getShapes().empty() && disjointShapes)
567 return failure();
568 shapes.append(cstrEqOp.getShapes().begin(), cstrEqOp.getShapes().end());
569 }
570 rewriter.replaceOpWithNewOp<CstrEqOp>(op, shapes);
571 return success();
572 }
573};
574
575template <typename OpTy>
576struct RemoveDuplicateOperandsPattern : public OpRewritePattern<OpTy> {
577 using OpRewritePattern<OpTy>::OpRewritePattern;
578
579 LogicalResult matchAndRewrite(OpTy op,
580 PatternRewriter &rewriter) const override {
581 // Find unique operands.
582 SetVector<Value> unique(op.operand_begin(), op.operand_end());
583
584 // Reduce op to equivalent with unique operands.
585 if (unique.size() < op.getNumOperands()) {
586 rewriter.replaceOpWithNewOp<OpTy>(
587 op, op->getResultTypes(), unique.takeVector(), op.getProperties(),
588 op->getDiscardableAttrDictionary().getValue());
589 return success();
590 }
591
592 return failure();
593 }
594};
595} // namespace
596
597void AssumingAllOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
598 MLIRContext *context) {
599 patterns
600 .add<MergeAssumingAllOps, AssumingAllOneOp,
601 AssumingAllOfCstrBroadcastable, AssumingAllToCstrEqCanonicalization,
602 RemoveDuplicateOperandsPattern<AssumingAllOp>>(context);
603}
604
605OpFoldResult AssumingAllOp::fold(FoldAdaptor adaptor) {
606 // Iterate in reverse to first handle all constant operands. They are
607 // guaranteed to be the tail of the inputs because this is commutative.
608 for (int idx = adaptor.getInputs().size() - 1; idx >= 0; idx--) {
609 Attribute a = adaptor.getInputs()[idx];
610 // Cannot fold if any inputs are not constant;
611 if (!a)
612 return nullptr;
613
614 // We do not need to keep statically known values after handling them in
615 // this method.
616 getOperation()->eraseOperand(idx);
617
618 // Always false if any input is statically known false
619 if (!llvm::cast<BoolAttr>(a).getValue())
620 return a;
621 }
622 // If this is reached, all inputs were statically known passing.
623 return BoolAttr::get(getContext(), true);
624}
625
626LogicalResult AssumingAllOp::verify() {
627 // Ensure that AssumingAllOp contains at least one operand
628 if (getNumOperands() == 0)
629 return emitOpError("no operands specified");
630
631 return success();
632}
633
634//===----------------------------------------------------------------------===//
635// BroadcastOp
636//===----------------------------------------------------------------------===//
637
638OpFoldResult BroadcastOp::fold(FoldAdaptor adaptor) {
639 if (getShapes().size() == 1) {
640 // Otherwise, we need a cast which would be a canonicalization, not folding.
641 if (getShapes().front().getType() != getType())
642 return nullptr;
643 return getShapes().front();
644 }
645
646 auto firstAttr =
647 dyn_cast_or_null<DenseIntElementsAttr>(adaptor.getShapes().front());
648 if (!firstAttr)
649 return nullptr;
650
651 SmallVector<int64_t, 6> resultShape(firstAttr.getValues<int64_t>());
652
653 for (auto next : adaptor.getShapes().drop_front()) {
654 auto nextAttr = dyn_cast_or_null<DenseIntElementsAttr>(next);
655 if (!nextAttr)
656 return nullptr;
657 auto nextShape = llvm::to_vector<6>(nextAttr.getValues<int64_t>());
658
660 // If the shapes are not compatible, we can't fold it.
661 // TODO: Fold to an "error".
662 if (!OpTrait::util::getBroadcastedShape(resultShape, nextShape, tmpShape))
663 return nullptr;
664
665 resultShape.clear();
666 std::copy(tmpShape.begin(), tmpShape.end(),
667 std::back_inserter(resultShape));
668 }
669
670 Builder builder(getContext());
671 return builder.getIndexTensorAttr(resultShape);
672}
673
674LogicalResult BroadcastOp::verify() {
675 return verifyShapeOrExtentTensorOp(*this);
676}
677
678namespace {
679template <typename OpTy>
680struct RemoveEmptyShapeOperandsPattern : public OpRewritePattern<OpTy> {
681 using OpRewritePattern<OpTy>::OpRewritePattern;
682
683 LogicalResult matchAndRewrite(OpTy op,
684 PatternRewriter &rewriter) const override {
685 auto isPotentiallyNonEmptyShape = [](Value shape) {
686 if (auto extentTensorTy =
687 llvm::dyn_cast<RankedTensorType>(shape.getType())) {
688 if (extentTensorTy.getDimSize(0) == 0)
689 return false;
690 }
691 if (auto constShape = shape.getDefiningOp<ConstShapeOp>()) {
692 if (constShape.getShape().empty())
693 return false;
694 }
695 return true;
696 };
697 auto newOperands = llvm::filter_to_vector<8>(op->getOperands(),
698 isPotentiallyNonEmptyShape);
699
700 // Replace the op with empty shape constant if all operants are reduced to
701 // be empty.
702 if (newOperands.empty()) {
703 rewriter.replaceOpWithNewOp<ConstShapeOp>(
704 op, op->getResultTypes().front(), rewriter.getIndexTensorAttr({}));
705 return success();
706 }
707
708 // Reduce op to equivalent without empty shape operands.
709 if (newOperands.size() < op.getNumOperands()) {
710 rewriter.replaceOpWithNewOp<OpTy>(
711 op, op->getResultTypes(), newOperands, op.getProperties(),
712 op->getDiscardableAttrDictionary().getValue());
713 return success();
714 }
715
716 return failure();
717 }
718};
719
720struct BroadcastForwardSingleOperandPattern
721 : public OpRewritePattern<BroadcastOp> {
722 using OpRewritePattern<BroadcastOp>::OpRewritePattern;
723
724 LogicalResult matchAndRewrite(BroadcastOp op,
725 PatternRewriter &rewriter) const override {
726 if (op.getNumOperands() != 1)
727 return failure();
728 Value replacement = op.getShapes().front();
729
730 // Insert cast if needed.
731 if (replacement.getType() != op.getType()) {
732 auto loc = op.getLoc();
733 if (llvm::isa<ShapeType>(op.getType())) {
734 replacement = FromExtentTensorOp::create(rewriter, loc, replacement);
735 } else {
736 assert(!llvm::isa<ShapeType>(op.getType()) &&
737 !llvm::isa<ShapeType>(replacement.getType()) &&
738 "expect extent tensor cast");
740 tensor::CastOp::create(rewriter, loc, op.getType(), replacement);
741 }
742 }
743
744 rewriter.replaceOp(op, replacement);
745 return success();
746 }
747};
748
749struct BroadcastFoldConstantOperandsPattern
750 : public OpRewritePattern<BroadcastOp> {
751 using OpRewritePattern<BroadcastOp>::OpRewritePattern;
752
753 LogicalResult matchAndRewrite(BroadcastOp op,
754 PatternRewriter &rewriter) const override {
755 SmallVector<int64_t, 8> foldedConstantShape;
756 SmallVector<Value, 8> newShapeOperands;
757 for (Value shape : op.getShapes()) {
758 if (auto constShape = shape.getDefiningOp<ConstShapeOp>()) {
759 SmallVector<int64_t, 8> newFoldedConstantShape;
761 foldedConstantShape,
762 llvm::to_vector<8>(constShape.getShape().getValues<int64_t>()),
763 newFoldedConstantShape)) {
764 foldedConstantShape = newFoldedConstantShape;
765 continue;
766 }
767 }
768 newShapeOperands.push_back(shape);
769 }
770
771 // Need at least two constant operands to fold anything.
772 if (op.getNumOperands() - newShapeOperands.size() < 2)
773 return failure();
774
775 auto foldedConstantOperandsTy = RankedTensorType::get(
776 {static_cast<int64_t>(foldedConstantShape.size())},
777 rewriter.getIndexType());
778 newShapeOperands.push_back(
779 ConstShapeOp::create(rewriter, op.getLoc(), foldedConstantOperandsTy,
780 rewriter.getIndexTensorAttr(foldedConstantShape)));
781 rewriter.replaceOpWithNewOp<BroadcastOp>(
782 op, TypeRange{op.getType()}, newShapeOperands, op.getProperties(),
783 op->getDiscardableAttrDictionary().getValue());
784 return success();
785 }
786};
787
788template <typename OpTy>
789struct CanonicalizeCastExtentTensorOperandsPattern
790 : public OpRewritePattern<OpTy> {
791 using OpRewritePattern<OpTy>::OpRewritePattern;
792
793 LogicalResult matchAndRewrite(OpTy op,
794 PatternRewriter &rewriter) const override {
795 // Canonicalize operands.
796 bool anyChange = false;
797 auto canonicalizeOperand = [&](Value operand) -> Value {
798 if (auto castOp = operand.getDefiningOp<tensor::CastOp>()) {
799 // Only eliminate the cast if it holds no shape information.
800 bool isInformationLoosingCast =
801 llvm::cast<RankedTensorType>(castOp.getType()).isDynamicDim(0);
802 if (isInformationLoosingCast) {
803 anyChange = true;
804 return castOp.getSource();
805 }
806 }
807 return operand;
808 };
809 auto newOperands =
810 llvm::map_to_vector<8>(op.getOperands(), canonicalizeOperand);
811
812 // Rewrite op if any change required.
813 if (!anyChange)
814 return failure();
815 rewriter.replaceOpWithNewOp<OpTy>(
816 op, op->getResultTypes(), newOperands, op.getProperties(),
817 op->getDiscardableAttrDictionary().getValue());
818 return success();
819 }
820};
821
822struct BroadcastConcretizeResultTypePattern
823 : public OpRewritePattern<BroadcastOp> {
824 using OpRewritePattern<BroadcastOp>::OpRewritePattern;
825
826 LogicalResult matchAndRewrite(BroadcastOp op,
827 PatternRewriter &rewriter) const override {
828 // Only concretize dynamic extent tensor result types.
829 auto resultTy = llvm::dyn_cast<RankedTensorType>(op.getType());
830 if (!resultTy || !resultTy.isDynamicDim(0))
831 return failure();
832
833 // Infer resulting shape rank if possible.
834 int64_t maxRank = 0;
835 for (Value shape : op.getShapes()) {
836 if (auto extentTensorTy =
837 llvm::dyn_cast<RankedTensorType>(shape.getType())) {
838 // Cannot infer resulting shape rank if any operand is dynamically
839 // ranked.
840 if (extentTensorTy.isDynamicDim(0))
841 return failure();
842 maxRank = std::max(maxRank, extentTensorTy.getDimSize(0));
843 }
844 }
845
846 auto newOp = BroadcastOp::create(rewriter, op.getLoc(),
848 op.getShapes(), /*error=*/nullptr);
849 rewriter.replaceOpWithNewOp<tensor::CastOp>(op, op.getType(), newOp);
850 return success();
851 }
852};
853} // namespace
854
855void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
856 MLIRContext *context) {
857 patterns.add<BroadcastConcretizeResultTypePattern,
858 BroadcastFoldConstantOperandsPattern,
859 BroadcastForwardSingleOperandPattern,
860 CanonicalizeCastExtentTensorOperandsPattern<BroadcastOp>,
861 RemoveDuplicateOperandsPattern<BroadcastOp>,
862 RemoveEmptyShapeOperandsPattern<BroadcastOp>>(context);
863}
864
865//===----------------------------------------------------------------------===//
866// ConcatOp
867//===----------------------------------------------------------------------===//
868
869OpFoldResult ConcatOp::fold(FoldAdaptor adaptor) {
870 // concat with a poison operand is poison.
871 if (isa_and_present<ub::PoisonAttr>(adaptor.getLhs()) ||
872 isa_and_present<ub::PoisonAttr>(adaptor.getRhs()))
873 return ub::PoisonAttr::get(getContext());
874 auto lhs = llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getLhs());
875 auto rhs = llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getRhs());
876 if (!lhs || !rhs)
877 return nullptr;
878 auto lhsShape = llvm::to_vector<6>(lhs.getValues<int64_t>());
879 auto rhsShape = llvm::to_vector<6>(rhs.getValues<int64_t>());
880 SmallVector<int64_t, 6> resultShape;
881 resultShape.append(lhsShape.begin(), lhsShape.end());
882 resultShape.append(rhsShape.begin(), rhsShape.end());
883 Builder builder(getContext());
884 return builder.getIndexTensorAttr(resultShape);
885}
886
887//===----------------------------------------------------------------------===//
888// ConstShapeOp
889//===----------------------------------------------------------------------===//
890
891void ConstShapeOp::print(OpAsmPrinter &p) {
892 p << " ";
893 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
894 p << "[";
895 interleaveComma(getShape().getValues<int64_t>(), p);
896 p << "] : ";
897 p.printType(getType());
898}
899
900ParseResult ConstShapeOp::parse(OpAsmParser &parser, OperationState &result) {
901 if (parser.parseOptionalAttrDict(result.attributes))
902 return failure();
903 // We piggy-back on ArrayAttr parsing, though we don't internally store the
904 // shape as an ArrayAttr.
905 // TODO: Implement custom parser and maybe make syntax a bit more concise.
906 Attribute extentsRaw;
907 NamedAttrList dummy;
908 if (parser.parseAttribute(extentsRaw, "dummy", dummy))
909 return failure();
910 auto extentsArray = llvm::dyn_cast<ArrayAttr>(extentsRaw);
911 if (!extentsArray)
912 return failure();
914 for (Attribute extent : extentsArray) {
915 IntegerAttr attr = llvm::dyn_cast<IntegerAttr>(extent);
916 if (!attr)
917 return failure();
918 ints.push_back(attr.getInt());
919 }
920 Builder &builder = parser.getBuilder();
921 result.addAttribute("shape", builder.getIndexTensorAttr(ints));
922 Type resultTy;
923 if (parser.parseColonType(resultTy))
924 return failure();
925 result.types.push_back(resultTy);
926 return success();
927}
928
929OpFoldResult ConstShapeOp::fold(FoldAdaptor) { return getShapeAttr(); }
930
931void ConstShapeOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
932 MLIRContext *context) {
933 patterns.add<TensorCastConstShape>(context);
934}
935
936LogicalResult mlir::shape::ConstShapeOp::inferReturnTypes(
937 MLIRContext *context, std::optional<Location> location,
938 ConstShapeOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
939 Builder b(context);
940 const Properties prop = adaptor.getProperties();
941 inferredReturnTypes.assign({RankedTensorType::get(
942 {static_cast<int64_t>(prop.shape.size())}, b.getIndexType())});
943 return success();
944}
945
946bool mlir::shape::ConstShapeOp::isCompatibleReturnTypes(TypeRange l,
947 TypeRange r) {
948 if (l.size() != 1 || r.size() != 1)
949 return false;
950
951 Type lhs = l.front();
952 Type rhs = r.front();
953
954 if (llvm::isa<ShapeType>(lhs) || llvm::isa<ShapeType>(rhs))
955 // Shape type is compatible with all other valid return types.
956 return true;
957 return lhs == rhs;
958}
959
960//===----------------------------------------------------------------------===//
961// CstrBroadcastableOp
962//===----------------------------------------------------------------------===//
963
964void CstrBroadcastableOp::getCanonicalizationPatterns(
965 RewritePatternSet &patterns, MLIRContext *context) {
966 // Canonicalization patterns have overlap with the considerations during
967 // folding in case additional shape information is inferred at some point that
968 // does not result in folding.
969 patterns.add<CanonicalizeCastExtentTensorOperandsPattern<CstrBroadcastableOp>,
970 CstrBroadcastableEqOps,
971 RemoveDuplicateOperandsPattern<CstrBroadcastableOp>,
972 RemoveEmptyShapeOperandsPattern<CstrBroadcastableOp>>(context);
973}
974
975// Return true if there is exactly one attribute not representing a scalar
976// broadcast.
978 bool nonScalarSeen = false;
979 for (Attribute a : attributes) {
980 // Treat non-constant and poison operands as potentially non-scalar.
981 auto dense = llvm::dyn_cast_if_present<DenseIntElementsAttr>(a);
982 if (!dense || dense.getNumElements() != 0) {
983 if (nonScalarSeen)
984 return false;
985 nonScalarSeen = true;
986 }
987 }
988 return true;
989}
990
991OpFoldResult CstrBroadcastableOp::fold(FoldAdaptor adaptor) {
992 // No broadcasting is needed if all operands but one are scalar.
993 if (hasAtMostSingleNonScalar(adaptor.getShapes()))
994 return BoolAttr::get(getContext(), true);
995
996 if ([&] {
998 for (const auto &operand : adaptor.getShapes()) {
999 auto dense = llvm::dyn_cast_if_present<DenseIntElementsAttr>(operand);
1000 if (!dense)
1001 return false;
1002 extents.push_back(llvm::to_vector<6>(dense.getValues<int64_t>()));
1003 }
1005 }())
1006 return BoolAttr::get(getContext(), true);
1007
1008 // Lastly, see if folding can be completed based on what constraints are known
1009 // on the input shapes.
1010 if ([&] {
1012 for (auto shapeValue : getShapes()) {
1013 extents.emplace_back();
1014 if (failed(getShapeVec(shapeValue, extents.back())))
1015 return false;
1016 }
1018 }())
1019 return BoolAttr::get(getContext(), true);
1020
1021 // Because a failing witness result here represents an eventual assertion
1022 // failure, we do not replace it with a constant witness.
1023 return nullptr;
1024}
1025
1026LogicalResult CstrBroadcastableOp::verify() {
1027 // Ensure that CstrBroadcastableOp contains at least two operands
1028 if (getNumOperands() < 2)
1029 return emitOpError("required at least 2 input shapes");
1030 return success();
1031}
1032
1033//===----------------------------------------------------------------------===//
1034// CstrEqOp
1035//===----------------------------------------------------------------------===//
1036
1037void CstrEqOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1038 MLIRContext *context) {
1039 // If inputs are equal, return passing witness
1040 patterns.add<CstrEqEqOps>(context);
1041}
1042
1043OpFoldResult CstrEqOp::fold(FoldAdaptor adaptor) {
1044 if (llvm::all_of(adaptor.getShapes(), [&](Attribute a) {
1045 return a && a == adaptor.getShapes().front();
1046 }))
1047 return BoolAttr::get(getContext(), true);
1048
1049 // Because a failing witness result here represents an eventual assertion
1050 // failure, we do not try to replace it with a constant witness. Similarly, we
1051 // cannot if there are any non-const inputs.
1052 return nullptr;
1053}
1054
1055//===----------------------------------------------------------------------===//
1056// ConstSizeOp
1057//===----------------------------------------------------------------------===//
1058
1059void ConstSizeOp::build(OpBuilder &builder, OperationState &result,
1060 int64_t value) {
1061 build(builder, result, builder.getIndexAttr(value));
1062}
1063
1064OpFoldResult ConstSizeOp::fold(FoldAdaptor) { return getValueAttr(); }
1065
1066void ConstSizeOp::getAsmResultNames(
1067 llvm::function_ref<void(Value, StringRef)> setNameFn) {
1068 SmallString<4> buffer;
1069 llvm::raw_svector_ostream os(buffer);
1070 os << "c" << getValue();
1071 setNameFn(getResult(), os.str());
1072}
1073
1074//===----------------------------------------------------------------------===//
1075// ConstWitnessOp
1076//===----------------------------------------------------------------------===//
1077
1078OpFoldResult ConstWitnessOp::fold(FoldAdaptor) { return getPassingAttr(); }
1079
1080//===----------------------------------------------------------------------===//
1081// CstrRequireOp
1082//===----------------------------------------------------------------------===//
1083
1084OpFoldResult CstrRequireOp::fold(FoldAdaptor adaptor) {
1085 return adaptor.getPred();
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// DimOp
1090//===----------------------------------------------------------------------===//
1091
1092std::optional<int64_t> DimOp::getConstantIndex() {
1093 if (auto constSizeOp = getIndex().getDefiningOp<ConstSizeOp>())
1094 return constSizeOp.getValue().getLimitedValue();
1095 if (auto constantOp = getIndex().getDefiningOp<arith::ConstantOp>())
1096 return llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
1097 return std::nullopt;
1098}
1099
1100OpFoldResult DimOp::fold(FoldAdaptor adaptor) {
1101 Type valType = getValue().getType();
1102 auto valShapedType = llvm::dyn_cast<ShapedType>(valType);
1103 if (!valShapedType || !valShapedType.hasRank())
1104 return nullptr;
1105 std::optional<int64_t> index = getConstantIndex();
1106 if (!index.has_value())
1107 return nullptr;
1108 if (index.value() < 0 || index.value() >= valShapedType.getRank())
1109 return nullptr;
1110 auto extent = valShapedType.getDimSize(*index);
1111 if (ShapedType::isDynamic(extent))
1112 return nullptr;
1113 return IntegerAttr::get(IndexType::get(getContext()), extent);
1114}
1115
1116LogicalResult mlir::shape::DimOp::inferReturnTypes(
1117 MLIRContext *context, std::optional<Location> location,
1118 DimOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1119 inferredReturnTypes.assign({adaptor.getIndex().getType()});
1120 return success();
1121}
1122
1123bool mlir::shape::DimOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1125}
1126
1127//===----------------------------------------------------------------------===//
1128// DivOp
1129//===----------------------------------------------------------------------===//
1130
1131OpFoldResult DivOp::fold(FoldAdaptor adaptor) {
1132 auto lhs = llvm::dyn_cast_if_present<IntegerAttr>(adaptor.getLhs());
1133 if (!lhs)
1134 return nullptr;
1135 auto rhs = llvm::dyn_cast_if_present<IntegerAttr>(adaptor.getRhs());
1136 if (!rhs || rhs.getValue().isZero())
1137 return nullptr;
1138
1139 // Division in APInt does not follow floor(lhs, rhs) when the result is
1140 // negative. Rather, APInt rounds toward zero.
1141 APInt quotient, remainder;
1142 APInt::sdivrem(lhs.getValue(), rhs.getValue(), quotient, remainder);
1143 if (quotient.isNegative() && !remainder.isZero()) {
1144 quotient -= 1;
1145 }
1146
1147 Type indexTy = IndexType::get(getContext());
1148 return IntegerAttr::get(indexTy, quotient);
1149}
1150
1151LogicalResult mlir::shape::DivOp::inferReturnTypes(
1152 MLIRContext *context, std::optional<Location> location,
1153 DivOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1154 if (llvm::isa<SizeType>(adaptor.getLhs().getType()) ||
1155 llvm::isa<SizeType>(adaptor.getRhs().getType()))
1156 inferredReturnTypes.assign({SizeType::get(context)});
1157 else
1158 inferredReturnTypes.assign({IndexType::get(context)});
1159 return success();
1160}
1161
1162bool mlir::shape::DivOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1163 // SizeType is compatible with IndexType.
1165}
1166
1167LogicalResult DivOp::verify() { return verifySizeOrIndexOp(*this); }
1168
1169//===----------------------------------------------------------------------===//
1170// ShapeEqOp
1171//===----------------------------------------------------------------------===//
1172
1173OpFoldResult ShapeEqOp::fold(FoldAdaptor adaptor) {
1174 bool allSame = true;
1175 if (!adaptor.getShapes().empty() && !adaptor.getShapes().front())
1176 return {};
1177 for (Attribute operand : adaptor.getShapes().drop_front()) {
1178 if (!operand)
1179 return {};
1180 allSame = allSame && operand == adaptor.getShapes().front();
1181 }
1182 return BoolAttr::get(getContext(), allSame);
1183}
1184
1185//===----------------------------------------------------------------------===//
1186// IndexToSizeOp
1187//===----------------------------------------------------------------------===//
1188
1189OpFoldResult IndexToSizeOp::fold(FoldAdaptor adaptor) {
1190 // Constant values of both types, `shape.size` and `index`, are represented as
1191 // `IntegerAttr`s which makes constant folding simple.
1192 if (Attribute arg = adaptor.getArg())
1193 return arg;
1194 return {};
1195}
1196
1197void IndexToSizeOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1198 MLIRContext *context) {
1199 patterns.add<SizeToIndexToSizeCanonicalization>(context);
1200}
1201
1202//===----------------------------------------------------------------------===//
1203// FromExtentsOp
1204//===----------------------------------------------------------------------===//
1205
1206OpFoldResult FromExtentsOp::fold(FoldAdaptor adaptor) {
1208 for (Attribute attr : adaptor.getExtents()) {
1209 auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr);
1210 if (!intAttr)
1211 return nullptr;
1212 extents.push_back(intAttr.getInt());
1213 }
1214 Builder builder(getContext());
1215 return builder.getIndexTensorAttr(extents);
1216}
1217
1218//===----------------------------------------------------------------------===//
1219// FunctionLibraryOp
1220//===----------------------------------------------------------------------===//
1221
1222void FunctionLibraryOp::build(OpBuilder &builder, OperationState &result,
1223 StringRef name) {
1224 result.getOrAddProperties<Properties>().sym_name =
1225 builder.getStringAttr(name);
1226}
1227
1228FuncOp FunctionLibraryOp::getShapeFunction(Operation *op) {
1229 auto attr = llvm::dyn_cast_or_null<FlatSymbolRefAttr>(
1230 getMapping().get(op->getName().getIdentifier()));
1231 if (!attr)
1232 return nullptr;
1233 return lookupSymbol<FuncOp>(attr);
1234}
1235
1236ParseResult FunctionLibraryOp::parse(OpAsmParser &parser,
1238 // Parse the op name.
1239 StringAttr nameAttr;
1240 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(result.name),
1241 result.attributes))
1242 return failure();
1243
1244 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1245 return failure();
1246
1247 auto *bodyRegion = result.addRegion();
1248 if (parser.parseRegion(*bodyRegion))
1249 return failure();
1250
1251 if (parser.parseKeyword("mapping"))
1252 return failure();
1253
1254 DictionaryAttr mappingAttr;
1255 if (parser.parseAttribute(mappingAttr,
1256 parser.getBuilder().getType<NoneType>(), "mapping",
1257 result.attributes))
1258 return failure();
1259 return success();
1260}
1261
1262void FunctionLibraryOp::print(OpAsmPrinter &p) {
1263 p << ' ';
1264 p.printSymbolName(getName());
1266 (*this)->getDiscardableAttrDictionary().getValue());
1267 p << ' ';
1268 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
1269 /*printBlockTerminators=*/false);
1270 p << " mapping ";
1271 p.printAttributeWithoutType(getMappingAttr());
1272}
1273
1274//===----------------------------------------------------------------------===//
1275// FuncOp
1276//===----------------------------------------------------------------------===//
1277
1278FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
1280 OpBuilder builder(location->getContext());
1281 OperationState state(location, getOperationName());
1282 FuncOp::build(builder, state, name, type, attrs);
1283 return cast<FuncOp>(Operation::create(state));
1284}
1285FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
1287 SmallVector<NamedAttribute, 8> attrRef(attrs);
1288 return create(location, name, type, llvm::ArrayRef(attrRef));
1289}
1290FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
1292 ArrayRef<DictionaryAttr> argAttrs) {
1293 FuncOp func = create(location, name, type, attrs);
1294 func.setAllArgAttrs(argAttrs);
1295 return func;
1296}
1297
1298void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name,
1299 FunctionType type, ArrayRef<NamedAttribute> attrs,
1300 ArrayRef<DictionaryAttr> argAttrs) {
1301 state.addAttribute(FuncOp::getSymNameAttrName(state.name),
1302 builder.getStringAttr(name));
1303 state.addAttribute(FuncOp::getFunctionTypeAttrName(state.name),
1304 TypeAttr::get(type));
1305 state.attributes.append(attrs.begin(), attrs.end());
1306 state.addRegion();
1307
1308 if (argAttrs.empty())
1309 return;
1310 assert(type.getNumInputs() == argAttrs.size());
1312 builder, state, argAttrs, /*resultAttrs=*/{},
1313 getArgAttrsAttrName(state.name), getResAttrsAttrName(state.name));
1314}
1315
1316ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
1317 auto buildFuncType =
1318 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
1320 std::string &) { return builder.getFunctionType(argTypes, results); };
1321
1323 parser, result, /*allowVariadic=*/false,
1324 getFunctionTypeAttrName(result.name), buildFuncType,
1325 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
1326}
1327
1328void FuncOp::print(OpAsmPrinter &p) {
1330 p, *this, /*isVariadic=*/false, getFunctionTypeAttrName(),
1331 getArgAttrsAttrName(), getResAttrsAttrName());
1332}
1333
1334//===----------------------------------------------------------------------===//
1335// GetExtentOp
1336//===----------------------------------------------------------------------===//
1337
1338std::optional<int64_t> GetExtentOp::getConstantDim() {
1339 if (auto constSizeOp = getDim().getDefiningOp<ConstSizeOp>())
1340 return constSizeOp.getValue().getLimitedValue();
1341 if (auto constantOp = getDim().getDefiningOp<arith::ConstantOp>())
1342 return llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
1343 return std::nullopt;
1344}
1345
1346OpFoldResult GetExtentOp::fold(FoldAdaptor adaptor) {
1347 auto elements =
1348 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getShape());
1349 if (!elements)
1350 return nullptr;
1351 std::optional<int64_t> dim = getConstantDim();
1352 if (!dim.has_value())
1353 return nullptr;
1354 if (dim.value() >= elements.getNumElements())
1355 return nullptr;
1356 if (dim.value() < 0)
1357 return nullptr;
1358 return elements.getValues<Attribute>()[(uint64_t)dim.value()];
1359}
1360
1361void GetExtentOp::build(OpBuilder &builder, OperationState &result, Value shape,
1362 int64_t dim) {
1363 auto loc = result.location;
1364 auto dimAttr = builder.getIndexAttr(dim);
1365 if (llvm::isa<ShapeType>(shape.getType())) {
1366 Value dim = ConstSizeOp::create(builder, loc, dimAttr);
1367 build(builder, result, builder.getType<SizeType>(), shape, dim);
1368 } else {
1369 Value dim = arith::ConstantOp::create(builder, loc, builder.getIndexType(),
1370 dimAttr);
1371 build(builder, result, builder.getIndexType(), shape, dim);
1372 }
1373}
1374
1375LogicalResult mlir::shape::GetExtentOp::inferReturnTypes(
1376 MLIRContext *context, std::optional<Location> location,
1377 GetExtentOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1378 inferredReturnTypes.assign({IndexType::get(context)});
1379 return success();
1380}
1381
1382bool mlir::shape::GetExtentOp::isCompatibleReturnTypes(TypeRange l,
1383 TypeRange r) {
1384 // SizeType is compatible with IndexType.
1386}
1387
1388LogicalResult GetExtentOp::verify() { return verifySizeOrIndexOp(*this); }
1389
1390//===----------------------------------------------------------------------===//
1391// IsBroadcastableOp
1392//===----------------------------------------------------------------------===//
1393
1394void IsBroadcastableOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1395 MLIRContext *context) {
1396 patterns.add<RemoveDuplicateOperandsPattern<IsBroadcastableOp>>(context);
1397}
1398
1399OpFoldResult IsBroadcastableOp::fold(FoldAdaptor adaptor) {
1400 // Can always broadcast fewer than two shapes.
1401 if (adaptor.getShapes().size() < 2) {
1402 return BoolAttr::get(getContext(), true);
1403 }
1404
1405 return nullptr;
1406}
1407
1408//===----------------------------------------------------------------------===//
1409// MeetOp
1410//===----------------------------------------------------------------------===//
1411
1412LogicalResult mlir::shape::MeetOp::inferReturnTypes(
1413 MLIRContext *context, std::optional<Location> location,
1414 MeetOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1415 if (adaptor.getOperands().empty())
1416 return failure();
1417
1418 auto isShapeType = [](Type arg) {
1419 if (llvm::isa<ShapeType>(arg))
1420 return true;
1421 return isExtentTensorType(arg);
1422 };
1423
1424 ValueRange::type_range types = adaptor.getOperands().getTypes();
1425 Type acc = types.front();
1426 for (auto t : drop_begin(types)) {
1427 Type l = acc, r = t;
1428 if (!llvm::isa<ShapeType, SizeType>(l))
1429 std::swap(l, r);
1430
1431 // Handle sizes, propagate error type if present.
1432 if (llvm::isa<SizeType>(l)) {
1433 if (llvm::isa<SizeType, IndexType>(r))
1434 acc = l;
1435 else
1436 return emitOptionalError(location, "requires all sizes or shapes");
1437 } else if (llvm::isa<IndexType>(l)) {
1438 if (llvm::isa<IndexType>(r))
1439 acc = r;
1440 else
1441 return emitOptionalError(location, "requires all sizes or shapes");
1442 } else if (llvm::isa<ShapeType>(l)) {
1443 // Handle shapes, propagate error type if present.
1444 if (isShapeType(r))
1445 acc = l;
1446 else
1447 return emitOptionalError(location, "requires all sizes or shapes");
1448 } else if (isExtentTensorType(l)) {
1449 auto rank1 = llvm::cast<RankedTensorType>(l).getShape()[0];
1450 auto rank2 = llvm::cast<RankedTensorType>(r).getShape()[0];
1451 if (ShapedType::isDynamic(rank1))
1452 acc = l;
1453 else if (ShapedType::isDynamic(rank2))
1454 acc = r;
1455 else if (rank1 != rank2)
1456 return emitOptionalError(location, "unequal shape cardinality");
1457 else
1458 acc = l;
1459 }
1460 }
1461 inferredReturnTypes.assign({acc});
1462 return success();
1463}
1464
1465bool mlir::shape::MeetOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1466 if (l.size() != 1 || r.size() != 1)
1467 return false;
1468 if (l == r)
1469 return true;
1470
1471 Type lhs = l.front();
1472 Type rhs = r.front();
1473
1474 if (!llvm::isa<ShapeType, SizeType>(lhs))
1475 std::swap(lhs, rhs);
1476
1477 if (llvm::isa<SizeType>(lhs))
1478 return llvm::isa<SizeType, IndexType>(rhs);
1479 if (llvm::isa<ShapeType>(lhs))
1480 return llvm::isa<ShapeType, TensorType>(rhs);
1481
1482 if (succeeded(verifyCompatibleShapes({lhs, rhs})))
1483 return true;
1484 return false;
1485}
1486
1487//===----------------------------------------------------------------------===//
1488// RankOp
1489//===----------------------------------------------------------------------===//
1490
1491OpFoldResult shape::RankOp::fold(FoldAdaptor adaptor) {
1492 auto shape =
1493 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getShape());
1494 if (!shape)
1495 return {};
1496 int64_t rank = shape.getNumElements();
1497 Builder builder(getContext());
1498 return builder.getIndexAttr(rank);
1499}
1500
1501/// Evaluate the `rank` operation for shapes of ranked tensors at compile time.
1502/// Constant folding fails in cases where only the rank is constant, not the
1503/// shape itself.
1504/// This canonicalization matches `shape.rank(shape.shape_of(%ranked_tensor))`.
1505///
1506/// Example:
1507///
1508/// %shape = shape.shape_of %ranked_tensor : tensor<1x2x?xf32>
1509/// %rank = shape.rank %shape
1510///
1511/// becomes
1512///
1513/// %rank = shape.const_size 3
1514
1515namespace {
1516struct RankShapeOfCanonicalizationPattern
1517 : public OpRewritePattern<shape::RankOp> {
1518 using OpRewritePattern<shape::RankOp>::OpRewritePattern;
1519
1520 LogicalResult matchAndRewrite(shape::RankOp op,
1521 PatternRewriter &rewriter) const override {
1522 auto shapeOfOp = op.getShape().getDefiningOp<ShapeOfOp>();
1523 if (!shapeOfOp)
1524 return failure();
1525 auto rankedTensorType =
1526 llvm::dyn_cast<RankedTensorType>(shapeOfOp.getArg().getType());
1527 if (!rankedTensorType)
1528 return failure();
1529 int64_t rank = rankedTensorType.getRank();
1530 if (llvm::isa<IndexType>(op.getType())) {
1531 rewriter.replaceOpWithNewOp<arith::ConstantIndexOp>(op.getOperation(),
1532 rank);
1533 } else if (llvm::isa<shape::SizeType>(op.getType())) {
1534 rewriter.replaceOpWithNewOp<shape::ConstSizeOp>(op.getOperation(), rank);
1535 } else {
1536 return failure();
1537 }
1538 return success();
1539 }
1540};
1541} // namespace
1542
1543void shape::RankOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1544 MLIRContext *context) {
1545 patterns.add<RankShapeOfCanonicalizationPattern>(context);
1546}
1547
1548LogicalResult mlir::shape::RankOp::inferReturnTypes(
1549 MLIRContext *context, std::optional<Location> location,
1550 RankOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1551 if (llvm::isa<ShapeType>(adaptor.getShape().getType()))
1552 inferredReturnTypes.assign({SizeType::get(context)});
1553 else
1554 inferredReturnTypes.assign({IndexType::get(context)});
1555 return success();
1556}
1557
1558bool mlir::shape::RankOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1559 // SizeType is compatible with IndexType.
1561}
1562
1563LogicalResult shape::RankOp::verify() { return verifySizeOrIndexOp(*this); }
1564
1565//===----------------------------------------------------------------------===//
1566// NumElementsOp
1567//===----------------------------------------------------------------------===//
1568
1569OpFoldResult NumElementsOp::fold(FoldAdaptor adaptor) {
1570 // num_elements of poison shape is poison.
1571 if (isa_and_present<ub::PoisonAttr>(adaptor.getShape()))
1572 return ub::PoisonAttr::get(getContext());
1573
1574 // Fold only when argument constant.
1575 auto shape =
1576 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getShape());
1577 if (!shape)
1578 return {};
1579
1580 APInt product(64, 1);
1581 for (auto value : shape)
1582 product *= value;
1583 Builder builder(getContext());
1584 return builder.getIndexAttr(product.getLimitedValue());
1585}
1586
1587LogicalResult mlir::shape::NumElementsOp::inferReturnTypes(
1588 MLIRContext *context, std::optional<Location> location,
1589 NumElementsOp::Adaptor adaptor,
1590 SmallVectorImpl<Type> &inferredReturnTypes) {
1591 if (llvm::isa<ShapeType>(adaptor.getShape().getType()))
1592 inferredReturnTypes.assign({SizeType::get(context)});
1593 else
1594 inferredReturnTypes.assign({IndexType::get(context)});
1595 return success();
1596}
1597
1598bool mlir::shape::NumElementsOp::isCompatibleReturnTypes(TypeRange l,
1599 TypeRange r) {
1600 // SizeType is compatible with IndexType.
1602}
1603
1604LogicalResult shape::NumElementsOp::verify() {
1605 return verifySizeOrIndexOp(*this);
1606}
1607
1608//===----------------------------------------------------------------------===//
1609// MaxOp
1610//===----------------------------------------------------------------------===//
1611
1612OpFoldResult MaxOp::fold(FoldAdaptor adaptor) {
1613 // If operands are equal, just propagate one.
1614 if (getLhs() == getRhs())
1615 return getLhs();
1616 return nullptr;
1617}
1618
1619LogicalResult mlir::shape::MaxOp::inferReturnTypes(
1620 MLIRContext *context, std::optional<Location> location,
1621 MaxOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1622 if (adaptor.getLhs().getType() == adaptor.getRhs().getType())
1623 inferredReturnTypes.assign({adaptor.getLhs().getType()});
1624 else
1625 inferredReturnTypes.assign({SizeType::get(context)});
1626 return success();
1627}
1628
1629bool mlir::shape::MaxOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1630 if (l.size() != 1 || r.size() != 1)
1631 return false;
1632 if (llvm::isa<ShapeType>(l.front()) && llvm::isa<ShapeType>(r.front()))
1633 return true;
1634 if (llvm::isa<SizeType>(l.front()) && llvm::isa<SizeType>(r.front()))
1635 return true;
1636 return false;
1637}
1638
1639//===----------------------------------------------------------------------===//
1640// MinOp
1641//===----------------------------------------------------------------------===//
1642
1643OpFoldResult MinOp::fold(FoldAdaptor adaptor) {
1644 // If operands are equal, just propagate one.
1645 if (getLhs() == getRhs())
1646 return getLhs();
1647 return nullptr;
1648}
1649
1650LogicalResult mlir::shape::MinOp::inferReturnTypes(
1651 MLIRContext *context, std::optional<Location> location,
1652 MinOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1653 if (adaptor.getLhs().getType() == adaptor.getRhs().getType())
1654 inferredReturnTypes.assign({adaptor.getLhs().getType()});
1655 else
1656 inferredReturnTypes.assign({SizeType::get(context)});
1657 return success();
1658}
1659
1660bool mlir::shape::MinOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1661 if (l.size() != 1 || r.size() != 1)
1662 return false;
1663 if (llvm::isa<ShapeType>(l.front()) && llvm::isa<ShapeType>(r.front()))
1664 return true;
1665 if (llvm::isa<SizeType>(l.front()) && llvm::isa<SizeType>(r.front()))
1666 return true;
1667 return false;
1668}
1669
1670//===----------------------------------------------------------------------===//
1671// MulOp
1672//===----------------------------------------------------------------------===//
1673
1674OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
1675 auto lhs = llvm::dyn_cast_if_present<IntegerAttr>(adaptor.getLhs());
1676 if (!lhs)
1677 return nullptr;
1678 auto rhs = llvm::dyn_cast_if_present<IntegerAttr>(adaptor.getRhs());
1679 if (!rhs)
1680 return nullptr;
1681 APInt folded = lhs.getValue() * rhs.getValue();
1682 Type indexTy = IndexType::get(getContext());
1683 return IntegerAttr::get(indexTy, folded);
1684}
1685
1686LogicalResult mlir::shape::MulOp::inferReturnTypes(
1687 MLIRContext *context, std::optional<Location> location,
1688 MulOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1689 if (llvm::isa<SizeType>(adaptor.getLhs().getType()) ||
1690 llvm::isa<SizeType>(adaptor.getRhs().getType()))
1691 inferredReturnTypes.assign({SizeType::get(context)});
1692 else
1693 inferredReturnTypes.assign({IndexType::get(context)});
1694 return success();
1695}
1696
1697bool mlir::shape::MulOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1698 // SizeType is compatible with IndexType.
1700}
1701
1702LogicalResult shape::MulOp::verify() { return verifySizeOrIndexOp(*this); }
1703
1704//===----------------------------------------------------------------------===//
1705// ShapeOfOp
1706//===----------------------------------------------------------------------===//
1707
1708namespace {
1709/// Replace shape_of(x) where x has a constant shape with a const_shape op.
1710struct ShapeOfOpToConstShapeOp : public OpRewritePattern<shape::ShapeOfOp> {
1711 using OpRewritePattern<shape::ShapeOfOp>::OpRewritePattern;
1712
1713 LogicalResult matchAndRewrite(shape::ShapeOfOp op,
1714 PatternRewriter &rewriter) const override {
1715 auto type = llvm::dyn_cast<ShapedType>(op.getArg().getType());
1716 if (!type || !type.hasStaticShape())
1717 return failure();
1718
1719 Type resultType = op.getResult().getType();
1720 Location loc = op.getLoc();
1721 Type constResType =
1722 isa<ShapeType>(resultType)
1723 ? resultType
1724 : RankedTensorType::get({type.getRank()}, rewriter.getIndexType());
1725 Value constShape =
1726 ConstShapeOp::create(rewriter, loc, constResType,
1727 rewriter.getIndexTensorAttr(type.getShape()))
1728 .getResult();
1729 if (constShape.getType() != resultType)
1730 constShape =
1731 tensor::CastOp::create(rewriter, loc, resultType, constShape);
1732 rewriter.replaceOp(op, constShape);
1733 return success();
1734 }
1735};
1736
1737// Canonicalize
1738//
1739// %0 = tensor.reshape %input(%shape) : (tensor<*xf32>, tensor<?xindex>) ->
1740// tensor<*xf32>
1741// %1 = shape.shape_of %0 : tensor<*xf32> -> tensor<?xindex>
1742//
1743// to
1744//
1745// %0 = tensor.reshape %input(%shape) : (tensor<*xf32>, tensor<?xindex>) ->
1746// tensor<*xf32>
1747// %1 = %shape
1748//
1749struct ShapeOfFromReshape : public OpRewritePattern<shape::ShapeOfOp> {
1750 using OpRewritePattern<shape::ShapeOfOp>::OpRewritePattern;
1751
1752 LogicalResult matchAndRewrite(shape::ShapeOfOp op,
1753 PatternRewriter &rewriter) const override {
1754 auto tensorReshapeOp = op.getArg().getDefiningOp<tensor::ReshapeOp>();
1755 if (!tensorReshapeOp)
1756 return rewriter.notifyMatchFailure(op, "producer is not tensor.reshape");
1757 if (!isa<TensorType>(op.getType()))
1758 return rewriter.notifyMatchFailure(op, "result is not a tensor");
1759
1760 // Operand 'shape' of 'tensor.reshape' may now be used as the result of
1761 // 'shape.shape_of'. While its type is guaranteed to be compatible in well-
1762 // formed IR, it may not be identical (dynamically vs statically shaped),
1763 // in which case it needs to be cast first using 'tensor.cast'.
1764 // Additionally, it may not have identical element type (i32 vs index)
1765 // while it has identical shaped type (dynamic vs static), in which case it
1766 // needs to be cast first using 'arith.index_cast'. Note: 'shape.shape_of'
1767 // op result must be shape or extent tensor.
1768 Value shape = tensorReshapeOp.getShape();
1769
1770 auto opTensorTy = cast<RankedTensorType>(op.getType());
1771 auto shapeTensorTy = cast<RankedTensorType>(shape.getType());
1772
1773 if (opTensorTy != shapeTensorTy) {
1774 if (opTensorTy.getElementType() == shapeTensorTy.getElementType())
1775 shape =
1776 tensor::CastOp::create(rewriter, op.getLoc(), opTensorTy, shape);
1777 else if (!isExtentTensorType(shapeTensorTy))
1778 shape = arith::IndexCastOp::create(rewriter, op.getLoc(), opTensorTy,
1779 shape);
1780 }
1781
1782 rewriter.replaceOp(op, shape);
1783 return success();
1784 }
1785};
1786
1787// Canonicalize
1788// ```
1789// %0 = shape.shape_of %arg : tensor<?x?x?xf32> -> tensor<3xindex>
1790// %1 = tensor.cast %0 : tensor<3xindex> to tensor<?xindex>
1791// ```
1792// to
1793// ```
1794// %1 = shape.shape_of %arg : tensor<?x?x?xf32> -> tensor<?xindex>
1795// ```
1796struct ShapeOfCastExtentTensor : public OpRewritePattern<tensor::CastOp> {
1797 using OpRewritePattern<tensor::CastOp>::OpRewritePattern;
1798
1799 LogicalResult matchAndRewrite(tensor::CastOp op,
1800 PatternRewriter &rewriter) const override {
1801 auto ty = llvm::dyn_cast<RankedTensorType>(op.getType());
1802 if (!ty || ty.getRank() != 1)
1803 return failure();
1804
1805 auto shapeOfOp = op.getSource().getDefiningOp<ShapeOfOp>();
1806 if (!shapeOfOp)
1807 return failure();
1808
1809 // Argument type must be ranked and must not conflict.
1810 auto argTy = llvm::dyn_cast<RankedTensorType>(shapeOfOp.getArg().getType());
1811 if (!argTy || (!ty.isDynamicDim(0) && ty.getDimSize(0) != argTy.getRank()))
1812 return failure();
1813
1814 rewriter.replaceOpWithNewOp<ShapeOfOp>(op, ty, shapeOfOp.getArg());
1815 return success();
1816 }
1817};
1818} // namespace
1819
1820void ShapeOfOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1821 MLIRContext *context) {
1822 patterns.add<ShapeOfCastExtentTensor, ShapeOfFromReshape,
1823 ExtractFromShapeOfExtentTensor, ShapeOfOpToConstShapeOp>(
1824 context);
1825}
1826
1827LogicalResult mlir::shape::ShapeOfOp::inferReturnTypes(
1828 MLIRContext *context, std::optional<Location> location,
1829 ShapeOfOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
1830 if (llvm::isa<ValueShapeType>(adaptor.getArg().getType()))
1831 inferredReturnTypes.assign({ShapeType::get(context)});
1832 else {
1833 auto shapedTy = llvm::cast<ShapedType>(adaptor.getArg().getType());
1834 int64_t rank =
1835 shapedTy.hasRank() ? shapedTy.getRank() : ShapedType::kDynamic;
1836 Type indexTy = IndexType::get(context);
1837 Type extentTensorTy = RankedTensorType::get({rank}, indexTy);
1838 inferredReturnTypes.assign({extentTensorTy});
1839 }
1840 return success();
1841}
1842
1843bool mlir::shape::ShapeOfOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1844 if (l.size() != 1 || r.size() != 1)
1845 return false;
1846 if (l == r)
1847 return true;
1848
1849 Type lhs = l.front();
1850 Type rhs = r.front();
1851
1852 if (!llvm::isa<ShapeType, ShapedType>(lhs) ||
1853 !llvm::isa<ShapeType, ShapedType>(rhs))
1854 return false;
1855
1856 if (llvm::isa<ShapeType>(lhs) || llvm::isa<ShapeType>(rhs))
1857 // Shape type is compatible with all other valid return types.
1858 return true;
1859
1860 if (succeeded(verifyCompatibleShapes({lhs, rhs})))
1861 return true;
1862 return false;
1863}
1864
1865LogicalResult shape::ShapeOfOp::verify() {
1866 return verifyShapeOrExtentTensorOp(*this);
1867}
1868
1869//===----------------------------------------------------------------------===//
1870// SizeToIndexOp
1871//===----------------------------------------------------------------------===//
1872
1873OpFoldResult SizeToIndexOp::fold(FoldAdaptor adaptor) {
1874 // Constant values of both types, `shape.size` and `index`, are represented as
1875 // `IntegerAttr`s which makes constant folding simple.
1876 if (Attribute arg = adaptor.getArg())
1877 return arg;
1878 return OpFoldResult();
1879}
1880
1881void SizeToIndexOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1882 MLIRContext *context) {
1883 patterns.add<IndexToSizeToIndexCanonicalization>(context);
1884}
1885
1886bool SizeToIndexOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
1887 if (inputs.size() != 1 || outputs.size() != 1)
1888 return false;
1889 return llvm::isa<IndexType, SizeType>(inputs[0]) &&
1890 llvm::isa<IndexType>(outputs[0]);
1891}
1892
1893//===----------------------------------------------------------------------===//
1894// YieldOp
1895//===----------------------------------------------------------------------===//
1896
1897LogicalResult shape::YieldOp::verify() {
1898 auto *parentOp = (*this)->getParentOp();
1899 auto results = parentOp->getResults();
1900 auto operands = getOperands();
1901
1902 if (parentOp->getNumResults() != getNumOperands())
1903 return emitOpError() << "number of operands does not match number of "
1904 "results of its parent";
1905 for (auto e : llvm::zip(results, operands))
1906 if (std::get<0>(e).getType() != std::get<1>(e).getType())
1907 return emitOpError() << "types mismatch between yield op and its parent";
1908
1909 return success();
1910}
1911
1912//===----------------------------------------------------------------------===//
1913// SplitAtOp
1914//===----------------------------------------------------------------------===//
1915
1916LogicalResult SplitAtOp::fold(FoldAdaptor adaptor,
1918 // Splitting a poison shape, or at a poison index, gives two poison halves.
1919 if (isa_and_present<ub::PoisonAttr>(adaptor.getOperand()) ||
1920 isa_and_present<ub::PoisonAttr>(adaptor.getIndex())) {
1921 auto poison = ub::PoisonAttr::get(getContext());
1922 results.push_back(poison);
1923 results.push_back(poison);
1924 return success();
1925 }
1926
1927 auto shapeAttr =
1928 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getOperand());
1929 auto indexAttr = llvm::dyn_cast_if_present<IntegerAttr>(adaptor.getIndex());
1930 if (!shapeAttr || !indexAttr)
1931 return failure();
1932 auto shapeVec = llvm::to_vector<6>(shapeAttr.getValues<int64_t>());
1933 auto shape = llvm::ArrayRef(shapeVec);
1934 auto splitPoint = indexAttr.getInt();
1935 // Verify that the split point is in the correct range.
1936 // TODO: Constant fold to an "error".
1937 int64_t rank = shape.size();
1938 if (-rank > splitPoint || splitPoint > rank)
1939 return failure();
1940 if (splitPoint < 0)
1941 splitPoint += shape.size();
1942 Builder builder(adaptor.getOperand().getContext());
1943 results.push_back(builder.getIndexTensorAttr(shape.take_front(splitPoint)));
1944 results.push_back(builder.getIndexTensorAttr(shape.drop_front(splitPoint)));
1945 return success();
1946}
1947
1948//===----------------------------------------------------------------------===//
1949// ToExtentTensorOp
1950//===----------------------------------------------------------------------===//
1951
1952OpFoldResult ToExtentTensorOp::fold(FoldAdaptor adaptor) {
1953 // to_extent_tensor of a poison shape is poison.
1954 if (isa_and_present<ub::PoisonAttr>(adaptor.getInput()))
1955 return ub::PoisonAttr::get(getContext());
1956
1957 auto inputAttr =
1958 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getInput());
1959 if (!inputAttr)
1960 return OpFoldResult();
1961 Builder builder(getContext());
1962 auto shape = llvm::to_vector<6>(inputAttr.getValues<int64_t>());
1963 auto type = RankedTensorType::get({static_cast<int64_t>(shape.size())},
1964 builder.getIndexType());
1965 return DenseIntElementsAttr::get(type, shape);
1966}
1967
1968bool ToExtentTensorOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
1969 if (inputs.size() != 1 || outputs.size() != 1)
1970 return false;
1971 if (auto inputTensor = llvm::dyn_cast<RankedTensorType>(inputs[0])) {
1972 if (!llvm::isa<IndexType>(inputTensor.getElementType()) ||
1973 inputTensor.getRank() != 1)
1974 return false;
1975 } else if (!llvm::isa<ShapeType>(inputs[0])) {
1976 return false;
1977 }
1978
1979 TensorType outputTensor = llvm::dyn_cast<TensorType>(outputs[0]);
1980 return outputTensor && llvm::isa<IndexType>(outputTensor.getElementType());
1981}
1982
1983//===----------------------------------------------------------------------===//
1984// ReduceOp
1985//===----------------------------------------------------------------------===//
1986
1987void ReduceOp::build(OpBuilder &builder, OperationState &result, Value shape,
1988 ValueRange initVals) {
1989 OpBuilder::InsertionGuard g(builder);
1990 result.addOperands(shape);
1991 result.addOperands(initVals);
1992
1993 Region *bodyRegion = result.addRegion();
1994 Block *bodyBlock = builder.createBlock(
1995 bodyRegion, /*insertPt=*/{}, builder.getIndexType(), result.location);
1996
1997 Type elementType;
1998 if (auto tensorType = llvm::dyn_cast<TensorType>(shape.getType()))
1999 elementType = tensorType.getElementType();
2000 else
2001 elementType = SizeType::get(builder.getContext());
2002 bodyBlock->addArgument(elementType, shape.getLoc());
2003
2004 for (Value initVal : initVals) {
2005 bodyBlock->addArgument(initVal.getType(), initVal.getLoc());
2006 result.addTypes(initVal.getType());
2007 }
2008}
2009
2010LogicalResult ReduceOp::verify() {
2011 // Verify block arg types.
2012 Block &block = getRegion().front();
2013
2014 // The block takes index, extent, and aggregated values as arguments.
2015 auto blockArgsCount = getInitVals().size() + 2;
2016 if (block.getNumArguments() != blockArgsCount)
2017 return emitOpError() << "ReduceOp body is expected to have "
2018 << blockArgsCount << " arguments";
2019
2020 // The first block argument is the index and must always be of type `index`.
2021 if (!llvm::isa<IndexType>(block.getArgument(0).getType()))
2022 return emitOpError(
2023 "argument 0 of ReduceOp body is expected to be of IndexType");
2024
2025 // The second block argument is the extent and must be of type `size` or
2026 // `index`, depending on whether the reduce operation is applied to a shape or
2027 // to an extent tensor.
2028 Type extentTy = block.getArgument(1).getType();
2029 if (llvm::isa<ShapeType>(getShape().getType())) {
2030 if (!llvm::isa<SizeType>(extentTy))
2031 return emitOpError("argument 1 of ReduceOp body is expected to be of "
2032 "SizeType if the ReduceOp operates on a ShapeType");
2033 } else {
2034 if (!llvm::isa<IndexType>(extentTy))
2035 return emitOpError(
2036 "argument 1 of ReduceOp body is expected to be of IndexType if the "
2037 "ReduceOp operates on an extent tensor");
2038 }
2039
2040 for (const auto &type : llvm::enumerate(getInitVals()))
2041 if (block.getArgument(type.index() + 2).getType() != type.value().getType())
2042 return emitOpError() << "type mismatch between argument "
2043 << type.index() + 2
2044 << " of ReduceOp body and initial value "
2045 << type.index();
2046 return success();
2047}
2048
2049ParseResult ReduceOp::parse(OpAsmParser &parser, OperationState &result) {
2050 // Parse operands.
2052 Type shapeOrExtentTensorType;
2053 if (parser.parseOperandList(operands, /*requiredOperandCount=*/-1,
2055 parser.parseColonType(shapeOrExtentTensorType) ||
2056 parser.parseOptionalArrowTypeList(result.types))
2057 return failure();
2058
2059 // Resolve operands.
2060 auto initVals = llvm::ArrayRef(operands).drop_front();
2061 if (parser.resolveOperand(operands.front(), shapeOrExtentTensorType,
2062 result.operands) ||
2063 parser.resolveOperands(initVals, result.types, parser.getNameLoc(),
2064 result.operands))
2065 return failure();
2066
2067 // Parse the body.
2068 Region *body = result.addRegion();
2069 if (parser.parseRegion(*body, /*args=*/{}, /*argTypes=*/{}))
2070 return failure();
2071
2072 // Parse attributes.
2073 if (parser.parseOptionalAttrDict(result.attributes))
2074 return failure();
2075
2076 return success();
2077}
2078
2079void ReduceOp::print(OpAsmPrinter &p) {
2080 p << '(' << getShape() << ", " << getInitVals()
2081 << ") : " << getShape().getType();
2082 p.printOptionalArrowTypeList(getResultTypes());
2083 p << ' ';
2084 p.printRegion(getRegion());
2085 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
2086}
2087
2088#define GET_OP_CLASSES
2089#include "mlir/Dialect/Shape/IR/ShapeOps.cpp.inc"
2090
2091#define GET_TYPEDEF_CLASSES
2092#include "mlir/Dialect/Shape/IR/ShapeOpsTypes.cpp.inc"
return success()
static bool isErrorPropagationPossible(TypeRange operandTypes)
Definition Shape.cpp:64
static bool hasAtMostSingleNonScalar(ArrayRef< Attribute > attributes)
Definition Shape.cpp:977
static LogicalResult verifyShapeOrExtentTensorOp(Operation *op)
Definition Shape.cpp:81
static bool eachHasOnlyOneOfTypes(TypeRange typeRange)
Definition Shape.cpp:94
static LogicalResult verifySizeOrIndexOp(Operation *op)
Definition Shape.cpp:69
static int64_t product(ArrayRef< int64_t > vals)
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
@ Paren
Parens surrounding zero or more operands.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual void printType(Type type)
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
static BoolAttr get(MLIRContext *context, bool value)
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:201
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
An attribute that represents a reference to a dense integer vector or tensor object.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition Builders.h:448
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:445
This class represents a single result from folding an operation.
A trait used to provide symbol table functionalities to a region operation.
StringAttr getIdentifier() const
Return the name of this operation as a StringAttr.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
iterator_range< dialect_attr_iterator > dialect_attr_range
Definition Operation.h:688
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
operand_type_range getOperandTypes()
Definition Operation.h:424
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:65
result_type_range getResultTypes()
Definition Operation.h:455
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class represents a successor of a region.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Block * splitBlock(Block *block, Block::iterator before)
Split the operations starting at "before" (inclusive) out of the given block into a new block,...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
Type getElementType() const
Returns the element type of this tensor type.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
ValueTypeRange< ValueRange > type_range
Definition ValueRange.h:427
Type front()
Return first type in the range.
Definition TypeRange.h:164
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A named class for passing around the variadic flag.
bool staticallyKnownBroadcastable(ArrayRef< SmallVector< int64_t, 6 > > shapes)
Returns true if a broadcast between n shapes is guaranteed to be successful and not result in an erro...
Definition Traits.cpp:24
bool getBroadcastedShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2, SmallVectorImpl< int64_t > &resultShape)
Returns true and sets resultShape to the broadcasted shape from the two given shapes if they are broa...
Definition Traits.cpp:59
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
void printFunctionOp(OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic, StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName)
Printer implementation for function-like operations.
ParseResult parseFunctionOp(OpAsmParser &parser, OperationState &result, bool allowVariadic, StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder, StringAttr argAttrsName, StringAttr resAttrsName)
Parser implementation for function-like operations.
DynamicAPInt getIndex(const ConeV &cone)
Get the index of a cone, i.e., the volume of the parallelepiped spanned by its generators,...
Definition Barvinok.cpp:63
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
bool isExtentTensorType(Type)
Definition Shape.cpp:42
LogicalResult getShapeVec(Value input, SmallVectorImpl< int64_t > &shapeValues)
Definition Shape.cpp:47
RankedTensorType getExtentTensorType(MLIRContext *ctx, int64_t rank=ShapedType::kDynamic)
Alias type for extent tensors.
Definition Shape.cpp:38
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
LogicalResult verifyCompatibleShapes(TypeRange types1, TypeRange types2)
Returns success if the given two arrays have the same number of elements and each pair wise entries h...
Attribute constFoldBinaryOp(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
Definition Matchers.h:442
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.