MLIR 24.0.0git
BufferizationToMemRef.cpp
Go to the documentation of this file.
1//===- BufferizationToMemRef.cpp - Bufferization to MemRef conversion -----===//
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// This file implements patterns to convert Bufferization dialect to MemRef
10// dialect.
11//
12//===----------------------------------------------------------------------===//
13
15
24
25namespace mlir {
26#define GEN_PASS_DEF_CONVERTBUFFERIZATIONTOMEMREFPASS
27#include "mlir/Conversion/Passes.h.inc"
28} // namespace mlir
29
30using namespace mlir;
31
32namespace {
33/// The CloneOpConversion transforms all bufferization clone operations into
34/// memref alloc and memref copy operations. In the dynamic-shape case, it also
35/// emits additional dim and constant operations to determine the shape. This
36/// conversion does not resolve memory leaks if it is used alone.
37struct CloneOpConversion : public OpConversionPattern<bufferization::CloneOp> {
38 using OpConversionPattern<bufferization::CloneOp>::OpConversionPattern;
39
40 LogicalResult
41 matchAndRewrite(bufferization::CloneOp op, OpAdaptor adaptor,
42 ConversionPatternRewriter &rewriter) const override {
43 Location loc = op->getLoc();
44
45 Type type = op.getType();
46 if (!isa<BaseMemRefType>(type) ||
47 !isa<BaseMemRefType>(op.getInput().getType()))
48 return rewriter.notifyMatchFailure(op, "expected memrefs");
49 Value alloc;
50
51 if (auto unrankedType = dyn_cast<UnrankedMemRefType>(type)) {
52 // Constants
53 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
54 Value one = arith::ConstantIndexOp::create(rewriter, loc, 1);
55
56 // Dynamically evaluate the size and shape of the unranked memref
57 Value rank = memref::RankOp::create(rewriter, loc, op.getInput());
58 MemRefType allocType =
59 MemRefType::get({ShapedType::kDynamic}, rewriter.getIndexType());
60 Value shape = memref::AllocaOp::create(rewriter, loc, allocType, rank);
61
62 // Create a loop to query dimension sizes, store them as a shape, and
63 // compute the total size of the memref
64 auto loopBody = [&](OpBuilder &builder, Location loc, Value i,
65 ValueRange args) {
66 auto acc = args.front();
67 auto dim = memref::DimOp::create(rewriter, loc, op.getInput(), i);
68
69 memref::StoreOp::create(rewriter, loc, dim, shape, i);
70 acc = arith::MulIOp::create(rewriter, loc, acc, dim);
71
72 scf::YieldOp::create(rewriter, loc, acc);
73 };
74 auto size = scf::ForOp::create(rewriter, loc, zero, rank, one,
75 ValueRange(one), loopBody)
76 .getResult(0);
77
78 MemRefType memrefType = MemRefType::get({ShapedType::kDynamic},
79 unrankedType.getElementType());
80
81 // Allocate new memref with 1D dynamic shape, then reshape into the
82 // shape of the original unranked memref
83 alloc = memref::AllocOp::create(rewriter, loc, memrefType, size);
84 alloc =
85 memref::ReshapeOp::create(rewriter, loc, unrankedType, alloc, shape);
86 } else {
87 MemRefType memrefType = cast<MemRefType>(type);
88 MemRefLayoutAttrInterface layout;
89 auto allocType =
90 MemRefType::get(memrefType.getShape(), memrefType.getElementType(),
91 layout, memrefType.getMemorySpace());
92 // Since this implementation always allocates, certain result types of
93 // the clone op cannot be lowered.
94 if (!memref::CastOp::areCastCompatible({allocType}, {memrefType}))
95 return failure();
96
97 // Transform a clone operation into alloc + copy operation and pay
98 // attention to the shape dimensions.
99 SmallVector<Value, 4> dynamicOperands;
100 for (int i = 0; i < memrefType.getRank(); ++i) {
101 if (!memrefType.isDynamicDim(i))
102 continue;
103 Value dim = rewriter.createOrFold<memref::DimOp>(loc, op.getInput(), i);
104 dynamicOperands.push_back(dim);
105 }
106
107 // Allocate a memref with identity layout.
108 alloc =
109 memref::AllocOp::create(rewriter, loc, allocType, dynamicOperands);
110 // Cast the allocation to the specified type if needed.
111 if (memrefType != allocType)
112 alloc =
113 memref::CastOp::create(rewriter, op->getLoc(), memrefType, alloc);
114 }
115
116 memref::CopyOp::create(rewriter, loc, op.getInput(), alloc);
117 rewriter.replaceOp(op, alloc);
118 return success();
119 }
120};
121
122} // namespace
123
124namespace {
125struct BufferizationToMemRefPass
127 BufferizationToMemRefPass> {
128 BufferizationToMemRefPass() = default;
129
130 void runOnOperation() override {
131 if (!isa<ModuleOp, FunctionOpInterface>(getOperation())) {
132 emitError(getOperation()->getLoc(),
133 "root operation must be a builtin.module or a function");
134 signalPassFailure();
135 return;
136 }
137
138 bufferization::DeallocHelperMap deallocHelperFuncMap;
139 if (auto module = dyn_cast<ModuleOp>(getOperation())) {
140 OpBuilder builder = OpBuilder::atBlockBegin(module.getBody());
141
142 // Build dealloc helper function if there are deallocs.
143 getOperation()->walk([&](bufferization::DeallocOp deallocOp) {
144 Operation *symtableOp =
145 deallocOp->getParentWithTrait<OpTrait::SymbolTable>();
146 if (deallocOp.getMemrefs().size() > 1 &&
147 !deallocHelperFuncMap.contains(symtableOp)) {
148 SymbolTable symbolTable(symtableOp);
149 func::FuncOp helperFuncOp =
151 builder, getOperation()->getLoc(), symbolTable);
152 deallocHelperFuncMap[symtableOp] = helperFuncOp;
153 }
154 });
155 }
156
157 RewritePatternSet patterns(&getContext());
158 patterns.add<CloneOpConversion>(patterns.getContext());
160 patterns, deallocHelperFuncMap);
161
162 ConversionTarget target(getContext());
163 target.addLegalDialect<memref::MemRefDialect, arith::ArithDialect,
164 scf::SCFDialect, func::FuncDialect>();
165 target.addIllegalDialect<bufferization::BufferizationDialect>();
166
167 if (failed(applyPartialConversion(getOperation(), target,
168 std::move(patterns))))
169 signalPassFailure();
170 }
171};
172} // namespace
return success()
b getContext())
static OpBuilder atBlockBegin(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
Definition Builders.h:243
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
void populateBufferizationDeallocLoweringPattern(RewritePatternSet &patterns, const DeallocHelperMap &deallocHelperFuncMap)
Adds the conversion pattern of the bufferization.dealloc operation to the given pattern set for use i...
llvm::DenseMap< Operation *, func::FuncOp > DeallocHelperMap
Maps from symbol table to its corresponding dealloc helper function.
Definition Passes.h:25
func::FuncOp buildDeallocationLibraryFunction(OpBuilder &builder, Location loc, SymbolTable &symbolTable)
Construct the library function needed for the fully generic bufferization.dealloc lowering implemente...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.