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.dropEquivalentFuncResults = dropEquivalentFuncResults;
184       opt.allowReturnAllocs = allowReturnAllocs;
185       opt.allowUnknownOps = allowUnknownOps;
186       opt.alwaysAliasingWithDest = alwaysAliasingWithDest;
187       opt.analysisFuzzerSeed = analysisFuzzerSeed;
188       opt.createDeallocs = createDeallocs;
189       opt.functionBoundaryTypeConversion =
190           parseLayoutMapOption(functionBoundaryTypeConversion);
191       opt.printConflicts = printConflicts;
192       opt.testAnalysisOnly = testAnalysisOnly;
193       opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries;
194       opt.promoteBufferResultsToOutParams = promoteBufferResultsToOutParams;
195       opt.unknownTypeConversion = parseLayoutMapOption(unknownTypeConversion);
196 
197       OpFilter::Entry::FilterFn filterFn =
198           [&](Operation *op) {
199             // Filter may be specified via options.
200             if (this->dialectFilter.hasValue())
201               return llvm::is_contained(this->dialectFilter,
202                                         op->getDialect()->getNamespace());
203             // No filter specified: All other ops are allowed.
204             return true;
205           };
206       opt.opFilter.allowOperation(filterFn);
207     } else {
208       opt = *options;
209     }
210 
211     ModuleOp moduleOp = getOperation();
212     if (opt.bufferizeFunctionBoundaries) {
213       if (failed(runOneShotModuleBufferize(moduleOp, opt))) {
214         signalPassFailure();
215         return;
216       }
217     } else {
218       if (failed(runOneShotBufferize(moduleOp, opt))) {
219         signalPassFailure();
220         return;
221       }
222     }
223 
224     if (opt.testAnalysisOnly)
225       return;
226 
227     OpPassManager cleanupPipeline("builtin.module");
228     cleanupPipeline.addPass(createCanonicalizerPass());
229     cleanupPipeline.addPass(createCSEPass());
230     cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
231     (void)runPipeline(cleanupPipeline, moduleOp);
232   }
233 
234 private:
235   llvm::Optional<OneShotBufferizationOptions> options;
236 };
237 } // namespace
238 
239 namespace {
240 struct BufferizationBufferizePass
241     : public BufferizationBufferizeBase<BufferizationBufferizePass> {
242   void runOnOperation() override {
243     BufferizationOptions options = getPartialBufferizationOptions();
244     options.opFilter.allowDialect<BufferizationDialect>();
245 
246     if (failed(bufferizeOp(getOperation(), options)))
247       signalPassFailure();
248   }
249 
250   void getDependentDialects(DialectRegistry &registry) const override {
251     registry
252         .insert<bufferization::BufferizationDialect, memref::MemRefDialect>();
253   }
254 };
255 } // namespace
256 
257 std::unique_ptr<Pass> mlir::bufferization::createBufferizationBufferizePass() {
258   return std::make_unique<BufferizationBufferizePass>();
259 }
260 
261 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() {
262   return std::make_unique<OneShotBufferizePass>();
263 }
264 
265 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass(
266     const OneShotBufferizationOptions &options) {
267   return std::make_unique<OneShotBufferizePass>(options);
268 }
269 
270 std::unique_ptr<OperationPass<func::FuncOp>>
271 mlir::bufferization::createFinalizingBufferizePass() {
272   return std::make_unique<FinalizingBufferizePass>();
273 }
274 
275 //===----------------------------------------------------------------------===//
276 // BufferizableOpInterface-based Bufferization
277 //===----------------------------------------------------------------------===//
278 
279 static bool isaTensor(Type t) { return t.isa<TensorType>(); }
280 
281 /// Return true if the given op has a tensor result or a tensor operand.
282 static bool hasTensorSemantics(Operation *op) {
283   if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
284     bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor);
285     bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor);
286     return hasTensorArg || hasTensorResult;
287   }
288 
289   bool hasTensorResult = any_of(op->getResultTypes(), isaTensor);
290   bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor);
291   return hasTensorResult || hasTensorOperand;
292 }
293 
294 LogicalResult
295 bufferization::finalizeBuffers(Operation *op,
296                                const BufferizationOptions &options) {
297   // Promote returned buffers to "out" parameters.
298   // TODO: Pass options to support custom dealloc ops.
299   if (options.promoteBufferResultsToOutParams && isa<ModuleOp>(op) &&
300       failed(promoteBufferResultsToOutParams(cast<ModuleOp>(op))))
301     return failure();
302 
303   return success();
304 }
305 
306 LogicalResult bufferization::bufferizeOp(Operation *op,
307                                          const AnalysisState &analysisState) {
308   // Catch incorrect API usage.
309   assert((analysisState.hasDialectState(
310               func::FuncDialect::getDialectNamespace()) ||
311           !analysisState.getOptions().bufferizeFunctionBoundaries) &&
312          "must use ModuleBufferize to bufferize function boundaries");
313 
314   BufferizationState bufferizationState(analysisState);
315   if (failed(bufferizeOp(op, bufferizationState)))
316     return failure();
317   if (failed(finalizeBuffers(op, analysisState.getOptions())))
318     return failure();
319   return success();
320 }
321 
322 namespace {
323 /// A rewriter that keeps track of extra information during bufferization.
324 class BufferizationRewriter : public IRRewriter {
325 public:
326   BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps,
327                         DenseSet<Operation *> &toMemrefOps,
328                         const BufferizationOptions &options,
329                         const OpFilter *opFilter)
330       : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps),
331         options(options), opFilter(opFilter) {}
332 
333 protected:
334   void notifyOperationRemoved(Operation *op) override {
335     IRRewriter::notifyOperationRemoved(op);
336     erasedOps.insert(op);
337     // Erase if present.
338     toMemrefOps.erase(op);
339   }
340 
341   void notifyOperationInserted(Operation *op) override {
342     IRRewriter::notifyOperationInserted(op);
343 
344     // Keep track of to_memref ops.
345     if (isa<ToMemrefOp>(op)) {
346       toMemrefOps.insert(op);
347       return;
348     }
349 
350     // Skip to_tensor ops.
351     if (isa<ToTensorOp>(op))
352       return;
353 
354     // Skip non-tensor ops.
355     if (!hasTensorSemantics(op))
356       return;
357 
358     // Skip ops that are not allowed.
359     if (!options.isOpAllowed(op) || (opFilter && !opFilter->isOpAllowed(op)))
360       return;
361 
362     // Adding new bufferizable ops is not allowed during bufferization. Such ops
363     // would not be analyzed and can lead to surprising behavior.
364     llvm_unreachable(
365         "creating new tensor ops is not allowed during bufferization");
366   }
367 
368 private:
369   /// A set of all erased ops.
370   DenseSet<Operation *> &erasedOps;
371 
372   /// A set of all to_memref ops.
373   DenseSet<Operation *> &toMemrefOps;
374 
375   /// The bufferization options.
376   /// Used for debug modes.
377   LLVM_ATTRIBUTE_UNUSED
378   const BufferizationOptions &options;
379 
380   const OpFilter *opFilter;
381 };
382 } // namespace
383 
384 LogicalResult bufferization::bufferizeOp(Operation *op,
385                                          BufferizationState &bufferizationState,
386                                          const OpFilter *opFilter) {
387   const auto &options = bufferizationState.getOptions();
388   assert(options.unknownTypeConversion !=
389              BufferizationOptions::LayoutMapOption::InferLayoutMap &&
390          "invalid layout map option");
391 
392   // Keep track of to_memref ops.
393   DenseSet<Operation *> toMemrefOps;
394   op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); });
395 
396   // Gather all bufferizable ops in top-to-bottom order.
397   //
398   // We should ideally know the exact memref type of all operands when
399   // bufferizing an op. (This is the case when bufferizing top-to-bottom.)
400   // Otherwise, we have to use a memref type with a fully dynamic layout map to
401   // avoid copies. We are currently missing patterns for layout maps to
402   // canonicalize away (or canonicalize to more precise layouts).
403   SmallVector<Operation *> worklist;
404   op->walk<WalkOrder::PreOrder>([&](Operation *op) {
405     if (hasTensorSemantics(op))
406       worklist.push_back(op);
407   });
408 
409   // Keep track of all erased ops.
410   DenseSet<Operation *> erasedOps;
411 
412   // Bufferize all ops.
413   BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps,
414                                  bufferizationState.getOptions(), opFilter);
415   for (unsigned i = 0; i < worklist.size(); ++i) {
416     Operation *op = worklist[i];
417     // Skip ops that were erased.
418     if (erasedOps.contains(op))
419       continue;
420     // Skip ops that are not bufferizable or not allowed.
421     auto bufferizableOp = options.dynCastBufferizableOp(op);
422     if (!bufferizableOp)
423       continue;
424     if (opFilter && !opFilter->isOpAllowed(op))
425       continue;
426     // Skip ops that no longer have tensor semantics.
427     if (!hasTensorSemantics(op))
428       continue;
429     // Bufferize the op.
430     rewriter.setInsertionPoint(op);
431     if (failed(bufferizableOp.bufferize(rewriter, bufferizationState)))
432       return op->emitError("failed to bufferize op");
433   }
434 
435   // Fold all to_memref(to_tensor(x)) pairs.
436   for (Operation *op : toMemrefOps) {
437     rewriter.setInsertionPoint(op);
438     (void)bufferization::foldToMemrefToTensorPair(rewriter,
439                                                   cast<ToMemrefOp>(op));
440   }
441 
442   /// Check the result of bufferization. Return an error if an op was not
443   /// bufferized, unless partial bufferization is allowed.
444   if (bufferizationState.getOptions().allowUnknownOps)
445     return success();
446 
447   for (Operation *op : worklist) {
448     // Skip ops that are entirely gone.
449     if (erasedOps.contains(op))
450       continue;
451     // Ops that no longer have tensor semantics (because they were updated
452     // in-place) are allowed.
453     if (!hasTensorSemantics(op))
454       continue;
455     // Continue ops that are not allowed.
456     if (!options.isOpAllowed(op))
457       continue;
458     if (opFilter && !opFilter->isOpAllowed(op))
459       continue;
460     // Ops without any uses and no side effects will fold away.
461     if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op))
462       continue;
463     return op->emitError("op was not bufferized");
464   }
465 
466   return success();
467 }
468 
469 namespace {
470 /// This a "no analysis, always copy" AnalysisState. In the absence of an
471 /// analysis, a buffer must be copied each time it is written to. Therefore, all
472 /// OpOperands that bufferize to a memory write must bufferize out-of-place.
473 class AlwaysCopyAnalysisState : public AnalysisState {
474 public:
475   AlwaysCopyAnalysisState(const BufferizationOptions &options)
476       : AnalysisState(options) {
477     // Note: Allocations must be deallocated with a subsequent run of the buffer
478     // deallocation pass.
479     assert(!options.createDeallocs &&
480            "cannot create deallocs with AlwaysCopyBufferizationState");
481   }
482 
483   AlwaysCopyAnalysisState(const AlwaysCopyAnalysisState &) = delete;
484 
485   virtual ~AlwaysCopyAnalysisState() = default;
486 
487   /// Return `true` if the given OpResult has been decided to bufferize inplace.
488   bool isInPlace(OpOperand &opOperand) const override {
489     // OpOperands that bufferize to a memory write are out-of-place, i.e., an
490     // alloc and copy is inserted.
491     return !bufferizesToMemoryWrite(opOperand);
492   }
493 
494   /// Return true if `v1` and `v2` bufferize to equivalent buffers.
495   bool areEquivalentBufferizedValues(Value v1, Value v2) const override {
496     // There is no analysis, so we do not know if the values are equivalent. The
497     // conservative answer is "false".
498     return false;
499   }
500 
501   /// Return true if `v1` and `v2` may bufferize to aliasing buffers.
502   bool areAliasingBufferizedValues(Value v1, Value v2) const override {
503     // There is no analysis, so we do not know if the values are equivalent. The
504     // conservative answer is "true".
505     return true;
506   }
507 
508   /// Return `true` if the given tensor has undefined contents.
509   bool hasUndefinedContents(OpOperand *opOperand) const override {
510     // There is no analysis, so the conservative answer is "false".
511     return false;
512   }
513 
514   /// Return true if the given tensor (or an aliasing tensor) is yielded from
515   /// the containing block. Also include all aliasing tensors in the same block.
516   bool isTensorYielded(Value tensor) const override {
517     // There is no analysis, so conservatively answer "true".
518     return true;
519   }
520 };
521 } // namespace
522 
523 LogicalResult bufferization::bufferizeOp(Operation *op,
524                                          const BufferizationOptions &options) {
525   AlwaysCopyAnalysisState state(options);
526   return bufferizeOp(op, state);
527 }
528 
529 BufferizationOptions bufferization::getPartialBufferizationOptions() {
530   BufferizationOptions options;
531   options.allowUnknownOps = true;
532   options.createDeallocs = false;
533   options.unknownTypeConversion =
534       BufferizationOptions::LayoutMapOption::IdentityLayoutMap;
535   return options;
536 }
537