1 //===- Bufferize.cpp - Bufferization utilities ----------------------------===//
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 
11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
13 #include "mlir/Dialect/Bufferization/Transforms/Bufferize.h"
14 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
15 #include "mlir/Dialect/Bufferization/Transforms/OneShotModuleBufferize.h"
16 #include "mlir/Dialect/Bufferization/Transforms/Passes.h"
17 #include "mlir/Dialect/Func/IR/FuncOps.h"
18 #include "mlir/Dialect/MemRef/IR/MemRef.h"
19 #include "mlir/IR/Operation.h"
20 #include "mlir/Pass/PassManager.h"
21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
22 #include "mlir/Transforms/Passes.h"
23 
24 using namespace mlir;
25 using namespace mlir::bufferization;
26 
27 //===----------------------------------------------------------------------===//
28 // BufferizeTypeConverter
29 //===----------------------------------------------------------------------===//
30 
31 static Value materializeToTensor(OpBuilder &builder, TensorType type,
32                                  ValueRange inputs, Location loc) {
33   assert(inputs.size() == 1);
34   assert(inputs[0].getType().isa<BaseMemRefType>());
35   return builder.create<bufferization::ToTensorOp>(loc, type, inputs[0]);
36 }
37 
38 /// Registers conversions into BufferizeTypeConverter
39 BufferizeTypeConverter::BufferizeTypeConverter() {
40   // Keep all types unchanged.
41   addConversion([](Type type) { return type; });
42   // Convert RankedTensorType to MemRefType.
43   addConversion([](RankedTensorType type) -> Type {
44     return MemRefType::get(type.getShape(), type.getElementType());
45   });
46   // Convert UnrankedTensorType to UnrankedMemRefType.
47   addConversion([](UnrankedTensorType type) -> Type {
48     return UnrankedMemRefType::get(type.getElementType(), 0);
49   });
50   addArgumentMaterialization(materializeToTensor);
51   addSourceMaterialization(materializeToTensor);
52   addTargetMaterialization([](OpBuilder &builder, BaseMemRefType type,
53                               ValueRange inputs, Location loc) -> Value {
54     assert(inputs.size() == 1 && "expected exactly one input");
55 
56     if (auto inputType = inputs[0].getType().dyn_cast<MemRefType>()) {
57       // MemRef to MemRef cast.
58       assert(inputType != type && "expected different types");
59       // Unranked to ranked and ranked to unranked casts must be explicit.
60       auto rankedDestType = type.dyn_cast<MemRefType>();
61       if (!rankedDestType)
62         return nullptr;
63       FailureOr<Value> replacement =
64           castOrReallocMemRefValue(builder, inputs[0], rankedDestType);
65       if (failed(replacement))
66         return nullptr;
67       return *replacement;
68     }
69 
70     if (inputs[0].getType().isa<TensorType>()) {
71       // Tensor to MemRef cast.
72       return builder.create<bufferization::ToMemrefOp>(loc, type, inputs[0]);
73     }
74 
75     llvm_unreachable("only tensor/memref input types supported");
76   });
77 }
78 
79 void mlir::bufferization::populateBufferizeMaterializationLegality(
80     ConversionTarget &target) {
81   target.addLegalOp<bufferization::ToTensorOp, bufferization::ToMemrefOp>();
82 }
83 
84 namespace {
85 // In a finalizing bufferize conversion, we know that all tensors have been
86 // converted to memrefs, thus, this op becomes an identity.
87 class BufferizeToTensorOp
88     : public OpConversionPattern<bufferization::ToTensorOp> {
89 public:
90   using OpConversionPattern::OpConversionPattern;
91   LogicalResult
92   matchAndRewrite(bufferization::ToTensorOp op, OpAdaptor adaptor,
93                   ConversionPatternRewriter &rewriter) const override {
94     rewriter.replaceOp(op, adaptor.memref());
95     return success();
96   }
97 };
98 } // namespace
99 
100 namespace {
101 // In a finalizing bufferize conversion, we know that all tensors have been
102 // converted to memrefs, thus, this op becomes an identity.
103 class BufferizeToMemrefOp
104     : public OpConversionPattern<bufferization::ToMemrefOp> {
105 public:
106   using OpConversionPattern::OpConversionPattern;
107   LogicalResult
108   matchAndRewrite(bufferization::ToMemrefOp op, OpAdaptor adaptor,
109                   ConversionPatternRewriter &rewriter) const override {
110     rewriter.replaceOp(op, adaptor.tensor());
111     return success();
112   }
113 };
114 } // namespace
115 
116 void mlir::bufferization::populateEliminateBufferizeMaterializationsPatterns(
117     BufferizeTypeConverter &typeConverter, RewritePatternSet &patterns) {
118   patterns.add<BufferizeToTensorOp, BufferizeToMemrefOp>(typeConverter,
119                                                          patterns.getContext());
120 }
121 
122 namespace {
123 struct FinalizingBufferizePass
124     : public FinalizingBufferizeBase<FinalizingBufferizePass> {
125   using FinalizingBufferizeBase<
126       FinalizingBufferizePass>::FinalizingBufferizeBase;
127 
128   void runOnOperation() override {
129     auto func = getOperation();
130     auto *context = &getContext();
131 
132     BufferizeTypeConverter typeConverter;
133     RewritePatternSet patterns(context);
134     ConversionTarget target(*context);
135 
136     populateEliminateBufferizeMaterializationsPatterns(typeConverter, patterns);
137 
138     // If all result types are legal, and all block arguments are legal (ensured
139     // by func conversion above), then all types in the program are legal.
140     //
141     // We also check that the operand types are legal to avoid creating invalid
142     // IR. For example, this prevents
143     // populateEliminateBufferizeMaterializationsPatterns from updating the
144     // types of the operands to a return op without updating the enclosing
145     // function.
146     target.markUnknownOpDynamicallyLegal(
147         [&](Operation *op) { return typeConverter.isLegal(op); });
148 
149     if (failed(applyFullConversion(func, target, std::move(patterns))))
150       signalPassFailure();
151   }
152 };
153 
154 static BufferizationOptions::LayoutMapOption
155 parseLayoutMapOption(const std::string &s) {
156   if (s == "fully-dynamic-layout-map")
157     return BufferizationOptions::LayoutMapOption::FullyDynamicLayoutMap;
158   if (s == "identity-layout-map")
159     return BufferizationOptions::LayoutMapOption::IdentityLayoutMap;
160   if (s == "infer-layout-map")
161     return BufferizationOptions::LayoutMapOption::InferLayoutMap;
162   llvm_unreachable("invalid layout map option");
163 }
164 
165 struct OneShotBufferizePass
166     : public OneShotBufferizeBase<OneShotBufferizePass> {
167   OneShotBufferizePass() : OneShotBufferizeBase<OneShotBufferizePass>() {}
168 
169   explicit OneShotBufferizePass(const OneShotBufferizationOptions &options)
170       : options(options) {}
171 
172   void getDependentDialects(DialectRegistry &registry) const override {
173     registry
174         .insert<bufferization::BufferizationDialect, memref::MemRefDialect>();
175     registerAllocationOpInterfaceExternalModels(registry);
176   }
177 
178   void runOnOperation() override {
179     OneShotBufferizationOptions opt;
180     if (!options) {
181       // Make new bufferization options if none were provided when creating the
182       // pass.
183       opt.allowReturnAllocs = allowReturnAllocs;
184       opt.allowUnknownOps = allowUnknownOps;
185       opt.analysisFuzzerSeed = analysisFuzzerSeed;
186       opt.createDeallocs = createDeallocs;
187       opt.functionBoundaryTypeConversion =
188           parseLayoutMapOption(functionBoundaryTypeConversion);
189       opt.printConflicts = printConflicts;
190       opt.testAnalysisOnly = testAnalysisOnly;
191       opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries;
192       opt.unknownTypeConversion = parseLayoutMapOption(unknownTypeConversion);
193 
194       OpFilter::Entry::FilterFn filterFn =
195           [&](Operation *op) {
196             // Filter may be specified via options.
197             if (this->dialectFilter.hasValue())
198               return llvm::is_contained(this->dialectFilter,
199                                         op->getDialect()->getNamespace());
200             // No filter specified: All other ops are allowed.
201             return true;
202           };
203       opt.opFilter.allowOperation(filterFn);
204     } else {
205       opt = *options;
206     }
207 
208     ModuleOp moduleOp = getOperation();
209     if (opt.bufferizeFunctionBoundaries) {
210       if (failed(runOneShotModuleBufferize(moduleOp, opt))) {
211         signalPassFailure();
212         return;
213       }
214     } else {
215       if (failed(runOneShotBufferize(moduleOp, opt))) {
216         signalPassFailure();
217         return;
218       }
219     }
220 
221     if (opt.testAnalysisOnly)
222       return;
223 
224     OpPassManager cleanupPipeline("builtin.module");
225     cleanupPipeline.addPass(createCanonicalizerPass());
226     cleanupPipeline.addPass(createCSEPass());
227     cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
228     (void)runPipeline(cleanupPipeline, moduleOp);
229   }
230 
231 private:
232   llvm::Optional<OneShotBufferizationOptions> options;
233 };
234 } // namespace
235 
236 namespace {
237 struct BufferizationBufferizePass
238     : public BufferizationBufferizeBase<BufferizationBufferizePass> {
239   void runOnOperation() override {
240     BufferizationOptions options = getPartialBufferizationOptions();
241     options.opFilter.allowDialect<BufferizationDialect>();
242 
243     if (failed(bufferizeOp(getOperation(), options)))
244       signalPassFailure();
245   }
246 
247   void getDependentDialects(DialectRegistry &registry) const override {
248     registry
249         .insert<bufferization::BufferizationDialect, memref::MemRefDialect>();
250   }
251 };
252 } // namespace
253 
254 std::unique_ptr<Pass> mlir::bufferization::createBufferizationBufferizePass() {
255   return std::make_unique<BufferizationBufferizePass>();
256 }
257 
258 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() {
259   return std::make_unique<OneShotBufferizePass>();
260 }
261 
262 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass(
263     const OneShotBufferizationOptions &options) {
264   return std::make_unique<OneShotBufferizePass>(options);
265 }
266 
267 std::unique_ptr<OperationPass<func::FuncOp>>
268 mlir::bufferization::createFinalizingBufferizePass() {
269   return std::make_unique<FinalizingBufferizePass>();
270 }
271 
272 //===----------------------------------------------------------------------===//
273 // BufferizableOpInterface-based Bufferization
274 //===----------------------------------------------------------------------===//
275 
276 static bool isaTensor(Type t) { return t.isa<TensorType>(); }
277 
278 /// Return true if the given op has a tensor result or a tensor operand.
279 static bool hasTensorSemantics(Operation *op) {
280   if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
281     bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor);
282     bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor);
283     return hasTensorArg || hasTensorResult;
284   }
285 
286   bool hasTensorResult = any_of(op->getResultTypes(), isaTensor);
287   bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor);
288   return hasTensorResult || hasTensorOperand;
289 }
290 
291 LogicalResult bufferization::bufferizeOp(Operation *op,
292                                          const AnalysisState &analysisState) {
293   // Catch incorrect API usage.
294   assert((analysisState.hasDialectState(
295               func::FuncDialect::getDialectNamespace()) ||
296           !analysisState.getOptions().bufferizeFunctionBoundaries) &&
297          "must use ModuleBufferize to bufferize function boundaries");
298 
299   BufferizationState bufferizationState(analysisState);
300   if (failed(bufferizeOp(op, bufferizationState)))
301     return failure();
302   return success();
303 }
304 
305 namespace {
306 /// A rewriter that keeps track of extra information during bufferization.
307 class BufferizationRewriter : public IRRewriter {
308 public:
309   BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps,
310                         DenseSet<Operation *> &toMemrefOps,
311                         const BufferizationOptions &options,
312                         const OpFilter *opFilter)
313       : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps),
314         options(options), opFilter(opFilter) {}
315 
316 protected:
317   void notifyOperationRemoved(Operation *op) override {
318     IRRewriter::notifyOperationRemoved(op);
319     erasedOps.insert(op);
320     // Erase if present.
321     toMemrefOps.erase(op);
322   }
323 
324   void notifyOperationInserted(Operation *op) override {
325     IRRewriter::notifyOperationInserted(op);
326 
327     // Keep track of to_memref ops.
328     if (isa<ToMemrefOp>(op)) {
329       toMemrefOps.insert(op);
330       return;
331     }
332 
333     // Skip to_tensor ops.
334     if (isa<ToTensorOp>(op))
335       return;
336 
337     // Skip non-tensor ops.
338     if (!hasTensorSemantics(op))
339       return;
340 
341     // Skip ops that are not allowed.
342     if (!options.isOpAllowed(op) || (opFilter && !opFilter->isOpAllowed(op)))
343       return;
344 
345     // Adding new bufferizable ops is not allowed during bufferization. Such ops
346     // would not be analyzed and can lead to surprising behavior.
347     llvm_unreachable(
348         "creating new tensor ops is not allowed during bufferization");
349   }
350 
351 private:
352   /// A set of all erased ops.
353   DenseSet<Operation *> &erasedOps;
354 
355   /// A set of all to_memref ops.
356   DenseSet<Operation *> &toMemrefOps;
357 
358   /// The bufferization options.
359   /// Used for debug modes.
360   LLVM_ATTRIBUTE_UNUSED
361   const BufferizationOptions &options;
362 
363   const OpFilter *opFilter;
364 };
365 } // namespace
366 
367 LogicalResult bufferization::bufferizeOp(Operation *op,
368                                          BufferizationState &bufferizationState,
369                                          const OpFilter *opFilter) {
370   const auto &options = bufferizationState.getOptions();
371   assert(options.unknownTypeConversion !=
372              BufferizationOptions::LayoutMapOption::InferLayoutMap &&
373          "invalid layout map option");
374 
375   // Keep track of to_memref ops.
376   DenseSet<Operation *> toMemrefOps;
377   op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); });
378 
379   // Gather all bufferizable ops in top-to-bottom order.
380   //
381   // We should ideally know the exact memref type of all operands when
382   // bufferizing an op. (This is the case when bufferizing top-to-bottom.)
383   // Otherwise, we have to use a memref type with a fully dynamic layout map to
384   // avoid copies. We are currently missing patterns for layout maps to
385   // canonicalize away (or canonicalize to more precise layouts).
386   SmallVector<Operation *> worklist;
387   op->walk<WalkOrder::PreOrder>([&](Operation *op) {
388     if (hasTensorSemantics(op))
389       worklist.push_back(op);
390   });
391 
392   // Keep track of all erased ops.
393   DenseSet<Operation *> erasedOps;
394 
395   // Bufferize all ops.
396   BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps,
397                                  bufferizationState.getOptions(), opFilter);
398   for (unsigned i = 0; i < worklist.size(); ++i) {
399     Operation *op = worklist[i];
400     // Skip ops that were erased.
401     if (erasedOps.contains(op))
402       continue;
403     // Skip ops that are not bufferizable or not allowed.
404     auto bufferizableOp = options.dynCastBufferizableOp(op);
405     if (!bufferizableOp)
406       continue;
407     if (opFilter && !opFilter->isOpAllowed(op))
408       continue;
409     // Skip ops that no longer have tensor semantics.
410     if (!hasTensorSemantics(op))
411       continue;
412     // Bufferize the op.
413     rewriter.setInsertionPoint(op);
414     if (failed(bufferizableOp.bufferize(rewriter, bufferizationState)))
415       return op->emitError("failed to bufferize op");
416   }
417 
418   // Fold all to_memref(to_tensor(x)) pairs.
419   for (Operation *op : toMemrefOps) {
420     rewriter.setInsertionPoint(op);
421     (void)bufferization::foldToMemrefToTensorPair(rewriter,
422                                                   cast<ToMemrefOp>(op));
423   }
424 
425   /// Check the result of bufferization. Return an error if an op was not
426   /// bufferized, unless partial bufferization is allowed.
427   if (bufferizationState.getOptions().allowUnknownOps)
428     return success();
429 
430   for (Operation *op : worklist) {
431     // Skip ops that are entirely gone.
432     if (erasedOps.contains(op))
433       continue;
434     // Ops that no longer have tensor semantics (because they were updated
435     // in-place) are allowed.
436     if (!hasTensorSemantics(op))
437       continue;
438     // Continue ops that are not allowed.
439     if (!options.isOpAllowed(op))
440       continue;
441     if (opFilter && !opFilter->isOpAllowed(op))
442       continue;
443     // Ops without any uses and no side effects will fold away.
444     if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op))
445       continue;
446     return op->emitError("op was not bufferized");
447   }
448 
449   return success();
450 }
451 
452 LogicalResult bufferization::bufferizeOp(Operation *op,
453                                          const BufferizationOptions &options) {
454   AnalysisState state(options);
455   return bufferizeOp(op, state);
456 }
457 
458 BufferizationOptions bufferization::getPartialBufferizationOptions() {
459   BufferizationOptions options;
460   options.allowUnknownOps = true;
461   options.createDeallocs = false;
462   options.unknownTypeConversion =
463       BufferizationOptions::LayoutMapOption::IdentityLayoutMap;
464   return options;
465 }
466