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       : LinalgDetensorizeBase<LinalgDetensorize>() {}
198 
199   class CostModel {
200   public:
201     virtual ~CostModel() = default;
202 
203     /// A cost model algorithm computes the following outputs:
204     ///
205     /// - opsToDetensor: the list of linalg ops that should be
206     /// detensored.
207     ///
208     /// - blockArgsToDetensor: since the operands and results of detensored
209     /// linalg ops can cross the BB boundary (e.g. a linalg op's input can come
210     /// from a BB argument and a linalg op's output can be passed to successor
211     /// BBs), we need to maintain the sub-set of arguments that should be
212     /// detensored (i.e. converted by typeConverter) for each affected BB.
213     ///
214     /// Example:
215     ///
216     /// For the following snippet:
217     /// ...
218     /// ^bb1(%6: tensor<i32>, %9: tensor<i32>):
219     ///   %7 = linalg.init_tensor [] : tensor<i32>
220     ///   %8 = linalg.generic #attrs
221     ///     ins(%6, %6 : tensor<i32>, tensor<i32>)
222     ///     outs(%7 : tensor<i32>) {
223     ///     ^bb0(%arg0: i32, %arg1: i32, %arg2: i32):
224     ///       %9 = addi %arg0, %arg1 : i32
225     ///       linalg.yield %9 : i32
226     ///   } -> tensor<i32>
227     ///   %10 = "some.op"(%9)
228     ///   br ^bb2(%8 : tensor<i32>)
229     /// ...
230     ///
231     /// if the cost model decides that the linalg.generic op should be
232     /// detensored, then:
233     /// - opsToDetensor should be = {linalg.generic{add}}.
234     /// - blockArgsToDetensor should be = {bb1 -> {0}, bb2 -> {0}}.
235     virtual void compute(FuncOp func, DetensorizeTypeConverter typeConverter,
236                          DenseSet<Operation *> &opsToDetensor,
237                          DenseSet<BlockArgument> &blockArgsToDetensor) = 0;
238 
239     /// From the blockArgsToDetensor set computed by a CostModel
240     /// implementation, this method computes the corresponding branch op
241     /// detensoring. The result is a map from a branch op to a subset of indices
242     /// of its operands. The indices specify which of the branch op's operands
243     /// should be detensored.
244     ///
245     /// For the previous example, this method would compute: {bb2 -> {0}}.
246     static DenseMap<Operation *, DenseSet<int>> computeBranchOpDetensoring(
247         const DenseSet<BlockArgument> &blockArgsToDetensor) {
248       DenseMap<Operation *, DenseSet<int>> detensorableBranchOps;
249 
250       for (auto blockArgumentElem : blockArgsToDetensor) {
251         Block *block = blockArgumentElem.getOwner();
252 
253         for (PredecessorIterator pred = block->pred_begin();
254              pred != block->pred_end(); ++pred) {
255           BranchOpInterface terminator =
256               dyn_cast<BranchOpInterface>((*pred)->getTerminator());
257           auto blockOperands =
258               terminator.getSuccessorOperands(pred.getSuccessorIndex());
259 
260           if (!blockOperands || blockOperands->empty())
261             continue;
262 
263           detensorableBranchOps[terminator].insert(
264               blockOperands->getBeginOperandIndex() +
265               blockArgumentElem.getArgNumber());
266         }
267       }
268 
269       return detensorableBranchOps;
270     }
271   };
272 
273   /// Detensorize linalg ops involved in control-flow within a function.
274   ///
275   /// This model starts from CondBranchOps within a function. For each cond_br,
276   /// the model then walks the use-def chain for the branch's condition
277   /// backwards in order to understand where the condition's value comes from.
278   /// If the condition value is (indirectly) computed by a linalg op that can be
279   /// detensored, the model then continues walking the use-def chain in order to
280   /// understand where the linalg op's operands come from. This leads to
281   /// discovering a "detensoring component". A detensoring component is the set
282   /// of operations + block arguments that are involved in control-flow AND can
283   /// be detensored.
284   ///
285   /// For examples where this model succeeds to discover a detensoring
286   /// component, see:
287   /// - test/Dialect/Linalg/detensorize_while.mlir
288   /// - test/Dialect/Linalg/detesorize_while_pure_cf.mlir.
289   ///
290   /// For an example where this model marks control-flow as "non-detensorable",
291   /// see:
292   /// - test/Dialect/Linalg/detensorize_while_failure.mlir
293   class PureControlFlowDetectionModel : public CostModel {
294   public:
295     void compute(FuncOp func, DetensorizeTypeConverter typeConverter,
296                  DenseSet<Operation *> &opsToDetensor,
297                  DenseSet<BlockArgument> &blockArgsToDetensor) override {
298       SmallVector<Value> workList;
299 
300       func.walk([&](CondBranchOp condBr) {
301         for (auto operand : condBr.getOperands()) {
302           workList.push_back(operand);
303         }
304       });
305 
306       func.walk([&](BranchOp br) {
307         for (auto operand : br.getOperands()) {
308           workList.push_back(operand);
309         }
310       });
311 
312       DenseSet<Value> visitedValues;
313       DenseSet<Operation *> visitedOps;
314 
315       // For a (to-be-detesored) value, check if it "escapes" the block by being
316       // passed to terminator. If it does, then workList is updated with the
317       // corresponding argument to the successor block.
318       auto updateWorkListWithSuccessorArguments =
319           [&](Value value, BranchOpInterface terminator) {
320             if (!terminator)
321               return;
322 
323             for (auto operandIdx :
324                  llvm::seq<unsigned>(0, terminator->getOperands().size())) {
325               Value operand = terminator->getOperand(operandIdx);
326 
327               if (operand == value) {
328                 auto succBlockArg =
329                     terminator.getSuccessorBlockArgument(operandIdx);
330 
331                 if (succBlockArg && !blockArgsToDetensor.count(*succBlockArg))
332                   workList.push_back(*succBlockArg);
333               }
334             }
335           };
336 
337       while (!workList.empty()) {
338         Value currentItem = workList.pop_back_val();
339 
340         if (!visitedValues.insert(currentItem).second)
341           continue;
342 
343         // 1   - Look forward:
344         // 1.1 - If currentItem escapes to one or more successors, add
345         // the corresponding successor arguments to workList.
346         updateWorkListWithSuccessorArguments(
347             currentItem, dyn_cast<BranchOpInterface>(
348                              currentItem.getParentBlock()->getTerminator()));
349 
350         // 1.2 - For each user of currentItem, add the defined values to
351         // workList. This way, the user ops can be inspected later if they are
352         // detensorable and if so, their operands will be added to workList to
353         // potentially discover other parts of the detensorable component.
354         for (auto *user : currentItem.getUsers())
355           for (Value result : user->getResults())
356             workList.push_back(result);
357 
358         // 2   - Look backward:
359         // 2.1 - The current item is defined by a block argument. If the owner
360         // block is a non-entry one, then:
361         //       * Add the argument to blockArgsToDetensor.
362         //       * Walk the use-def chain backwards to add each predecessor's
363         //       terminator-operands corresponding to currentItem to workList.
364         if (currentItem.dyn_cast<BlockArgument>()) {
365           BlockArgument currentItemBlockArgument =
366               currentItem.cast<BlockArgument>();
367           Block *ownerBlock = currentItemBlockArgument.getOwner();
368 
369           // Function arguments are not detensored/converted.
370           if (&*ownerBlock->getParent()->begin() == ownerBlock)
371             continue;
372 
373           // This inner-block argument is involved in control-flow, it should be
374           // detensored.
375           blockArgsToDetensor.insert(currentItemBlockArgument);
376 
377           for (PredecessorIterator pred = ownerBlock->pred_begin();
378                pred != ownerBlock->pred_end(); ++pred) {
379             BranchOpInterface terminator =
380                 dyn_cast<BranchOpInterface>((*pred)->getTerminator());
381 
382             // TODO: For now, we give up if any of the control-flow components
383             // in a function is not detensorable. Fix that.
384             if (!terminator) {
385               opsToDetensor.clear();
386               blockArgsToDetensor.clear();
387               return;
388             }
389 
390             auto ownerBlockOperands =
391                 terminator.getSuccessorOperands(pred.getSuccessorIndex());
392 
393             if (!ownerBlockOperands || ownerBlockOperands->empty())
394               continue;
395 
396             // For each predecessor, add the value it passes to that argument to
397             // workList to find out how it's computed.
398             workList.push_back(
399                 ownerBlockOperands
400                     .getValue()[currentItemBlockArgument.getArgNumber()]);
401           }
402 
403           continue;
404         }
405 
406         Operation *currentItemDefiningOp = currentItem.getDefiningOp();
407 
408         if (!visitedOps.insert(currentItemDefiningOp).second)
409           continue;
410 
411         // 2.2 - The current item is computed by a GenericOp. If the op should
412         // be detensored, then:
413         //       * Add it to opsToDetensor.
414         //       * Add its operands to workList to discover other parts of the
415         //       potentially detensorable component.
416         if (auto genericOp = dyn_cast<GenericOp>(currentItemDefiningOp)) {
417           // The op was encountered already, no need to inspect it again.
418           if (opsToDetensor.count(genericOp))
419             continue;
420 
421           // TODO: For now, we give up if any of the control-flow components
422           // in a function is not detensorable. Fix that.
423           if (!shouldBeDetensored(genericOp, typeConverter)) {
424             opsToDetensor.clear();
425             blockArgsToDetensor.clear();
426             return;
427           }
428 
429           opsToDetensor.insert(genericOp);
430 
431           for (Value genericOpOperand : genericOp.inputs())
432             workList.push_back(genericOpOperand);
433 
434           continue;
435         }
436 
437         // 2.3 - The current item is the result of a FromElementsOp, it will be
438         // trivially detensored later as part of canonicalization patterns
439         // applied at the end of detensoring.
440         //
441         // Note: No need to check whether the result type of this op is
442         // detensorable since if it wasn't we wouldn't reach that point in the
443         // work list.
444         if (dyn_cast<tensor::FromElementsOp>(currentItemDefiningOp))
445           continue;
446 
447         // 2.4 - The current item is the result of a scalar op, add all its
448         // operands to the work list.
449         if (llvm::all_of(
450                 currentItemDefiningOp->getResultTypes(),
451                 [&](Type resultType) { return resultType.isIntOrFloat(); }))
452           for (Value scalarOpOperand : currentItemDefiningOp->getOperands())
453             workList.push_back(scalarOpOperand);
454       }
455     }
456   };
457 
458   /// Detensorize everything that can detensored.
459   class AggressiveDetensoringModel : public CostModel {
460   public:
461     void compute(FuncOp func, DetensorizeTypeConverter typeConverter,
462                  DenseSet<Operation *> &opsToDetensor,
463                  DenseSet<BlockArgument> &blockArgsToDetensor) override {
464       func.walk([&](GenericOp genericOp) {
465         if (shouldBeDetensored(genericOp, typeConverter))
466           opsToDetensor.insert(genericOp);
467       });
468 
469       for (Block &block : llvm::drop_begin(func.getBody(), 1))
470         for (BlockArgument blockArgument : block.getArguments())
471           blockArgsToDetensor.insert(blockArgument);
472     }
473   };
474 
475   void runOnFunction() override {
476     MLIRContext *context = &getContext();
477     DetensorizeTypeConverter typeConverter;
478     RewritePatternSet patterns(context);
479     ConversionTarget target(*context);
480     DenseSet<Operation *> opsToDetensor;
481     DenseMap<Operation *, DenseSet<int>> detensorableBranchOps;
482     DenseSet<BlockArgument> blockArgsToDetensor;
483 
484     if (aggressiveMode.getValue()) {
485       AggressiveDetensoringModel costModel;
486       costModel.compute(getFunction(), typeConverter, opsToDetensor,
487                         blockArgsToDetensor);
488 
489     } else {
490       PureControlFlowDetectionModel costModel;
491       costModel.compute(getFunction(), typeConverter, opsToDetensor,
492                         blockArgsToDetensor);
493     }
494 
495     detensorableBranchOps =
496         CostModel::computeBranchOpDetensoring(blockArgsToDetensor);
497 
498     target.addDynamicallyLegalOp<GenericOp>(
499         [&](GenericOp op) { return !opsToDetensor.count(op); });
500 
501     target.addDynamicallyLegalOp<FuncOp>([&](FuncOp op) {
502       // A function is legal if all of its non-entry blocks are legal. We
503       // don't legalize the entry block (i.e. the function's signature)
504       // since detensoring can't happen along external calling convention
505       // boundaries, which we conservatively approximate as all function
506       // signatures.
507       return llvm::all_of(llvm::drop_begin(op.getBody(), 1), [&](Block &block) {
508         if (llvm::any_of(blockArgsToDetensor, [&](BlockArgument blockArgument) {
509               return blockArgument.getOwner() == &block &&
510                      !typeConverter.isLegal(blockArgument.getType());
511             })) {
512           return false;
513         }
514         return true;
515       });
516     });
517 
518     target.markUnknownOpDynamicallyLegal([&](Operation *op) {
519       if (isNotBranchOpInterfaceOrReturnLikeOp(op) ||
520           isLegalForReturnOpTypeConversionPattern(op, typeConverter,
521                                                   /*returnOpAlwaysLegal*/ true))
522         return true;
523 
524       if (auto branchOp = dyn_cast<BranchOpInterface>(op)) {
525         if (!detensorableBranchOps.count(branchOp))
526           return true;
527 
528         for (auto operandIdx : detensorableBranchOps[branchOp])
529           if (!typeConverter.isLegal(
530                   branchOp->getOperand(operandIdx).getType()))
531             return false;
532 
533         return true;
534       }
535 
536       return false;
537     });
538 
539     patterns.insert<DetensorizeGenericOp>(typeConverter, context);
540     patterns.insert<FunctionNonEntryBlockConversion>(FuncOp::getOperationName(),
541                                                      context, typeConverter,
542                                                      blockArgsToDetensor);
543     // Since non-entry block arguments get detensorized, we also need to
544     // update the control flow inside the function to reflect the correct
545     // types.
546     auto shouldConvertBranchOperand = [&](BranchOpInterface branchOp,
547                                           int operandIdx) -> bool {
548       return detensorableBranchOps.count(branchOp) &&
549              detensorableBranchOps[branchOp].count(operandIdx);
550     };
551 
552     populateBranchOpInterfaceTypeConversionPattern(patterns, typeConverter,
553                                                    shouldConvertBranchOperand);
554 
555     if (failed(applyFullConversion(getFunction(), target, std::move(patterns))))
556       signalPassFailure();
557 
558     RewritePatternSet canonPatterns(context);
559     canonPatterns.add<ExtractFromReshapeFromElements>(context);
560     if (failed(applyPatternsAndFoldGreedily(getFunction(),
561                                             std::move(canonPatterns))))
562       signalPassFailure();
563   }
564 
565   Option<bool> aggressiveMode{
566       *this, "aggressive-mode",
567       llvm::cl::desc("Detensorize all ops that qualify for detensoring along "
568                      "with branch operands and basic-block arguments.")};
569 };
570 } // namespace
571 
572 std::unique_ptr<Pass> mlir::createLinalgDetensorizePass() {
573   return std::make_unique<LinalgDetensorize>();
574 }
575