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