1 //===- Detensorize.cpp - Linalg transformations as patterns ----------===//
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 "PassDetail.h"
10 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
11 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
12 #include "mlir/Dialect/Linalg/Passes.h"
13 #include "mlir/Dialect/StandardOps/Transforms/FuncConversions.h"
14 #include "mlir/Dialect/Tensor/IR/Tensor.h"
15 #include "mlir/IR/OpDefinition.h"
16 #include "mlir/Transforms/DialectConversion.h"
17 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
18 #include <iterator>
19 #include <memory>
20 
21 using namespace mlir;
22 using namespace mlir::linalg;
23 
24 static Value sourceMaterializationCallback(OpBuilder &builder, Type type,
25                                            ValueRange inputs, Location loc) {
26   assert(inputs.size() == 1);
27   // A detensored value is converted back by creating a new tensor from its
28   // element(s).
29   auto createNewTensorOp = builder.create<tensor::FromElementsOp>(
30       loc, inputs[0].getType(), inputs[0]);
31 
32   // FromElementsOp results in a tensor<1xdtype>, we need to reshape that to
33   // a tensor<dtype> instead.
34   return builder.create<linalg::TensorCollapseShapeOp>(
35       loc, type, createNewTensorOp, ArrayRef<ReassociationExprs>{});
36 }
37 
38 namespace {
39 /// Defines the criteria a TensorType must follow in order to be considered
40 /// "detensorable".
41 ///
42 /// NOTE: For now, only 0-D tensors are supported.
43 ///
44 /// Returns true if tensorType can be detensored.
45 bool canBeDetensored(TensorType tensorType) {
46   return tensorType.hasRank() && tensorType.getRank() == 0;
47 }
48 
49 bool shouldBeDetensored(Operation *op, TypeConverter typeConverter) {
50   GenericOp genericOp = dyn_cast_or_null<GenericOp>(op);
51   return genericOp &&
52          llvm::all_of(
53              genericOp.getInputAndOutputOperands(), [&](OpOperand *opOperand) {
54                return !typeConverter.isLegal(opOperand->get().getType());
55              });
56 }
57 
58 /// A conversion patttern for detensoring `linalg.generic` ops.
59 class DetensorizeGenericOp : public OpConversionPattern<GenericOp> {
60 public:
61   using OpConversionPattern::OpConversionPattern;
62   LogicalResult
63   matchAndRewrite(GenericOp op, ArrayRef<Value> operands,
64                   ConversionPatternRewriter &rewriter) const override {
65     Block *originalBlock = op->getBlock();
66 
67     // Gather some information about the op before inling its region.
68     Block *opEntryBlock = &*op.region().begin();
69     YieldOp yieldOp = dyn_cast<YieldOp>(op.region().back().getTerminator());
70 
71     // Split the op's region before the op. This way, we have a clear insertion
72     // point in which the op can be inlined.
73     Block *newBlock = originalBlock->splitBlock(op);
74     rewriter.inlineRegionBefore(op.region(), newBlock);
75     // Now that op's region is inlined, the operands of its YieldOp are mapped
76     // to the materialized target values. Therefore, we can replace the op's
77     // uses with those of its YielOp's operands.
78     rewriter.replaceOp(op, yieldOp->getOperands());
79 
80     // No need for these intermediate blocks, merge them into 1.
81     rewriter.mergeBlocks(opEntryBlock, originalBlock, operands);
82     rewriter.mergeBlocks(newBlock, originalBlock, {});
83 
84     rewriter.eraseOp(&*Block::iterator(yieldOp));
85 
86     return success();
87   }
88 };
89 
90 /// A conversion pattern for detensoring internal (non-entry) blocks within a
91 /// function.
92 struct FunctionNonEntryBlockConversion : public ConversionPattern {
93   FunctionNonEntryBlockConversion(StringRef functionLikeOpName,
94                                   MLIRContext *ctx, TypeConverter &converter,
95                                   DenseSet<BlockArgument> blockArgsToDetensor)
96       : ConversionPattern(converter, functionLikeOpName, /*benefit=*/1, ctx),
97         blockArgsToDetensor(blockArgsToDetensor) {}
98 
99   LogicalResult
100   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
101                   ConversionPatternRewriter &rewriter) const override {
102     rewriter.startRootUpdate(op);
103     Region &region = function_like_impl::getFunctionBody(op);
104     SmallVector<TypeConverter::SignatureConversion, 2> conversions;
105 
106     for (Block &block : llvm::drop_begin(region, 1)) {
107       conversions.emplace_back(block.getNumArguments());
108       TypeConverter::SignatureConversion &back = conversions.back();
109 
110       for (BlockArgument blockArgument : block.getArguments()) {
111         int idx = blockArgument.getArgNumber();
112 
113         if (blockArgsToDetensor.count(blockArgument))
114           back.addInputs(idx, {getTypeConverter()->convertType(
115                                   block.getArgumentTypes()[idx])});
116         else
117           back.addInputs(idx, {block.getArgumentTypes()[idx]});
118       }
119     }
120 
121     if (failed(rewriter.convertNonEntryRegionTypes(&region, *typeConverter,
122                                                    conversions))) {
123       rewriter.cancelRootUpdate(op);
124       return failure();
125     }
126 
127     rewriter.finalizeRootUpdate(op);
128     return success();
129   }
130 
131 private:
132   const DenseSet<BlockArgument> blockArgsToDetensor;
133 };
134 
135 class DetensorizeTypeConverter : public TypeConverter {
136 public:
137   DetensorizeTypeConverter() {
138     addConversion([](Type type) { return type; });
139 
140     // A TensorType that can be detensored, is converted to the underlying
141     // element type.
142     addConversion([](TensorType tensorType) -> Type {
143       if (canBeDetensored(tensorType))
144         return tensorType.getElementType();
145 
146       return tensorType;
147     });
148 
149     // A tensor value is detensoried by extracting its element(s).
150     addTargetMaterialization([](OpBuilder &builder, Type type,
151                                 ValueRange inputs, Location loc) -> Value {
152       return builder.create<tensor::ExtractOp>(loc, inputs[0], ValueRange{});
153     });
154 
155     addSourceMaterialization(sourceMaterializationCallback);
156     addArgumentMaterialization(sourceMaterializationCallback);
157   }
158 };
159 
160 /// Canonicalizes the pattern of the form
161 ///
162 /// %tensor = tensor.from_elements(%element) : (i32) -> tensor<1xi32>
163 /// %reshaped_tensor = linalg.tensor_collapse_shape %tensor []
164 ///     : tensor<1xi32> into tensor<i32>
165 /// %extracted_element = tensor.extract %reshaped_tensor[] : tensor<i32>
166 ///
167 /// to just %element.
168 struct ExtractFromReshapeFromElements
169     : public OpRewritePattern<tensor::ExtractOp> {
170   using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern;
171 
172   LogicalResult matchAndRewrite(tensor::ExtractOp extract,
173                                 PatternRewriter &rewriter) const final {
174     if (!extract.indices().empty())
175       return failure();
176 
177     auto tensorReshape =
178         extract.tensor().getDefiningOp<TensorCollapseShapeOp>();
179     if (tensorReshape == nullptr)
180       return failure();
181 
182     auto tensorFromElements =
183         tensorReshape.getOperand()
184             .getDefiningOp<mlir::tensor::FromElementsOp>();
185     if (tensorFromElements == nullptr)
186       return failure();
187 
188     rewriter.replaceOp(extract, tensorFromElements.getOperand(0));
189     return success();
190   }
191 };
192 
193 /// @see LinalgDetensorize in Linalg/Passes.td for more details.
194 struct LinalgDetensorize : public LinalgDetensorizeBase<LinalgDetensorize> {
195   LinalgDetensorize() = default;
196   LinalgDetensorize(const LinalgDetensorize &pass) {}
197 
198   class CostModel {
199   public:
200     virtual ~CostModel() = default;
201 
202     /// A cost model algorithm computes the following outputs:
203     ///
204     /// - opsToDetensor: the list of linalg ops that should be
205     /// detensored.
206     ///
207     /// - blockArgsToDetensor: since the operands and results of detensored
208     /// linalg ops can cross the BB boundary (e.g. a linalg op's input can come
209     /// from a BB argument and a linalg op's output can be passed to successor
210     /// BBs), we need to maintain the sub-set of arguments that should be
211     /// detensored (i.e. converted by typeConverter) for each affected BB.
212     ///
213     /// Example:
214     ///
215     /// For the following snippet:
216     /// ...
217     /// ^bb1(%6: tensor<i32>, %9: tensor<i32>):
218     ///   %7 = linalg.init_tensor [] : tensor<i32>
219     ///   %8 = linalg.generic #attrs
220     ///     ins(%6, %6 : tensor<i32>, tensor<i32>)
221     ///     outs(%7 : tensor<i32>) {
222     ///     ^bb0(%arg0: i32, %arg1: i32, %arg2: i32):
223     ///       %9 = addi %arg0, %arg1 : i32
224     ///       linalg.yield %9 : i32
225     ///   } -> tensor<i32>
226     ///   %10 = "some.op"(%9)
227     ///   br ^bb2(%8 : tensor<i32>)
228     /// ...
229     ///
230     /// if the cost model decides that the linalg.generic op should be
231     /// detensored, then:
232     /// - opsToDetensor should be = {linalg.generic{add}}.
233     /// - blockArgsToDetensor should be = {bb1 -> {0}, bb2 -> {0}}.
234     virtual void compute(FuncOp func, DetensorizeTypeConverter typeConverter,
235                          DenseSet<Operation *> &opsToDetensor,
236                          DenseSet<BlockArgument> &blockArgsToDetensor) = 0;
237 
238     /// From the blockArgsToDetensor set computed by a CostModel
239     /// implementation, this method computes the corresponding branch op
240     /// detensoring. The result is a map from a branch op to a subset of indices
241     /// of its operands. The indices specify which of the branch op's operands
242     /// should be detensored.
243     ///
244     /// For the previous example, this method would compute: {bb2 -> {0}}.
245     static DenseMap<Operation *, DenseSet<int>> computeBranchOpDetensoring(
246         const DenseSet<BlockArgument> &blockArgsToDetensor) {
247       DenseMap<Operation *, DenseSet<int>> detensorableBranchOps;
248 
249       for (auto blockArgumentElem : blockArgsToDetensor) {
250         Block *block = blockArgumentElem.getOwner();
251 
252         for (PredecessorIterator pred = block->pred_begin();
253              pred != block->pred_end(); ++pred) {
254           BranchOpInterface terminator =
255               dyn_cast<BranchOpInterface>((*pred)->getTerminator());
256           auto blockOperands =
257               terminator.getSuccessorOperands(pred.getSuccessorIndex());
258 
259           if (!blockOperands || blockOperands->empty())
260             continue;
261 
262           detensorableBranchOps[terminator].insert(
263               blockOperands->getBeginOperandIndex() +
264               blockArgumentElem.getArgNumber());
265         }
266       }
267 
268       return detensorableBranchOps;
269     }
270   };
271 
272   /// Detensorize linalg ops involved in control-flow within a function.
273   ///
274   /// This model starts from CondBranchOps within a function. For each cond_br,
275   /// the model then walks the use-def chain for the branch's condition
276   /// backwards in order to understand where the condition's value comes from.
277   /// If the condition value is (indirectly) computed by a linalg op that can be
278   /// detensored, the model then continues walking the use-def chain in order to
279   /// understand where the linalg op's operands come from. This leads to
280   /// discovering a "detensoring component". A detensoring component is the set
281   /// of operations + block arguments that are involved in control-flow AND can
282   /// be detensored.
283   ///
284   /// For examples where this model succeeds to discover a detensoring
285   /// component, see:
286   /// - test/Dialect/Linalg/detensorize_while.mlir
287   /// - test/Dialect/Linalg/detesorize_while_pure_cf.mlir.
288   ///
289   /// For an example where this model marks control-flow as "non-detensorable",
290   /// see:
291   /// - test/Dialect/Linalg/detensorize_while_failure.mlir
292   class PureControlFlowDetectionModel : public CostModel {
293   public:
294     void compute(FuncOp func, DetensorizeTypeConverter typeConverter,
295                  DenseSet<Operation *> &opsToDetensor,
296                  DenseSet<BlockArgument> &blockArgsToDetensor) override {
297       SmallVector<Value> workList;
298 
299       func.walk(
300           [&](CondBranchOp condBr) { workList.push_back(condBr.condition()); });
301 
302       DenseSet<Value> visitedValues;
303       DenseSet<Operation *> visitedOps;
304 
305       // For a (to-be-detesored) value, check if it "escapes" the block by being
306       // passed to terminator. If it does, then workList is updated with the
307       // corresponding argument to the successor block.
308       auto updateWorkListWithSuccessorArguments =
309           [&](Value value, BranchOpInterface terminator) {
310             if (!terminator)
311               return;
312 
313             for (auto operandIdx :
314                  llvm::seq<unsigned>(0, terminator->getOperands().size())) {
315               Value operand = terminator->getOperand(operandIdx);
316 
317               if (operand == value) {
318                 auto succBlockArg =
319                     terminator.getSuccessorBlockArgument(operandIdx);
320 
321                 if (succBlockArg && !blockArgsToDetensor.count(*succBlockArg))
322                   workList.push_back(*succBlockArg);
323               }
324             }
325           };
326 
327       while (!workList.empty()) {
328         Value currentItem = workList.pop_back_val();
329 
330         if (!visitedValues.insert(currentItem).second)
331           continue;
332 
333         // 1   - Look forward:
334         // 1.1 - If currentItem escapes to one or more successors, add
335         // the corresponding successor arguments to workList.
336         updateWorkListWithSuccessorArguments(
337             currentItem, dyn_cast<BranchOpInterface>(
338                              currentItem.getParentBlock()->getTerminator()));
339 
340         // 1.2 - For each user of currentItem, add the defined values to
341         // workList. This way, the user ops can be inspected later if they are
342         // detensorable and if so, their operands will be added to workList to
343         // potentially discover other parts of the detensorable component.
344         for (auto *user : currentItem.getUsers())
345           for (Value result : user->getResults())
346             workList.push_back(result);
347 
348         // 2   - Look backward:
349         // 2.1 - The current item is defined by a block argument. If the owner
350         // block is a non-entry one, then:
351         //       * Add the argument to blockArgsToDetensor.
352         //       * Walk the use-def chain backwards to add each predecessor's
353         //       terminator-operands corresponding to currentItem to workList.
354         if (currentItem.dyn_cast<BlockArgument>()) {
355           BlockArgument currentItemBlockArgument =
356               currentItem.cast<BlockArgument>();
357           Block *ownerBlock = currentItemBlockArgument.getOwner();
358 
359           // Function arguments are not detensored/converted.
360           if (&*ownerBlock->getParent()->begin() == ownerBlock)
361             continue;
362 
363           // This inner-block argument is involved in control-flow, it should be
364           // detensored.
365           blockArgsToDetensor.insert(currentItemBlockArgument);
366 
367           for (PredecessorIterator pred = ownerBlock->pred_begin();
368                pred != ownerBlock->pred_end(); ++pred) {
369             BranchOpInterface terminator =
370                 dyn_cast<BranchOpInterface>((*pred)->getTerminator());
371 
372             // TODO: For now, we give up if any of the control-flow components
373             // in a function is not detensorable. Fix that.
374             if (!terminator) {
375               opsToDetensor.clear();
376               blockArgsToDetensor.clear();
377               return;
378             }
379 
380             auto ownerBlockOperands =
381                 terminator.getSuccessorOperands(pred.getSuccessorIndex());
382 
383             if (!ownerBlockOperands || ownerBlockOperands->empty())
384               continue;
385 
386             // For each predecessor, add the value it passes to that argument to
387             // workList to find out how it's computed.
388             workList.push_back(
389                 ownerBlockOperands
390                     .getValue()[currentItemBlockArgument.getArgNumber()]);
391           }
392 
393           continue;
394         }
395 
396         Operation *currentItemDefiningOp = currentItem.getDefiningOp();
397 
398         if (!visitedOps.insert(currentItemDefiningOp).second)
399           continue;
400 
401         // 2.2 - The current item is computed by a GenericOp. If the op should
402         // be detensored, then:
403         //       * Add it to opsToDetensor.
404         //       * Add its operands to workList to discover other parts of the
405         //       potentially detensorable component.
406         if (auto genericOp = dyn_cast<GenericOp>(currentItemDefiningOp)) {
407           // The op was encountered already, no need to inspect it again.
408           if (opsToDetensor.count(genericOp))
409             continue;
410 
411           // TODO: For now, we give up if any of the control-flow components
412           // in a function is not detensorable. Fix that.
413           if (!shouldBeDetensored(genericOp, typeConverter)) {
414             opsToDetensor.clear();
415             blockArgsToDetensor.clear();
416             return;
417           }
418 
419           opsToDetensor.insert(genericOp);
420 
421           for (Value genericOpOperand : genericOp.inputs())
422             workList.push_back(genericOpOperand);
423 
424           continue;
425         }
426 
427         // 2.3 - The current item is the result of a FromElementsOp, it will be
428         // trivially detensored later as part of canonicalization patterns
429         // applied at the end of detensoring.
430         //
431         // Note: No need to check whether the result type of this op is
432         // detensorable since if it wasn't we wouldn't reach that point in the
433         // work list.
434         if (dyn_cast<tensor::FromElementsOp>(currentItemDefiningOp))
435           continue;
436 
437         // 2.4 - The current item is the result of a scalar op, add all its
438         // operands to the work list.
439         if (llvm::all_of(
440                 currentItemDefiningOp->getResultTypes(),
441                 [&](Type resultType) { return resultType.isIntOrFloat(); }))
442           for (Value scalarOpOperand : currentItemDefiningOp->getOperands())
443             workList.push_back(scalarOpOperand);
444       }
445     }
446   };
447 
448   /// Detensorize everything that can detensored.
449   class AggressiveDetensoringModel : public CostModel {
450   public:
451     void compute(FuncOp func, DetensorizeTypeConverter typeConverter,
452                  DenseSet<Operation *> &opsToDetensor,
453                  DenseSet<BlockArgument> &blockArgsToDetensor) override {
454       func.walk([&](GenericOp genericOp) {
455         if (shouldBeDetensored(genericOp, typeConverter))
456           opsToDetensor.insert(genericOp);
457       });
458 
459       for (Block &block : llvm::drop_begin(func.getBody(), 1))
460         for (BlockArgument blockArgument : block.getArguments())
461           blockArgsToDetensor.insert(blockArgument);
462     }
463   };
464 
465   void runOnFunction() override {
466     MLIRContext *context = &getContext();
467     DetensorizeTypeConverter typeConverter;
468     RewritePatternSet patterns(context);
469     ConversionTarget target(*context);
470     DenseSet<Operation *> opsToDetensor;
471     DenseMap<Operation *, DenseSet<int>> detensorableBranchOps;
472     DenseSet<BlockArgument> blockArgsToDetensor;
473 
474     if (aggressiveMode.getValue()) {
475       AggressiveDetensoringModel costModel;
476       costModel.compute(getFunction(), typeConverter, opsToDetensor,
477                         blockArgsToDetensor);
478 
479     } else {
480       PureControlFlowDetectionModel costModel;
481       costModel.compute(getFunction(), typeConverter, opsToDetensor,
482                         blockArgsToDetensor);
483     }
484 
485     detensorableBranchOps =
486         CostModel::computeBranchOpDetensoring(blockArgsToDetensor);
487 
488     target.addDynamicallyLegalOp<GenericOp>(
489         [&](GenericOp op) { return !opsToDetensor.count(op); });
490 
491     target.addDynamicallyLegalOp<FuncOp>([&](FuncOp op) {
492       // A function is legal if all of its non-entry blocks are legal. We
493       // don't legalize the entry block (i.e. the function's signature)
494       // since detensoring can't happen along external calling convention
495       // boundaries, which we conservatively approximate as all function
496       // signatures.
497       return llvm::all_of(llvm::drop_begin(op.getBody(), 1), [&](Block &block) {
498         if (llvm::any_of(blockArgsToDetensor, [&](BlockArgument blockArgument) {
499               return blockArgument.getOwner() == &block &&
500                      !typeConverter.isLegal(blockArgument.getType());
501             })) {
502           return false;
503         }
504         return true;
505       });
506     });
507 
508     target.markUnknownOpDynamicallyLegal([&](Operation *op) {
509       if (isNotBranchOpInterfaceOrReturnLikeOp(op) ||
510           isLegalForReturnOpTypeConversionPattern(op, typeConverter,
511                                                   /*returnOpAlwaysLegal*/ true))
512         return true;
513 
514       if (auto branchOp = dyn_cast<BranchOpInterface>(op)) {
515         if (!detensorableBranchOps.count(branchOp))
516           return true;
517 
518         for (auto operandIdx : detensorableBranchOps[branchOp])
519           if (!typeConverter.isLegal(
520                   branchOp->getOperand(operandIdx).getType()))
521             return false;
522 
523         return true;
524       }
525 
526       return false;
527     });
528 
529     patterns.insert<DetensorizeGenericOp>(typeConverter, context);
530     patterns.insert<FunctionNonEntryBlockConversion>(FuncOp::getOperationName(),
531                                                      context, typeConverter,
532                                                      blockArgsToDetensor);
533     // Since non-entry block arguments get detensorized, we also need to
534     // update the control flow inside the function to reflect the correct
535     // types.
536     auto shouldConvertBranchOperand = [&](BranchOpInterface branchOp,
537                                           int operandIdx) -> bool {
538       return detensorableBranchOps.count(branchOp) &&
539              detensorableBranchOps[branchOp].count(operandIdx);
540     };
541 
542     populateBranchOpInterfaceTypeConversionPattern(patterns, typeConverter,
543                                                    shouldConvertBranchOperand);
544 
545     if (failed(applyFullConversion(getFunction(), target, std::move(patterns))))
546       signalPassFailure();
547 
548     RewritePatternSet canonPatterns(context);
549     canonPatterns.add<ExtractFromReshapeFromElements>(context);
550     if (failed(applyPatternsAndFoldGreedily(getFunction(),
551                                             std::move(canonPatterns))))
552       signalPassFailure();
553   }
554 
555   Option<bool> aggressiveMode{
556       *this, "aggressive-mode",
557       llvm::cl::desc("Detensorize all ops that qualify for detensoring along "
558                      "with branch operands and basic-block arguments.")};
559 };
560 } // namespace
561 
562 std::unique_ptr<Pass> mlir::createLinalgDetensorizePass() {
563   return std::make_unique<LinalgDetensorize>();
564 }
565