MLIR 24.0.0git
Bufferize.cpp
Go to the documentation of this file.
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
10
18#include "mlir/IR/Diagnostics.h"
19#include "mlir/IR/Operation.h"
23#include "llvm/Support/DebugLog.h"
24#include <optional>
25
26namespace mlir {
27namespace bufferization {
28#define GEN_PASS_DEF_ONESHOTBUFFERIZEPASS
29#include "mlir/Dialect/Bufferization/Transforms/Passes.h.inc"
30} // namespace bufferization
31} // namespace mlir
32
33#define DEBUG_TYPE "bufferize"
34
35using namespace mlir;
36using namespace mlir::bufferization;
37
38namespace {
39
41parseHeuristicOption(const std::string &s) {
42 if (s == "bottom-up")
44 if (s == "top-down")
46 if (s == "bottom-up-from-terminators")
47 return OneShotBufferizationOptions::AnalysisHeuristic::
48 BottomUpFromTerminators;
49 if (s == "fuzzer")
51 llvm_unreachable("invalid analysisheuristic option");
52}
53
54struct OneShotBufferizePass
56 OneShotBufferizePass> {
57 using Base::Base;
58
59 void runOnOperation() override {
61 opt.allowReturnAllocsFromLoops = allowReturnAllocsFromLoops;
62 opt.allowUnknownOps = allowUnknownOps;
63 opt.analysisFuzzerSeed = analysisFuzzerSeed;
64 opt.analysisHeuristic = parseHeuristicOption(analysisHeuristic);
65 opt.copyBeforeWrite = copyBeforeWrite;
66 opt.dumpAliasSets = dumpAliasSets;
67 opt.setFunctionBoundaryTypeConversion(functionBoundaryTypeConversion);
68
69 if (mustInferMemorySpace && useEncodingForMemorySpace) {
70 emitError(getOperation()->getLoc())
71 << "only one of 'must-infer-memory-space' and "
72 "'use-encoding-for-memory-space' are allowed in "
73 << getArgument();
74 return signalPassFailure();
75 }
76
77 if (mustInferMemorySpace) {
78 opt.defaultMemorySpaceFn =
79 [](TensorLikeType t) -> std::optional<Attribute> {
80 return std::nullopt;
81 };
82 }
83
84 if (useEncodingForMemorySpace) {
85 opt.defaultMemorySpaceFn =
86 [](TensorLikeType t) -> std::optional<Attribute> {
87 if (auto rtt = dyn_cast<RankedTensorType>(t))
88 return rtt.getEncoding();
89 return std::nullopt;
90 };
91 }
92
93 opt.printConflicts = printConflicts;
94 opt.bufferAlignment = bufferAlignment;
95 opt.testAnalysisOnly = testAnalysisOnly;
96 opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries;
97 if (!mayHaveParallelRegions)
98 opt.mayHaveParallelRegions = false;
99 opt.noAnalysisFuncFilter = noAnalysisFuncFilter;
100
101 // Configure type converter.
102 LayoutMapOption unknownTypeConversionOption = unknownTypeConversion;
103 if (unknownTypeConversionOption == LayoutMapOption::InferLayoutMap) {
104 emitError(UnknownLoc::get(&getContext()),
105 "Invalid option: 'infer-layout-map' is not a valid value for "
106 "'unknown-type-conversion'");
107 return signalPassFailure();
108 }
109 opt.unknownTypeConverterFn = [=](TensorLikeType type, Attribute memorySpace,
111 const auto tensorType = cast<TensorType>(type);
112 if (unknownTypeConversionOption == LayoutMapOption::IdentityLayoutMap)
113 return cast<bufferization::BufferLikeType>(
114 bufferization::getMemRefTypeWithStaticIdentityLayout(tensorType,
115 memorySpace));
116 assert(unknownTypeConversionOption ==
117 LayoutMapOption::FullyDynamicLayoutMap &&
118 "invalid layout map option");
119 return cast<bufferization::BufferLikeType>(
120 bufferization::getMemRefTypeWithFullyDynamicLayout(tensorType,
121 memorySpace));
122 };
123
124 // Configure op filter.
125 OpFilter::Entry::FilterFn filterFn = [&](Operation *op) {
126 // Filter may be specified via options.
127 if (this->dialectFilter.hasValue() && !(*this->dialectFilter).empty())
128 return llvm::is_contained(this->dialectFilter,
129 op->getDialect()->getNamespace());
130 // No filter specified: All other ops are allowed.
131 return true;
132 };
133 opt.opFilter.allowOperation(filterFn);
134
135 if (opt.copyBeforeWrite && opt.testAnalysisOnly) {
136 // These two flags do not make sense together: "copy-before-write"
137 // indicates that copies should be inserted before every memory write,
138 // but "test-analysis-only" indicates that only the analysis should be
139 // tested. (I.e., no IR is bufferized.)
140 emitError(UnknownLoc::get(&getContext()),
141 "Invalid option: 'copy-before-write' cannot be used with "
142 "'test-analysis-only'");
143 return signalPassFailure();
144 }
145
146 if (opt.printConflicts && !opt.testAnalysisOnly) {
147 emitError(
148 UnknownLoc::get(&getContext()),
149 "Invalid option: 'print-conflicts' requires 'test-analysis-only'");
150 return signalPassFailure();
151 }
152
153 if (opt.dumpAliasSets && !opt.testAnalysisOnly) {
154 emitError(
155 UnknownLoc::get(&getContext()),
156 "Invalid option: 'dump-alias-sets' requires 'test-analysis-only'");
157 return signalPassFailure();
158 }
159
160 BufferizationState state;
161 BufferizationStatistics statistics;
162 ModuleOp moduleOp = getOperation();
163 if (opt.bufferizeFunctionBoundaries) {
164 if (failed(
165 runOneShotModuleBufferize(moduleOp, opt, state, &statistics))) {
166 signalPassFailure();
167 return;
168 }
169 } else {
170 if (!opt.noAnalysisFuncFilter.empty()) {
171 emitError(UnknownLoc::get(&getContext()),
172 "Invalid option: 'no-analysis-func-filter' requires "
173 "'bufferize-function-boundaries'");
174 return signalPassFailure();
175 }
176 if (failed(runOneShotBufferize(moduleOp, opt, state, &statistics))) {
177 signalPassFailure();
178 return;
179 }
180 }
181
182 // Set pass statistics.
183 this->numBufferAlloc = statistics.numBufferAlloc;
184 this->numTensorInPlace = statistics.numTensorInPlace;
185 this->numTensorOutOfPlace = statistics.numTensorOutOfPlace;
186 }
187};
188} // namespace
189
190//===----------------------------------------------------------------------===//
191// BufferizableOpInterface-based Bufferization
192//===----------------------------------------------------------------------===//
193
194namespace {
195/// A rewriter that keeps track of extra information during bufferization.
196class BufferizationRewriter : public IRRewriter, public RewriterBase::Listener {
197public:
198 BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps,
199 DenseSet<Operation *> &toBufferOps,
200 SmallVector<Operation *> &worklist,
201 const BufferizationOptions &options,
202 BufferizationStatistics *statistics)
203 : IRRewriter(ctx), erasedOps(erasedOps), toBufferOps(toBufferOps),
204 worklist(worklist), analysisState(options), statistics(statistics) {
205 setListener(this);
206 }
207
208protected:
209 void notifyOperationErased(Operation *op) override {
210 erasedOps.insert(op);
211 // Erase if present.
212 toBufferOps.erase(op);
213 }
214
215 void notifyOperationInserted(Operation *op, InsertPoint previous) override {
216 // We only care about newly created ops.
217 if (previous.isSet())
218 return;
219
220 erasedOps.erase(op);
221
222 // Gather statistics about allocs.
223 if (statistics) {
224 if (auto sideEffectingOp = dyn_cast<MemoryEffectOpInterface>(op))
225 statistics->numBufferAlloc += static_cast<int64_t>(
226 sideEffectingOp.hasEffect<MemoryEffects::Allocate>());
227 }
228
229 // Keep track of to_buffer ops.
230 if (isa<ToBufferOp>(op)) {
231 toBufferOps.insert(op);
232 return;
233 }
234
235 // Skip to_tensor ops.
236 if (isa<ToTensorOp>(op))
237 return;
238
239 // Skip non-tensor ops.
240 if (!hasTensorSemantics(op))
241 return;
242
243 // Skip ops that are not allowed to be bufferized.
244 auto const &options = analysisState.getOptions();
245 if (!options.isOpAllowed(op))
246 return;
247
248 // Add op to worklist.
249 worklist.push_back(op);
250 }
251
252private:
253 /// A set of all erased ops.
254 DenseSet<Operation *> &erasedOps;
255
256 /// A set of all to_buffer ops.
257 DenseSet<Operation *> &toBufferOps;
258
259 /// The worklist of ops to be bufferized.
260 SmallVector<Operation *> &worklist;
261
262 /// The analysis state. Used for debug assertions and access to the
263 /// bufferization options.
264 const AnalysisState analysisState;
265
266 /// Bufferization statistics for debugging.
267 BufferizationStatistics *statistics;
268};
269} // namespace
270
273 BufferizationState &bufferizationState,
274 BufferizationStatistics *statistics) {
275 if (options.copyBeforeWrite) {
276 AnalysisState analysisState(options);
277 if (failed(insertTensorCopies(op, analysisState, bufferizationState)))
278 return failure();
279 }
280
281 // Keep track of to_buffer ops.
282 DenseSet<Operation *> toBufferOps;
283 op->walk([&](ToBufferOp toBufferOp) { toBufferOps.insert(toBufferOp); });
284
285 // Gather all bufferizable ops in top-to-bottom order.
286 //
287 // We should ideally know the exact memref type of all operands when
288 // bufferizing an op. (This is the case when bufferizing top-to-bottom.)
289 // Otherwise, we have to use a memref type with a fully dynamic layout map to
290 // avoid copies. We are currently missing patterns for layout maps to
291 // canonicalize away (or canonicalize to more precise layouts).
293 op->walk<WalkOrder::PostOrder>([&](Operation *op) {
294 if (options.isOpAllowed(op) && hasTensorSemantics(op))
295 worklist.push_back(op);
296 });
297
298 // Keep track of all erased ops.
299 DenseSet<Operation *> erasedOps;
300
301 // Bufferize all ops.
302 BufferizationRewriter rewriter(op->getContext(), erasedOps, toBufferOps,
303 worklist, options, statistics);
304 for (unsigned i = 0; i < worklist.size(); ++i) {
305 Operation *nextOp = worklist[i];
306 // Skip ops that were erased.
307 if (erasedOps.contains(nextOp))
308 continue;
309 // Skip ops that are not bufferizable or not allowed.
310 auto bufferizableOp = options.dynCastBufferizableOp(nextOp);
311 if (!bufferizableOp)
312 continue;
313 // Skip ops that no longer have tensor semantics.
314 if (!hasTensorSemantics(nextOp))
315 continue;
316 // Check for unsupported unstructured control flow.
317 if (!bufferizableOp.supportsUnstructuredControlFlow())
318 for (Region &r : nextOp->getRegions())
319 if (r.getBlocks().size() > 1)
320 return nextOp->emitOpError(
321 "op or BufferizableOpInterface implementation does not support "
322 "unstructured control flow, but at least one region has multiple "
323 "blocks");
324
325 // Bufferize the op.
326 LDBG(3) << "//===-------------------------------------------===//\n"
327 << "IR after bufferizing: " << nextOp->getName();
328 rewriter.setInsertionPoint(nextOp);
329 if (failed(
330 bufferizableOp.bufferize(rewriter, options, bufferizationState))) {
331 LDBG(2) << "failed to bufferize\n"
332 << "//===-------------------------------------------===//";
333 return nextOp->emitError("failed to bufferize op");
334 }
335 LDBG(3) << *op << "\n//===-------------------------------------------===//";
336 }
337
338 // Return early if the top-level op is entirely gone.
339 if (erasedOps.contains(op))
340 return success();
341
342 // Fold all to_buffer(to_tensor(x)) pairs. Snapshot the set first:
343 // `foldToBufferToTensorPair` can erase ops, and the rewriter listener
344 // mutates `toBufferOps` from inside that call, which would invalidate
345 // any DenseSet iterator held across it.
346 SmallVector<Operation *> toBufferOpsSnapshot = llvm::to_vector(toBufferOps);
347 for (Operation *op : toBufferOpsSnapshot) {
348 if (erasedOps.contains(op))
349 continue;
350 rewriter.setInsertionPoint(op);
352 rewriter, cast<ToBufferOp>(op), options);
353 }
354
355 // Remove all dead to_tensor ops.
356 op->walk<WalkOrder::PostOrder>([&](ToTensorOp toTensorOp) {
357 if (toTensorOp->getUses().empty()) {
358 rewriter.eraseOp(toTensorOp);
359 return WalkResult::skip();
360 }
361 return WalkResult::advance();
362 });
363
364 /// Check the result of bufferization. Return an error if an op was not
365 /// bufferized, unless partial bufferization is allowed.
366 if (options.allowUnknownOps)
367 return success();
368
369 for (Operation *op : worklist) {
370 // Skip ops that are entirely gone.
371 if (erasedOps.contains(op))
372 continue;
373 // Ops that no longer have tensor semantics (because they were updated
374 // in-place) are allowed.
375 if (!hasTensorSemantics(op))
376 continue;
377 // Continue ops that are not allowed.
378 if (!options.isOpAllowed(op))
379 continue;
380 // Ops without any uses and no side effects will fold away.
381 if (op->getUses().empty() && isMemoryEffectFree(op))
382 continue;
383 // ToTensorOps/ToBufferOps are allowed in the output.
384 if (isa<ToTensorOp, ToBufferOp>(op))
385 continue;
386 return op->emitError("op was not bufferized");
387 }
388
389 return success();
390}
391
392LogicalResult
395 BufferizationState &state) {
396 OpBuilder::InsertionGuard g(rewriter);
397 auto bufferizableOp = options.dynCastBufferizableOp(block->getParentOp());
398 if (!bufferizableOp)
399 return failure();
400
401 // Compute the new signature.
402 SmallVector<Type> newTypes;
403 for (BlockArgument &bbArg : block->getArguments()) {
404 auto tensorType = dyn_cast<TensorLikeType>(bbArg.getType());
405 if (!tensorType) {
406 newTypes.push_back(bbArg.getType());
407 continue;
408 }
409
410 FailureOr<BufferLikeType> bufferType =
411 bufferization::getBufferType(bbArg, options, state);
412 if (failed(bufferType))
413 return failure();
414 newTypes.push_back(*bufferType);
415 }
416
417 // Change the type of all block arguments.
418 for (auto [bbArg, type] : llvm::zip(block->getArguments(), newTypes)) {
419 if (bbArg.getType() == type)
420 continue;
421
422 // Collect all uses of the bbArg.
423 SmallVector<OpOperand *> bbArgUses;
424 for (OpOperand &use : bbArg.getUses())
425 bbArgUses.push_back(&use);
426
427 Type tensorType = bbArg.getType();
428 // Change the bbArg type to memref.
429 bbArg.setType(type);
430
431 // Replace all uses of the original tensor bbArg.
432 rewriter.setInsertionPointToStart(block);
433 if (!bbArgUses.empty()) {
434 Value toTensorOp = bufferization::ToTensorOp::create(
435 rewriter, bbArg.getLoc(), tensorType, bbArg);
436 for (OpOperand *use : bbArgUses)
437 use->set(toTensorOp);
438 }
439 }
440
441 // Bufferize callers of the block. Iterate BlockOperands so each successor
442 // edge is handled once, including when one branch op targets this block more
443 // than once.
444 for (BlockOperand &blockOperand : block->getUses()) {
445 Operation *op = blockOperand.getOwner();
446 auto branchOp = dyn_cast<BranchOpInterface>(op);
447 if (!branchOp)
448 return op->emitOpError("cannot bufferize ops with block references that "
449 "do not implement BranchOpInterface");
450
451 SuccessorOperands operands =
452 branchOp.getSuccessorOperands(blockOperand.getOperandNumber());
453 SmallVector<Value> newOperands;
454 for (auto [operand, type] :
455 llvm::zip(operands.getForwardedOperands(), newTypes)) {
456 if (operand.getType() == type) {
457 // Not a tensor type. Nothing to do for this operand.
458 newOperands.push_back(operand);
459 continue;
460 }
461 FailureOr<BufferLikeType> operandBufferType =
462 bufferization::getBufferType(operand, options, state);
463 if (failed(operandBufferType))
464 return failure();
465 rewriter.setInsertionPointAfterValue(operand);
466 Value bufferizedOperand = bufferization::ToBufferOp::create(
467 rewriter, operand.getLoc(), *operandBufferType, operand);
468 // A cast is needed if the operand and the block argument have different
469 // bufferized types.
470 FailureOr<Value> casted = castBuffer(rewriter, operand.getLoc(),
471 bufferizedOperand, type, options);
472 if (failed(casted))
473 return failure();
474 newOperands.push_back(*casted);
475 }
476 operands.getMutableForwardedOperands().assign(newOperands);
477 }
478
479 return success();
480}
return success()
return MutableOperandRange * this
b getContext())
static llvm::ManagedStatic< PassManagerOptions > options
Base class for generic analysis states.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
A block operand represents an operand that holds a reference to a Block, e.g.
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgListType getArguments()
Definition Block.h:112
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
void assign(ValueRange values)
Assign this range to the given values.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition Builders.h:424
This class represents an operand of an operation.
Definition Value.h:256
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
use_range getUses()
Returns a range of all uses, which is useful for iterating over all uses.
Definition Operation.h:900
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class models how operands are forwarded to block arguments in control flow.
MutableOperandRange getMutableForwardedOperands() const
Get the range of operands that are simply forwarded to the successor.
OperandRange getForwardedOperands() const
Get the range of operands that are simply forwarded to the successor.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
LogicalResult bufferizeOp(Operation *op, const BufferizationOptions &options, BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Bufferize op and its nested ops that implement BufferizableOpInterface.
LogicalResult bufferizeBlockSignature(Block *block, RewriterBase &rewriter, const BufferizationOptions &options, BufferizationState &state)
Bufferize the signature of block and its callers (i.e., ops that have the given block as a successor)...
LogicalResult insertTensorCopies(Operation *op, const OneShotBufferizationOptions &options, const BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Resolve RaW and other conflicts by inserting bufferization.alloc_tensor ops.
LogicalResult runOneShotBufferize(Operation *op, const OneShotBufferizationOptions &options, BufferizationState &state, BufferizationStatistics *statistics=nullptr)
Run One-Shot Bufferize on the given op: Analysis + Bufferization.
LogicalResult foldToBufferToTensorPair(RewriterBase &rewriter, ToBufferOp toBuffer, const BufferizationOptions &options)
Try to fold to_buffer(to_tensor(x)).
llvm::LogicalResult runOneShotModuleBufferize(Operation *moduleOp, const bufferization::OneShotBufferizationOptions &options, BufferizationState &state, BufferizationStatistics *statistics=nullptr)
Run One-Shot Module Bufferization on the given SymbolTable.
Include the generated interface declarations.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
Bufferization statistics for debugging.
Definition Bufferize.h:35
Options for analysis-enabled bufferization.
unsigned analysisFuzzerSeed
Seed for the analysis fuzzer.
bool dumpAliasSets
Specifies whether the tensor IR should be annotated with alias sets.
bool allowReturnAllocsFromLoops
Specifies whether returning newly allocated memrefs from loops should be allowed.
AnalysisHeuristic analysisHeuristic
The heuristic controls the order in which ops are traversed during the analysis.
llvm::ArrayRef< std::string > noAnalysisFuncFilter
Specify the functions that should not be analyzed.