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 
9 #include "mlir/Dialect/Shape/IR/Shape.h"
10 
11 #include "mlir/Dialect/StandardOps/IR/Ops.h"
12 #include "mlir/Dialect/Tensor/IR/Tensor.h"
13 #include "mlir/Dialect/Traits.h"
14 #include "mlir/IR/Builders.h"
15 #include "mlir/IR/BuiltinTypes.h"
16 #include "mlir/IR/DialectImplementation.h"
17 #include "mlir/IR/PatternMatch.h"
18 #include "mlir/Transforms/InliningUtils.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/TypeSwitch.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace mlir;
24 using namespace mlir::shape;
25 
26 namespace {
27 #include "ShapeCanonicalization.inc"
28 }
29 
30 RankedTensorType shape::getExtentTensorType(MLIRContext *ctx) {
31   return RankedTensorType::get({ShapedType::kDynamicSize}, IndexType::get(ctx));
32 }
33 
34 static bool isErrorPropagationPossible(TypeRange operandTypes) {
35   return llvm::any_of(operandTypes, [](Type ty) {
36     return ty.isa<SizeType, ShapeType, ValueShapeType>();
37   });
38 }
39 
40 static LogicalResult verifySizeOrIndexOp(Operation *op) {
41   assert(op != nullptr && op->getNumResults() == 1);
42   Type resultTy = op->getResultTypes().front();
43   if (isErrorPropagationPossible(op->getOperandTypes())) {
44     if (!resultTy.isa<SizeType>())
45       return op->emitOpError()
46              << "if at least one of the operands can hold error values then "
47                 "the result must be of type `size` to propagate them";
48   }
49   return success();
50 }
51 
52 static LogicalResult verifyShapeOrExtentTensorOp(Operation *op) {
53   assert(op != nullptr && op->getNumResults() == 1);
54   Type resultTy = op->getResultTypes().front();
55   if (isErrorPropagationPossible(op->getOperandTypes())) {
56     if (!resultTy.isa<ShapeType>())
57       return op->emitOpError()
58              << "if at least one of the operands can hold error values then "
59                 "the result must be of type `shape` to propagate them";
60   }
61   return success();
62 }
63 
64 //===----------------------------------------------------------------------===//
65 // InlinerInterface
66 //===----------------------------------------------------------------------===//
67 
68 namespace {
69 /// This class defines the interface for inlining shape dialect ops.
70 struct ShapeInlinerInterface : public DialectInlinerInterface {
71   using DialectInlinerInterface::DialectInlinerInterface;
72 
73   // Returns true if the given region 'src' can be inlined into the region
74   // 'dest' that is attached to an operation registered to the current dialect.
75   bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
76                        BlockAndValueMapping &) const final {
77     return true;
78   }
79 
80   // Returns true if the given operation 'op', that is registered to this
81   // dialect, can be inlined into the region 'dest' that is attached to an
82   // operation registered to the current dialect.
83   bool isLegalToInline(Operation *op, Region *dest, bool wouldBeCloned,
84                        BlockAndValueMapping &) const final {
85     return true;
86   }
87 };
88 } // namespace
89 
90 void ShapeDialect::initialize() {
91   addOperations<
92 #define GET_OP_LIST
93 #include "mlir/Dialect/Shape/IR/ShapeOps.cpp.inc"
94       >();
95   addTypes<ShapeType, SizeType, ValueShapeType, WitnessType>();
96   addInterfaces<ShapeInlinerInterface>();
97   // Allow unknown operations during prototyping and testing. As the dialect is
98   // still evolving it makes it simple to start with an unregistered ops and
99   // try different variants before actually defining the op.
100   allowUnknownOperations();
101 }
102 
103 Operation *ShapeDialect::materializeConstant(OpBuilder &builder,
104                                              Attribute value, Type type,
105                                              Location loc) {
106   if (type.isa<ShapeType>() ||
107       type == getExtentTensorType(builder.getContext()))
108     return builder.create<ConstShapeOp>(loc, type,
109                                         value.cast<DenseIntElementsAttr>());
110   if (type.isa<SizeType>())
111     return builder.create<ConstSizeOp>(loc, type, value.cast<IntegerAttr>());
112   if (type.isa<WitnessType>())
113     return builder.create<ConstWitnessOp>(loc, type, value.cast<BoolAttr>());
114   if (ConstantOp::isBuildableWith(value, type))
115     return builder.create<ConstantOp>(loc, type, value);
116   return nullptr;
117 }
118 
119 /// Parse a type registered to this dialect.
120 Type ShapeDialect::parseType(DialectAsmParser &parser) const {
121   StringRef keyword;
122   if (parser.parseKeyword(&keyword))
123     return Type();
124 
125   if (keyword == "shape")
126     return ShapeType::get(getContext());
127   if (keyword == "size")
128     return SizeType::get(getContext());
129   if (keyword == "value_shape")
130     return ValueShapeType::get(getContext());
131   if (keyword == "witness")
132     return WitnessType::get(getContext());
133 
134   parser.emitError(parser.getNameLoc(), "unknown shape type: ") << keyword;
135   return Type();
136 }
137 
138 /// Print a type registered to this dialect.
139 void ShapeDialect::printType(Type type, DialectAsmPrinter &os) const {
140   TypeSwitch<Type>(type)
141       .Case<ShapeType>([&](Type) { os << "shape"; })
142       .Case<SizeType>([&](Type) { os << "size"; })
143       .Case<ValueShapeType>([&](Type) { os << "value_shape"; })
144       .Case<WitnessType>([&](Type) { os << "witness"; })
145       .Default([](Type) { llvm_unreachable("unexpected 'shape' type kind"); });
146 }
147 
148 LogicalResult ShapeDialect::verifyOperationAttribute(Operation *op,
149                                                      NamedAttribute attribute) {
150   // Verify shape.lib attribute.
151   if (attribute.first == "shape.lib") {
152     if (!op->hasTrait<OpTrait::SymbolTable>())
153       return op->emitError(
154           "shape.lib attribute may only be on op implementing SymbolTable");
155 
156     if (auto symbolRef = attribute.second.dyn_cast<SymbolRefAttr>()) {
157       auto *symbol = SymbolTable::lookupSymbolIn(op, symbolRef);
158       if (!symbol)
159         return op->emitError("shape function library ")
160                << symbolRef << " not found";
161       return isa<shape::FunctionLibraryOp>(symbol)
162                  ? success()
163                  : op->emitError()
164                        << symbolRef << " required to be shape function library";
165     }
166 
167     if (auto arr = attribute.second.dyn_cast<ArrayAttr>()) {
168       // Verify all entries are function libraries and mappings in libraries
169       // refer to unique ops.
170       DenseSet<Identifier> key;
171       for (auto it : arr) {
172         if (!it.isa<SymbolRefAttr>())
173           return op->emitError(
174               "only SymbolRefAttr allowed in shape.lib attribute array");
175 
176         auto shapeFnLib = dyn_cast<shape::FunctionLibraryOp>(
177             SymbolTable::lookupSymbolIn(op, it.cast<SymbolRefAttr>()));
178         if (!shapeFnLib)
179           return op->emitError()
180                  << it << " does not refer to FunctionLibraryOp";
181         for (auto mapping : shapeFnLib.mapping()) {
182           if (!key.insert(mapping.first).second) {
183             return op->emitError("only one op to shape mapping allowed, found "
184                                  "multiple for `")
185                    << mapping.first << "`";
186           }
187         }
188       }
189       return success();
190     }
191 
192     return op->emitError("only SymbolRefAttr or array of SymbolRefAttrs "
193                          "allowed as shape.lib attribute");
194   }
195   return success();
196 }
197 
198 //===----------------------------------------------------------------------===//
199 // AnyOp
200 //===----------------------------------------------------------------------===//
201 
202 // TODO: Canonicalization should be implemented for shapes that can be
203 // determined through mixtures of the known dimensions of the inputs.
204 OpFoldResult AnyOp::fold(ArrayRef<Attribute> operands) {
205   // Only the last operand is checked because AnyOp is commutative.
206   if (operands.back())
207     return operands.back();
208 
209   return nullptr;
210 }
211 
212 //===----------------------------------------------------------------------===//
213 // AssumingOp
214 //===----------------------------------------------------------------------===//
215 
216 static ParseResult parseAssumingOp(OpAsmParser &parser,
217                                    OperationState &result) {
218   result.regions.reserve(1);
219   Region *doRegion = result.addRegion();
220 
221   auto &builder = parser.getBuilder();
222   OpAsmParser::OperandType cond;
223   if (parser.parseOperand(cond) ||
224       parser.resolveOperand(cond, builder.getType<WitnessType>(),
225                             result.operands))
226     return failure();
227 
228   // Parse optional results type list.
229   if (parser.parseOptionalArrowTypeList(result.types))
230     return failure();
231 
232   // Parse the region and add a terminator if elided.
233   if (parser.parseRegion(*doRegion, /*arguments=*/{}, /*argTypes=*/{}))
234     return failure();
235   AssumingOp::ensureTerminator(*doRegion, parser.getBuilder(), result.location);
236 
237   // Parse the optional attribute list.
238   if (parser.parseOptionalAttrDict(result.attributes))
239     return failure();
240   return success();
241 }
242 
243 static void print(OpAsmPrinter &p, AssumingOp op) {
244   bool yieldsResults = !op.results().empty();
245 
246   p << AssumingOp::getOperationName() << " " << op.witness();
247   if (yieldsResults) {
248     p << " -> (" << op.getResultTypes() << ")";
249   }
250   p.printRegion(op.doRegion(),
251                 /*printEntryBlockArgs=*/false,
252                 /*printBlockTerminators=*/yieldsResults);
253   p.printOptionalAttrDict(op->getAttrs());
254 }
255 
256 namespace {
257 // Removes AssumingOp with a passing witness and inlines the region.
258 struct AssumingWithTrue : public OpRewritePattern<AssumingOp> {
259   using OpRewritePattern<AssumingOp>::OpRewritePattern;
260 
261   LogicalResult matchAndRewrite(AssumingOp op,
262                                 PatternRewriter &rewriter) const override {
263     auto witness = op.witness().getDefiningOp<ConstWitnessOp>();
264     if (!witness || !witness.passingAttr())
265       return failure();
266 
267     AssumingOp::inlineRegionIntoParent(op, rewriter);
268     return success();
269   }
270 };
271 } // namespace
272 
273 void AssumingOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns,
274                                              MLIRContext *context) {
275   // If taking a passing witness, inline region.
276   patterns.insert<AssumingWithTrue>(context);
277 }
278 
279 // See RegionBranchOpInterface in Interfaces/ControlFlowInterfaces.td
280 void AssumingOp::getSuccessorRegions(
281     Optional<unsigned> index, ArrayRef<Attribute> operands,
282     SmallVectorImpl<RegionSuccessor> &regions) {
283   // AssumingOp has unconditional control flow into the region and back to the
284   // parent, so return the correct RegionSuccessor purely based on the index
285   // being None or 0.
286   if (index.hasValue()) {
287     regions.push_back(RegionSuccessor(getResults()));
288     return;
289   }
290 
291   regions.push_back(RegionSuccessor(&doRegion()));
292 }
293 
294 void AssumingOp::inlineRegionIntoParent(AssumingOp &op,
295                                         PatternRewriter &rewriter) {
296   auto *blockBeforeAssuming = rewriter.getInsertionBlock();
297   auto *assumingBlock = op.getBody();
298   auto initPosition = rewriter.getInsertionPoint();
299   auto *blockAfterAssuming =
300       rewriter.splitBlock(blockBeforeAssuming, initPosition);
301 
302   // Remove the AssumingOp and AssumingYieldOp.
303   auto &yieldOp = assumingBlock->back();
304   rewriter.inlineRegionBefore(op.doRegion(), blockAfterAssuming);
305   rewriter.replaceOp(op, yieldOp.getOperands());
306   rewriter.eraseOp(&yieldOp);
307 
308   // Merge blocks together as there was no branching behavior from the
309   // AssumingOp.
310   rewriter.mergeBlocks(assumingBlock, blockBeforeAssuming);
311   rewriter.mergeBlocks(blockAfterAssuming, blockBeforeAssuming);
312 }
313 
314 //===----------------------------------------------------------------------===//
315 // AssumingAllOp
316 //===----------------------------------------------------------------------===//
317 
318 void AssumingAllOp::getCanonicalizationPatterns(
319     OwningRewritePatternList &patterns, MLIRContext *context) {
320   patterns.insert<AssumingAllOneOp>(context);
321 }
322 
323 OpFoldResult AssumingAllOp::fold(ArrayRef<Attribute> operands) {
324   // Iterate in reverse to first handle all constant operands. They are
325   // guaranteed to be the tail of the inputs because this is commutative.
326   for (int idx = operands.size() - 1; idx >= 0; idx--) {
327     Attribute a = operands[idx];
328     // Cannot fold if any inputs are not constant;
329     if (!a)
330       return nullptr;
331 
332     // We do not need to keep statically known values after handling them in
333     // this method.
334     getOperation()->eraseOperand(idx);
335 
336     // Always false if any input is statically known false
337     if (!a.cast<BoolAttr>().getValue())
338       return a;
339   }
340   // If this is reached, all inputs were statically known passing.
341   return BoolAttr::get(getContext(), true);
342 }
343 
344 static LogicalResult verify(AssumingAllOp op) {
345   // Ensure that AssumingAllOp contains at least one operand
346   if (op.getNumOperands() == 0)
347     return op.emitOpError("no operands specified");
348 
349   return success();
350 }
351 
352 //===----------------------------------------------------------------------===//
353 // BroadcastOp
354 //===----------------------------------------------------------------------===//
355 
356 OpFoldResult BroadcastOp::fold(ArrayRef<Attribute> operands) {
357   if (operands.size() == 1)
358     return shapes().front();
359 
360   // TODO: Support folding with more than 2 input shapes
361   if (shapes().size() > 2)
362     return nullptr;
363 
364   if (!operands[1])
365     return nullptr;
366 
367   auto rhsShape = llvm::to_vector<6>(
368       operands[1].cast<DenseIntElementsAttr>().getValues<int64_t>());
369   if (rhsShape.empty())
370     return shapes()[0];
371 
372   if (!operands[0])
373     return nullptr;
374 
375   auto lhsShape = llvm::to_vector<6>(
376       operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>());
377   if (lhsShape.empty())
378     return shapes()[1];
379 
380   SmallVector<int64_t, 6> resultShape;
381   // If the shapes are not compatible, we can't fold it.
382   // TODO: Fold to an "error".
383   if (!OpTrait::util::getBroadcastedShape(lhsShape, rhsShape, resultShape))
384     return nullptr;
385   Builder builder(getContext());
386   return builder.getIndexTensorAttr(resultShape);
387 }
388 
389 static LogicalResult verify(BroadcastOp op) {
390   return verifyShapeOrExtentTensorOp(op);
391 }
392 
393 namespace {
394 template <typename OpTy>
395 struct RemoveDuplicateOperandsPattern : public OpRewritePattern<OpTy> {
396   using OpRewritePattern<OpTy>::OpRewritePattern;
397 
398   LogicalResult matchAndRewrite(OpTy op,
399                                 PatternRewriter &rewriter) const override {
400     // Find unique operands.
401     SmallVector<Value, 2> unique;
402     for (Value v : op.getOperands()) {
403       if (!llvm::is_contained(unique, v))
404         unique.push_back(v);
405     }
406 
407     // Reduce op to equivalent with unique operands.
408     if (unique.size() < op.getNumOperands()) {
409       rewriter.replaceOpWithNewOp<OpTy>(op, op->getResultTypes(), unique,
410                                         op->getAttrs());
411       return success();
412     }
413 
414     return failure();
415   }
416 };
417 } // namespace
418 
419 void BroadcastOp::getCanonicalizationPatterns(
420     OwningRewritePatternList &patterns, MLIRContext *context) {
421   patterns.insert<RemoveDuplicateOperandsPattern<BroadcastOp>>(context);
422 }
423 
424 //===----------------------------------------------------------------------===//
425 // ConcatOp
426 //===----------------------------------------------------------------------===//
427 
428 OpFoldResult ConcatOp::fold(ArrayRef<Attribute> operands) {
429   if (!operands[0] || !operands[1])
430     return nullptr;
431   auto lhsShape = llvm::to_vector<6>(
432       operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>());
433   auto rhsShape = llvm::to_vector<6>(
434       operands[1].cast<DenseIntElementsAttr>().getValues<int64_t>());
435   SmallVector<int64_t, 6> resultShape;
436   resultShape.append(lhsShape.begin(), lhsShape.end());
437   resultShape.append(rhsShape.begin(), rhsShape.end());
438   Builder builder(getContext());
439   return builder.getIndexTensorAttr(resultShape);
440 }
441 
442 //===----------------------------------------------------------------------===//
443 // ConstShapeOp
444 //===----------------------------------------------------------------------===//
445 
446 static void print(OpAsmPrinter &p, ConstShapeOp &op) {
447   p << "shape.const_shape ";
448   p.printOptionalAttrDict(op->getAttrs(), /*elidedAttrs=*/{"shape"});
449   p << "[";
450   interleaveComma(op.shape().getValues<int64_t>(), p,
451                   [&](int64_t i) { p << i; });
452   p << "] : ";
453   p.printType(op.getType());
454 }
455 
456 static ParseResult parseConstShapeOp(OpAsmParser &parser,
457                                      OperationState &result) {
458   if (parser.parseOptionalAttrDict(result.attributes))
459     return failure();
460   // We piggy-back on ArrayAttr parsing, though we don't internally store the
461   // shape as an ArrayAttr.
462   // TODO: Implement custom parser and maybe make syntax a bit more concise.
463   Attribute extentsRaw;
464   NamedAttrList dummy;
465   if (parser.parseAttribute(extentsRaw, "dummy", dummy))
466     return failure();
467   auto extentsArray = extentsRaw.dyn_cast<ArrayAttr>();
468   if (!extentsArray)
469     return failure();
470   SmallVector<int64_t, 6> ints;
471   for (Attribute extent : extentsArray) {
472     IntegerAttr attr = extent.dyn_cast<IntegerAttr>();
473     if (!attr)
474       return failure();
475     ints.push_back(attr.getInt());
476   }
477   Builder &builder = parser.getBuilder();
478   result.addAttribute("shape", builder.getIndexTensorAttr(ints));
479   Type resultTy;
480   if (parser.parseColonType(resultTy))
481     return failure();
482   result.types.push_back(resultTy);
483   return success();
484 }
485 
486 OpFoldResult ConstShapeOp::fold(ArrayRef<Attribute>) { return shapeAttr(); }
487 
488 void ConstShapeOp::getCanonicalizationPatterns(
489     OwningRewritePatternList &patterns, MLIRContext *context) {
490   patterns.insert<TensorCastConstShape>(context);
491 }
492 
493 //===----------------------------------------------------------------------===//
494 // CstrBroadcastableOp
495 //===----------------------------------------------------------------------===//
496 
497 namespace {
498 // Given an input shape Value, try to obtain the shape's values.
499 LogicalResult getShapeVec(Value input, SmallVectorImpl<int64_t> &shapeValues) {
500   if (auto inputOp = input.getDefiningOp<ShapeOfOp>()) {
501     auto type = inputOp.arg().getType().dyn_cast<ShapedType>();
502     if (!type.hasRank())
503       return failure();
504     shapeValues = llvm::to_vector<6>(type.getShape());
505     return success();
506   } else if (auto inputOp = input.getDefiningOp<ConstShapeOp>()) {
507     shapeValues = llvm::to_vector<6>(inputOp.shape().getValues<int64_t>());
508     return success();
509   } else {
510     return failure();
511   }
512 }
513 } // namespace
514 
515 void CstrBroadcastableOp::getCanonicalizationPatterns(
516     OwningRewritePatternList &patterns, MLIRContext *context) {
517   // Canonicalization patterns have overlap with the considerations during
518   // folding in case additional shape information is inferred at some point that
519   // does not result in folding.
520   patterns.insert<CstrBroadcastableEqOps>(context);
521 }
522 
523 // Return true if there is exactly one attribute not representing a scalar
524 // broadcast.
525 static bool hasAtMostSingleNonScalar(ArrayRef<Attribute> attributes) {
526   bool nonScalarSeen = false;
527   for (Attribute a : attributes) {
528     if (!a || a.cast<DenseIntElementsAttr>().getNumElements() != 0) {
529       if (nonScalarSeen)
530         return false;
531       nonScalarSeen = true;
532     }
533   }
534   return true;
535 }
536 
537 OpFoldResult CstrBroadcastableOp::fold(ArrayRef<Attribute> operands) {
538   // No broadcasting is needed if all operands but one are scalar.
539   if (hasAtMostSingleNonScalar(operands))
540     return BoolAttr::get(getContext(), true);
541 
542   if ([&] {
543         SmallVector<SmallVector<int64_t, 6>, 6> extents;
544         for (const auto &operand : operands) {
545           if (!operand)
546             return false;
547           extents.push_back(llvm::to_vector<6>(
548               operand.cast<DenseIntElementsAttr>().getValues<int64_t>()));
549         }
550         return OpTrait::util::staticallyKnownBroadcastable(extents);
551       }())
552     return BoolAttr::get(getContext(), true);
553 
554   // Lastly, see if folding can be completed based on what constraints are known
555   // on the input shapes.
556   if ([&] {
557         SmallVector<SmallVector<int64_t, 6>, 6> extents;
558         for (const auto &shape : shapes()) {
559           extents.emplace_back();
560           if (failed(getShapeVec(shape, extents.back())))
561             return false;
562         }
563         return OpTrait::util::staticallyKnownBroadcastable(extents);
564       }())
565     return BoolAttr::get(getContext(), true);
566 
567   // Because a failing witness result here represents an eventual assertion
568   // failure, we do not replace it with a constant witness.
569   return nullptr;
570 }
571 
572 static LogicalResult verify(CstrBroadcastableOp op) {
573   // Ensure that AssumingAllOp contains at least one operand
574   if (op.getNumOperands() < 2)
575     return op.emitOpError("required at least 2 input shapes");
576   return success();
577 }
578 
579 //===----------------------------------------------------------------------===//
580 // CstrEqOp
581 //===----------------------------------------------------------------------===//
582 
583 void CstrEqOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns,
584                                            MLIRContext *context) {
585   // If inputs are equal, return passing witness
586   patterns.insert<CstrEqEqOps>(context);
587 }
588 
589 OpFoldResult CstrEqOp::fold(ArrayRef<Attribute> operands) {
590   if (llvm::all_of(operands,
591                    [&](Attribute a) { return a && a == operands[0]; }))
592     return BoolAttr::get(getContext(), true);
593 
594   // Because a failing witness result here represents an eventual assertion
595   // failure, we do not try to replace it with a constant witness. Similarly, we
596   // cannot if there are any non-const inputs.
597   return nullptr;
598 }
599 
600 //===----------------------------------------------------------------------===//
601 // ConstSizeOp
602 //===----------------------------------------------------------------------===//
603 
604 void ConstSizeOp::build(OpBuilder &builder, OperationState &result,
605                         int64_t value) {
606   build(builder, result, builder.getIndexAttr(value));
607 }
608 
609 OpFoldResult ConstSizeOp::fold(ArrayRef<Attribute>) { return valueAttr(); }
610 
611 void ConstSizeOp::getAsmResultNames(
612     llvm::function_ref<void(Value, StringRef)> setNameFn) {
613   SmallString<4> buffer;
614   llvm::raw_svector_ostream os(buffer);
615   os << "c" << value();
616   setNameFn(getResult(), os.str());
617 }
618 
619 //===----------------------------------------------------------------------===//
620 // ConstWitnessOp
621 //===----------------------------------------------------------------------===//
622 
623 OpFoldResult ConstWitnessOp::fold(ArrayRef<Attribute>) { return passingAttr(); }
624 
625 //===----------------------------------------------------------------------===//
626 // CstrRequireOp
627 //===----------------------------------------------------------------------===//
628 
629 OpFoldResult CstrRequireOp::fold(ArrayRef<Attribute> operands) {
630   return operands[0];
631 }
632 
633 //===----------------------------------------------------------------------===//
634 // DivOp
635 //===----------------------------------------------------------------------===//
636 
637 OpFoldResult DivOp::fold(ArrayRef<Attribute> operands) {
638   auto lhs = operands[0].dyn_cast_or_null<IntegerAttr>();
639   if (!lhs)
640     return nullptr;
641   auto rhs = operands[1].dyn_cast_or_null<IntegerAttr>();
642   if (!rhs)
643     return nullptr;
644 
645   // Division in APInt does not follow floor(lhs, rhs) when the result is
646   // negative. Rather, APInt rounds toward zero.
647   APInt quotient, remainder;
648   APInt::sdivrem(lhs.getValue(), rhs.getValue(), quotient, remainder);
649   if (quotient.isNegative() && !remainder.isNullValue()) {
650     quotient -= 1;
651   }
652 
653   Type indexTy = IndexType::get(getContext());
654   return IntegerAttr::get(indexTy, quotient);
655 }
656 
657 //===----------------------------------------------------------------------===//
658 // ShapeEqOp
659 //===----------------------------------------------------------------------===//
660 
661 OpFoldResult ShapeEqOp::fold(ArrayRef<Attribute> operands) {
662   bool allSame = true;
663   if (!operands.empty() && !operands[0])
664     return {};
665   for (Attribute operand : operands.drop_front(1)) {
666     if (!operand)
667       return {};
668     allSame = allSame && operand == operands[0];
669   }
670   return BoolAttr::get(getContext(), allSame);
671 }
672 
673 //===----------------------------------------------------------------------===//
674 // IndexToSizeOp
675 //===----------------------------------------------------------------------===//
676 
677 OpFoldResult IndexToSizeOp::fold(ArrayRef<Attribute> operands) {
678   // Constant values of both types, `shape.size` and `index`, are represented as
679   // `IntegerAttr`s which makes constant folding simple.
680   if (Attribute arg = operands[0])
681     return arg;
682   return {};
683 }
684 
685 void IndexToSizeOp::getCanonicalizationPatterns(
686     OwningRewritePatternList &patterns, MLIRContext *context) {
687   patterns.insert<SizeToIndexToSizeCanonicalization>(context);
688 }
689 
690 //===----------------------------------------------------------------------===//
691 // FromExtentsOp
692 //===----------------------------------------------------------------------===//
693 
694 OpFoldResult FromExtentsOp::fold(ArrayRef<Attribute> operands) {
695   if (llvm::any_of(operands, [](Attribute a) { return !a; }))
696     return nullptr;
697   SmallVector<int64_t, 6> extents;
698   for (auto attr : operands)
699     extents.push_back(attr.cast<IntegerAttr>().getInt());
700   Builder builder(getContext());
701   return builder.getIndexTensorAttr(extents);
702 }
703 
704 //===----------------------------------------------------------------------===//
705 // FunctionLibraryOp
706 //===----------------------------------------------------------------------===//
707 
708 void FunctionLibraryOp::build(OpBuilder &builder, OperationState &result,
709                               StringRef name) {
710   ensureTerminator(*result.addRegion(), builder, result.location);
711   result.attributes.push_back(builder.getNamedAttr(
712       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
713 }
714 
715 FuncOp FunctionLibraryOp::getShapeFunction(Operation *op) {
716   auto attr = mapping()
717                   .get(op->getName().getIdentifier())
718                   .dyn_cast_or_null<FlatSymbolRefAttr>();
719   if (!attr)
720     return nullptr;
721   return lookupSymbol<FuncOp>(attr);
722 }
723 
724 ParseResult parseFunctionLibraryOp(OpAsmParser &parser,
725                                    OperationState &result) {
726   // Parse the op name.
727   StringAttr nameAttr;
728   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
729                              result.attributes))
730     return failure();
731 
732   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
733     return failure();
734 
735   auto *bodyRegion = result.addRegion();
736   if (parser.parseRegion(*bodyRegion))
737     return failure();
738 
739   FunctionLibraryOp::ensureTerminator(*bodyRegion, parser.getBuilder(),
740                                       result.location);
741   if (parser.parseKeyword("mapping"))
742     return failure();
743 
744   DictionaryAttr mappingAttr;
745   if (parser.parseAttribute(mappingAttr,
746                             parser.getBuilder().getType<NoneType>(), "mapping",
747                             result.attributes))
748     return failure();
749   return success();
750 }
751 
752 void print(OpAsmPrinter &p, FunctionLibraryOp op) {
753   p << op.getOperationName() << ' ';
754   p.printSymbolName(op.getName());
755   p.printOptionalAttrDictWithKeyword(
756       op->getAttrs(), {SymbolTable::getSymbolAttrName(), "mapping"});
757   p.printRegion(op.getOperation()->getRegion(0), /*printEntryBlockArgs=*/false,
758                 /*printBlockTerminators=*/false);
759   p << " mapping ";
760   p.printAttributeWithoutType(op.mappingAttr());
761 }
762 
763 //===----------------------------------------------------------------------===//
764 // GetExtentOp
765 //===----------------------------------------------------------------------===//
766 
767 Optional<int64_t> GetExtentOp::getConstantDim() {
768   if (auto constSizeOp = dim().getDefiningOp<ConstSizeOp>())
769     return constSizeOp.value().getLimitedValue();
770   if (auto constantOp = dim().getDefiningOp<ConstantOp>())
771     return constantOp.value().cast<IntegerAttr>().getInt();
772   return llvm::None;
773 }
774 
775 OpFoldResult GetExtentOp::fold(ArrayRef<Attribute> operands) {
776   auto elements = operands[0].dyn_cast_or_null<DenseIntElementsAttr>();
777   if (!elements)
778     return nullptr;
779   Optional<int64_t> dim = getConstantDim();
780   if (!dim.hasValue())
781     return nullptr;
782   if (dim.getValue() >= elements.getNumElements())
783     return nullptr;
784   return elements.getValue({(uint64_t)dim.getValue()});
785 }
786 
787 void GetExtentOp::build(OpBuilder &builder, OperationState &result, Value shape,
788                         int64_t dim) {
789   auto loc = result.location;
790   auto dimAttr = builder.getIndexAttr(dim);
791   if (shape.getType().isa<ShapeType>()) {
792     Value dim = builder.create<ConstSizeOp>(loc, dimAttr);
793     build(builder, result, builder.getType<SizeType>(), shape, dim);
794   } else {
795     Value dim =
796         builder.create<ConstantOp>(loc, builder.getIndexType(), dimAttr);
797     build(builder, result, builder.getIndexType(), shape, dim);
798   }
799 }
800 
801 //===----------------------------------------------------------------------===//
802 // IsBroadcastableOp
803 //===----------------------------------------------------------------------===//
804 
805 void IsBroadcastableOp::getCanonicalizationPatterns(
806     OwningRewritePatternList &patterns, MLIRContext *context) {
807   patterns.insert<RemoveDuplicateOperandsPattern<IsBroadcastableOp>>(context);
808 }
809 
810 OpFoldResult IsBroadcastableOp::fold(ArrayRef<Attribute> operands) {
811   // Can always broadcast fewer than two shapes.
812   if (operands.size() < 2) {
813     return BoolAttr::get(getContext(), true);
814   }
815 
816   return nullptr;
817 }
818 
819 //===----------------------------------------------------------------------===//
820 // RankOp
821 //===----------------------------------------------------------------------===//
822 
823 OpFoldResult shape::RankOp::fold(ArrayRef<Attribute> operands) {
824   auto shape = operands[0].dyn_cast_or_null<DenseIntElementsAttr>();
825   if (!shape)
826     return {};
827   int64_t rank = shape.getNumElements();
828   Builder builder(getContext());
829   return builder.getIndexAttr(rank);
830 }
831 
832 /// Evaluate the `rank` operation for shapes of ranked tensors at compile time.
833 /// Constant folding fails in cases where only the rank is constant, not the
834 /// shape itself.
835 /// This canonicalization matches `shape.rank(shape.shape_of(%ranked_tensor))`.
836 ///
837 /// Example:
838 ///
839 /// %shape = shape.shape_of %ranked_tensor : tensor<1x2x?xf32>
840 /// %rank = shape.rank %shape
841 ///
842 /// becomes
843 ///
844 /// %rank = shape.const_size 3
845 
846 namespace {
847 struct RankShapeOfCanonicalizationPattern
848     : public OpRewritePattern<shape::RankOp> {
849   using OpRewritePattern<shape::RankOp>::OpRewritePattern;
850 
851   LogicalResult matchAndRewrite(shape::RankOp op,
852                                 PatternRewriter &rewriter) const override {
853     auto shapeOfOp = op.shape().getDefiningOp<ShapeOfOp>();
854     if (!shapeOfOp)
855       return failure();
856     auto rankedTensorType =
857         shapeOfOp.arg().getType().dyn_cast<RankedTensorType>();
858     if (!rankedTensorType)
859       return failure();
860     int64_t rank = rankedTensorType.getRank();
861     if (op.getType().isa<IndexType>()) {
862       rewriter.replaceOpWithNewOp<ConstantIndexOp>(op.getOperation(), rank);
863     } else if (op.getType().isa<shape::SizeType>()) {
864       rewriter.replaceOpWithNewOp<shape::ConstSizeOp>(op.getOperation(), rank);
865     } else {
866       return failure();
867     }
868     return success();
869   }
870 };
871 } // namespace
872 
873 void shape::RankOp::getCanonicalizationPatterns(
874     OwningRewritePatternList &patterns, MLIRContext *context) {
875   patterns.insert<RankShapeOfCanonicalizationPattern>(context);
876 }
877 
878 //===----------------------------------------------------------------------===//
879 // NumElementsOp
880 //===----------------------------------------------------------------------===//
881 
882 OpFoldResult NumElementsOp::fold(ArrayRef<Attribute> operands) {
883 
884   // Fold only when argument constant.
885   Attribute shape = operands[0];
886   if (!shape)
887     return {};
888 
889   APInt product(64, 1);
890   for (auto value : shape.cast<DenseIntElementsAttr>())
891     product *= value;
892   Builder builder(getContext());
893   return builder.getIndexAttr(product.getLimitedValue());
894 }
895 
896 void NumElementsOp::build(OpBuilder &builder, OperationState &result,
897                           Value shape) {
898   if (shape.getType().isa<ShapedType>()) {
899     auto type = builder.getIndexType();
900     return build(builder, result, type, shape);
901   }
902   auto type = SizeType::get(builder.getContext());
903   return build(builder, result, type, shape);
904 }
905 
906 //===----------------------------------------------------------------------===//
907 // MulOp
908 //===----------------------------------------------------------------------===//
909 
910 OpFoldResult MulOp::fold(ArrayRef<Attribute> operands) {
911   auto lhs = operands[0].dyn_cast_or_null<IntegerAttr>();
912   if (!lhs)
913     return nullptr;
914   auto rhs = operands[1].dyn_cast_or_null<IntegerAttr>();
915   if (!rhs)
916     return nullptr;
917   APInt folded = lhs.getValue() * rhs.getValue();
918   Type indexTy = IndexType::get(getContext());
919   return IntegerAttr::get(indexTy, folded);
920 }
921 
922 //===----------------------------------------------------------------------===//
923 // ShapeOfOp
924 //===----------------------------------------------------------------------===//
925 
926 OpFoldResult ShapeOfOp::fold(ArrayRef<Attribute>) {
927   auto type = getOperand().getType().dyn_cast<ShapedType>();
928   if (!type || !type.hasStaticShape())
929     return nullptr;
930   Builder builder(getContext());
931   return builder.getIndexTensorAttr(type.getShape());
932 }
933 
934 void ShapeOfOp::build(OpBuilder &builder, OperationState &result, Value arg) {
935   Type type = arg.getType().isa<ShapedType>()
936                   ? (Type)getExtentTensorType(builder.getContext())
937                   : (Type)builder.getType<ShapeType>();
938   return ShapeOfOp::build(builder, result, type, arg);
939 }
940 
941 namespace {
942 struct ShapeOfWithTensor : public OpRewritePattern<shape::ShapeOfOp> {
943   using OpRewritePattern<shape::ShapeOfOp>::OpRewritePattern;
944 
945   LogicalResult matchAndRewrite(shape::ShapeOfOp op,
946                                 PatternRewriter &rewriter) const override {
947     if (!op.arg().getType().isa<ShapedType>())
948       return failure();
949     if (op.getType().isa<ShapedType>())
950       return failure();
951 
952     rewriter.replaceOpWithNewOp<shape::ShapeOfOp>(op.getOperation(), op.arg());
953     return success();
954   }
955 };
956 } // namespace
957 
958 void ShapeOfOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns,
959                                             MLIRContext *context) {
960   patterns.insert<ShapeOfWithTensor>(context);
961 }
962 
963 //===----------------------------------------------------------------------===//
964 // SizeToIndexOp
965 //===----------------------------------------------------------------------===//
966 
967 OpFoldResult SizeToIndexOp::fold(ArrayRef<Attribute> operands) {
968   // Constant values of both types, `shape.size` and `index`, are represented as
969   // `IntegerAttr`s which makes constant folding simple.
970   if (Attribute arg = operands[0])
971     return arg;
972   return impl::foldCastOp(*this);
973 }
974 
975 void SizeToIndexOp::getCanonicalizationPatterns(
976     OwningRewritePatternList &patterns, MLIRContext *context) {
977   patterns.insert<IndexToSizeToIndexCanonicalization>(context);
978 }
979 
980 //===----------------------------------------------------------------------===//
981 // YieldOp
982 //===----------------------------------------------------------------------===//
983 
984 static LogicalResult verify(shape::YieldOp op) {
985   auto *parentOp = op->getParentOp();
986   auto results = parentOp->getResults();
987   auto operands = op.getOperands();
988 
989   if (parentOp->getNumResults() != op.getNumOperands())
990     return op.emitOpError() << "number of operands does not match number of "
991                                "results of its parent";
992   for (auto e : llvm::zip(results, operands))
993     if (std::get<0>(e).getType() != std::get<1>(e).getType())
994       return op.emitOpError()
995              << "types mismatch between yield op and its parent";
996 
997   return success();
998 }
999 
1000 //===----------------------------------------------------------------------===//
1001 // SplitAtOp
1002 //===----------------------------------------------------------------------===//
1003 
1004 LogicalResult SplitAtOp::fold(ArrayRef<Attribute> operands,
1005                               SmallVectorImpl<OpFoldResult> &results) {
1006   if (!operands[0] || !operands[1])
1007     return failure();
1008   auto shapeVec = llvm::to_vector<6>(
1009       operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>());
1010   auto shape = llvm::makeArrayRef(shapeVec);
1011   auto splitPoint = operands[1].cast<IntegerAttr>().getInt();
1012   // Verify that the split point is in the correct range.
1013   // TODO: Constant fold to an "error".
1014   int64_t rank = shape.size();
1015   if (!(-rank <= splitPoint && splitPoint <= rank))
1016     return failure();
1017   if (splitPoint < 0)
1018     splitPoint += shape.size();
1019   Builder builder(operands[0].getContext());
1020   results.push_back(builder.getIndexTensorAttr(shape.take_front(splitPoint)));
1021   results.push_back(builder.getIndexTensorAttr(shape.drop_front(splitPoint)));
1022   return success();
1023 }
1024 
1025 //===----------------------------------------------------------------------===//
1026 // ToExtentTensorOp
1027 //===----------------------------------------------------------------------===//
1028 
1029 OpFoldResult ToExtentTensorOp::fold(ArrayRef<Attribute> operands) {
1030   if (!operands[0])
1031     return impl::foldCastOp(*this);
1032   Builder builder(getContext());
1033   auto shape = llvm::to_vector<6>(
1034       operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>());
1035   auto type = RankedTensorType::get({static_cast<int64_t>(shape.size())},
1036                                     builder.getIndexType());
1037   return DenseIntElementsAttr::get(type, shape);
1038 }
1039 
1040 //===----------------------------------------------------------------------===//
1041 // ReduceOp
1042 //===----------------------------------------------------------------------===//
1043 
1044 void ReduceOp::build(OpBuilder &builder, OperationState &result, Value shape,
1045                      ValueRange initVals) {
1046   result.addOperands(shape);
1047   result.addOperands(initVals);
1048 
1049   Region *bodyRegion = result.addRegion();
1050   bodyRegion->push_back(new Block);
1051   Block &bodyBlock = bodyRegion->front();
1052   bodyBlock.addArgument(builder.getIndexType());
1053 
1054   Type elementType;
1055   if (auto tensorType = shape.getType().dyn_cast<TensorType>())
1056     elementType = tensorType.getElementType();
1057   else
1058     elementType = SizeType::get(builder.getContext());
1059   bodyBlock.addArgument(elementType);
1060 
1061   for (Type initValType : initVals.getTypes()) {
1062     bodyBlock.addArgument(initValType);
1063     result.addTypes(initValType);
1064   }
1065 }
1066 
1067 static LogicalResult verify(ReduceOp op) {
1068   // Verify block arg types.
1069   Block &block = op.region().front();
1070 
1071   // The block takes index, extent, and aggregated values as arguments.
1072   auto blockArgsCount = op.initVals().size() + 2;
1073   if (block.getNumArguments() != blockArgsCount)
1074     return op.emitOpError() << "ReduceOp body is expected to have "
1075                             << blockArgsCount << " arguments";
1076 
1077   // The first block argument is the index and must always be of type `index`.
1078   if (!block.getArgument(0).getType().isa<IndexType>())
1079     return op.emitOpError(
1080         "argument 0 of ReduceOp body is expected to be of IndexType");
1081 
1082   // The second block argument is the extent and must be of type `size` or
1083   // `index`, depending on whether the reduce operation is applied to a shape or
1084   // to an extent tensor.
1085   Type extentTy = block.getArgument(1).getType();
1086   if (op.shape().getType().isa<ShapeType>()) {
1087     if (!extentTy.isa<SizeType>())
1088       return op.emitOpError("argument 1 of ReduceOp body is expected to be of "
1089                             "SizeType if the ReduceOp operates on a ShapeType");
1090   } else {
1091     if (!extentTy.isa<IndexType>())
1092       return op.emitOpError(
1093           "argument 1 of ReduceOp body is expected to be of IndexType if the "
1094           "ReduceOp operates on an extent tensor");
1095   }
1096 
1097   for (auto type : llvm::enumerate(op.initVals()))
1098     if (block.getArgument(type.index() + 2).getType() != type.value().getType())
1099       return op.emitOpError()
1100              << "type mismatch between argument " << type.index() + 2
1101              << " of ReduceOp body and initial value " << type.index();
1102   return success();
1103 }
1104 
1105 static ParseResult parseReduceOp(OpAsmParser &parser, OperationState &result) {
1106   // Parse operands.
1107   SmallVector<OpAsmParser::OperandType, 3> operands;
1108   Type shapeOrExtentTensorType;
1109   if (parser.parseOperandList(operands, /*requiredOperandCount=*/-1,
1110                               OpAsmParser::Delimiter::Paren) ||
1111       parser.parseColonType(shapeOrExtentTensorType) ||
1112       parser.parseOptionalArrowTypeList(result.types))
1113     return failure();
1114 
1115   // Resolve operands.
1116   auto initVals = llvm::makeArrayRef(operands).drop_front();
1117   if (parser.resolveOperand(operands.front(), shapeOrExtentTensorType,
1118                             result.operands) ||
1119       parser.resolveOperands(initVals, result.types, parser.getNameLoc(),
1120                              result.operands))
1121     return failure();
1122 
1123   // Parse the body.
1124   Region *body = result.addRegion();
1125   if (parser.parseRegion(*body, /*args=*/{}, /*argTypes=*/{}))
1126     return failure();
1127 
1128   // Parse attributes.
1129   if (parser.parseOptionalAttrDict(result.attributes))
1130     return failure();
1131 
1132   return success();
1133 }
1134 
1135 static void print(OpAsmPrinter &p, ReduceOp op) {
1136   p << op.getOperationName() << '(' << op.shape() << ", " << op.initVals()
1137     << ") : " << op.shape().getType();
1138   p.printOptionalArrowTypeList(op.getResultTypes());
1139   p.printRegion(op.region());
1140   p.printOptionalAttrDict(op->getAttrs());
1141 }
1142 
1143 #define GET_OP_CLASSES
1144 #include "mlir/Dialect/Shape/IR/ShapeOps.cpp.inc"
1145