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 struct OneShotBufferizePass
155     : public OneShotBufferizeBase<OneShotBufferizePass> {
156   OneShotBufferizePass() : OneShotBufferizeBase<OneShotBufferizePass>() {}
157 
158   explicit OneShotBufferizePass(const OneShotBufferizationOptions &options)
159       : options(options) {}
160 
161   void getDependentDialects(DialectRegistry &registry) const override {
162     registry
163         .insert<bufferization::BufferizationDialect, memref::MemRefDialect>();
164     registerAllocationOpInterfaceExternalModels(registry);
165   }
166 
167   void runOnOperation() override {
168     OneShotBufferizationOptions opt;
169     if (!options) {
170       // Make new bufferization options if none were provided when creating the
171       // pass.
172       opt.allowReturnAllocs = allowReturnAllocs;
173       opt.allowUnknownOps = allowUnknownOps;
174       opt.analysisFuzzerSeed = analysisFuzzerSeed;
175       opt.createDeallocs = createDeallocs;
176       opt.fullyDynamicLayoutMaps = fullyDynamicLayoutMaps;
177       opt.printConflicts = printConflicts;
178       opt.testAnalysisOnly = testAnalysisOnly;
179       opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries;
180 
181       BufferizationOptions::OpFilterEntry::FilterFn filterFn =
182           [&](Operation *op) {
183             // Filter may be specified via options.
184             if (this->dialectFilter.hasValue())
185               return llvm::find(this->dialectFilter,
186                                 op->getDialect()->getNamespace()) !=
187                      this->dialectFilter.end();
188             // No filter specified: All other ops are allowed.
189             return true;
190           };
191       opt.allowOperationInFilter(filterFn);
192     } else {
193       opt = *options;
194     }
195 
196     ModuleOp moduleOp = getOperation();
197     if (opt.bufferizeFunctionBoundaries) {
198       if (failed(runOneShotModuleBufferize(moduleOp, opt))) {
199         signalPassFailure();
200         return;
201       }
202     } else {
203       if (failed(runOneShotBufferize(moduleOp, opt))) {
204         signalPassFailure();
205         return;
206       }
207     }
208 
209     if (opt.testAnalysisOnly)
210       return;
211 
212     OpPassManager cleanupPipeline("builtin.module");
213     cleanupPipeline.addPass(createCanonicalizerPass());
214     cleanupPipeline.addPass(createCSEPass());
215     cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
216     (void)runPipeline(cleanupPipeline, moduleOp);
217   }
218 
219 private:
220   llvm::Optional<OneShotBufferizationOptions> options;
221 };
222 } // namespace
223 
224 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() {
225   return std::make_unique<OneShotBufferizePass>();
226 }
227 
228 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass(
229     const OneShotBufferizationOptions &options) {
230   return std::make_unique<OneShotBufferizePass>(options);
231 }
232 
233 std::unique_ptr<OperationPass<func::FuncOp>>
234 mlir::bufferization::createFinalizingBufferizePass() {
235   return std::make_unique<FinalizingBufferizePass>();
236 }
237 
238 //===----------------------------------------------------------------------===//
239 // BufferizableOpInterface-based Bufferization
240 //===----------------------------------------------------------------------===//
241 
242 static bool isaTensor(Type t) { return t.isa<TensorType>(); }
243 
244 /// Return true if the given op has a tensor result or a tensor operand.
245 static bool hasTensorSemantics(Operation *op) {
246   if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
247     bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor);
248     bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor);
249     return hasTensorArg || hasTensorResult;
250   }
251 
252   bool hasTensorResult = any_of(op->getResultTypes(), isaTensor);
253   bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor);
254   return hasTensorResult || hasTensorOperand;
255 }
256 
257 LogicalResult
258 bufferization::finalizeBuffers(Operation *op,
259                                const BufferizationOptions &options) {
260   // Hoist buffers.
261   if (failed(hoistBufferAllocations(op, options)))
262     return failure();
263 
264   // Deallocate buffers that escape block boundaries ("leaking buffers") with
265   // the buffer deallocation pass.
266   bool hasLeakingAlloc = false;
267   if (failed(createAllocDeallocOps(op, options, /*onlyLeakingAllocs=*/true,
268                                    &hasLeakingAlloc)))
269     return failure();
270   if (options.createDeallocs && hasLeakingAlloc &&
271       failed(deallocateBuffers(op)))
272     return failure();
273 
274   // Deallocate all remaining buffers at the end of the block.
275   if (failed(createAllocDeallocOps(op, options)))
276     return failure();
277 
278   return success();
279 }
280 
281 LogicalResult bufferization::bufferizeOp(Operation *op,
282                                          const AnalysisState &analysisState) {
283   // Catch incorrect API usage.
284   assert((analysisState.hasDialectState(
285               func::FuncDialect::getDialectNamespace()) ||
286           !analysisState.getOptions().bufferizeFunctionBoundaries) &&
287          "must use ModuleBufferize to bufferize function boundaries");
288 
289   BufferizationState bufferizationState(analysisState);
290   if (failed(bufferizeOp(op, bufferizationState)))
291     return failure();
292   if (failed(finalizeBuffers(op, analysisState.getOptions())))
293     return failure();
294   return success();
295 }
296 
297 namespace {
298 /// A rewriter that keeps track of extra information during bufferization.
299 class BufferizationRewriter : public IRRewriter {
300 public:
301   BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps,
302                         DenseSet<Operation *> &toMemrefOps,
303                         SmallVector<Operation *> &worklist)
304       : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps),
305         worklist(worklist) {}
306 
307 protected:
308   void notifyOperationRemoved(Operation *op) override {
309     IRRewriter::notifyOperationRemoved(op);
310     erasedOps.insert(op);
311   }
312 
313   void notifyOperationInserted(Operation *op) override {
314     IRRewriter::notifyOperationInserted(op);
315 
316     // Keep track of to_memref ops.
317     if (isa<ToMemrefOp>(op)) {
318       toMemrefOps.insert(op);
319       return;
320     }
321 
322     // Skip to_tensor ops.
323     if (isa<ToTensorOp>(op))
324       return;
325 
326     // A new bufferizable op was inserted. Add it to the worklist.
327     if (hasTensorSemantics(op))
328       worklist.push_back(op);
329   }
330 
331 private:
332   /// A set of all erased ops.
333   DenseSet<Operation *> &erasedOps;
334 
335   /// A set of all to_memref ops.
336   DenseSet<Operation *> &toMemrefOps;
337 
338   /// The list of bufferizable ops.
339   SmallVector<Operation *> &worklist;
340 };
341 } // namespace
342 
343 LogicalResult
344 bufferization::bufferizeOp(Operation *op,
345                            BufferizationState &bufferizationState) {
346   const auto &options = bufferizationState.getOptions();
347 
348   // Keep track of to_memref ops.
349   DenseSet<Operation *> toMemrefOps;
350   op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); });
351 
352   // Gather all bufferizable ops in top-to-bottom order.
353   //
354   // We should ideally know the exact memref type of all operands when
355   // bufferizing an op. (This is the case when bufferizing top-to-bottom.)
356   // Otherwise, we have to use a memref type with a fully dynamic layout map,
357   // which has to canonicalize away. This is less efficient.
358   //
359   // If "fullyDynamicLayoutMaps = false", we would have to insert buffer copies
360   // to fold ("finalize") to_memref(to_tensor(x)) ops with non-cast-compatible
361   // layout maps when doing a traversal other than top-to-bottom. These would
362   // not easily fold away.
363   SmallVector<Operation *> worklist;
364   op->walk<WalkOrder::PreOrder>([&](Operation *op) {
365     if (hasTensorSemantics(op))
366       worklist.push_back(op);
367   });
368 
369   // Keep track of all erased ops.
370   DenseSet<Operation *> erasedOps;
371 
372   // Bufferize all ops.
373   BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps,
374                                  worklist);
375   for (unsigned i = 0; i < worklist.size(); ++i) {
376     Operation *op = worklist[i];
377     // Skip ops that were erased.
378     if (erasedOps.contains(op))
379       continue;
380     // Skip ops that are not bufferizable.
381     auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op);
382     if (!bufferizableOp)
383       continue;
384     // Continue ops that are not allowed.
385     if (!options.isOpAllowed(op))
386       continue;
387     // Bufferize the op.
388     rewriter.setInsertionPoint(op);
389     (void)bufferizableOp.bufferize(rewriter, bufferizationState);
390   }
391 
392   // Fold all to_memref(to_tensor(x)) pairs.
393   for (Operation *op : toMemrefOps) {
394     if (erasedOps.contains(op))
395       continue;
396     rewriter.setInsertionPoint(op);
397     (void)bufferization::foldToMemrefToTensorPair(rewriter,
398                                                   cast<ToMemrefOp>(op));
399   }
400 
401   /// Check the result of bufferization. Return an error if an op was not
402   /// bufferized, unless partial bufferization is allowed.
403   if (bufferizationState.getOptions().allowUnknownOps)
404     return success();
405 
406   for (Operation *op : worklist) {
407     // Skip ops that are entirely gone.
408     if (erasedOps.contains(op))
409       continue;
410     // Ops that no longer have tensor semantics (because they were updated
411     // in-place) are allowed.
412     if (!hasTensorSemantics(op))
413       continue;
414     // Continue ops that are not allowed.
415     if (!options.isOpAllowed(op))
416       continue;
417     // Ops without any uses and no side effects will fold away.
418     if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op))
419       continue;
420     return op->emitError("op was not bufferized");
421   }
422 
423   return success();
424 }
425 
426 namespace {
427 /// This a "no analysis, always copy" AnalysisState. In the absence of an
428 /// analysis, a buffer must be copied each time it is written to. Therefore, all
429 /// OpOperands that bufferize to a memory write must bufferize out-of-place.
430 class AlwaysCopyAnalysisState : public AnalysisState {
431 public:
432   AlwaysCopyAnalysisState(const BufferizationOptions &options)
433       : AnalysisState(options) {}
434 
435   AlwaysCopyAnalysisState(const AlwaysCopyAnalysisState &) = delete;
436 
437   virtual ~AlwaysCopyAnalysisState() = default;
438 
439   /// Return `true` if the given OpResult has been decided to bufferize inplace.
440   bool isInPlace(OpOperand &opOperand) const override {
441     // OpOperands that bufferize to a memory write are out-of-place, i.e., an
442     // alloc and copy is inserted.
443     return !bufferizesToMemoryWrite(opOperand);
444   }
445 
446   /// Return true if `v1` and `v2` bufferize to equivalent buffers.
447   bool areEquivalentBufferizedValues(Value v1, Value v2) const override {
448     // There is no analysis, so we do not know if the values are equivalent. The
449     // conservative answer is "false".
450     return false;
451   }
452 };
453 } // namespace
454 
455 LogicalResult bufferization::bufferizeOp(Operation *op,
456                                          const BufferizationOptions &options) {
457   AlwaysCopyAnalysisState state(options);
458   return bufferizeOp(op, state);
459 }
460 
461 BufferizationOptions bufferization::getPartialBufferizationOptions() {
462   BufferizationOptions options;
463   options.allowUnknownOps = true;
464   options.createDeallocs = false;
465   options.fullyDynamicLayoutMaps = false;
466   return options;
467 }
468