1 //===- Bufferize.cpp - Bufferization for std ops --------------------------===//
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 bufferization of std ops.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "mlir/Transforms/Bufferize.h"
14 #include "PassDetail.h"
15 #include "mlir/Dialect/SCF/SCF.h"
16 #include "mlir/Dialect/StandardOps/IR/Ops.h"
17 #include "mlir/Dialect/StandardOps/Transforms/Passes.h"
18 #include "mlir/IR/BlockAndValueMapping.h"
19 #include "mlir/Transforms/DialectConversion.h"
20
21 using namespace mlir;
22
23 namespace {
24 class BufferizeDimOp : public OpConversionPattern<DimOp> {
25 public:
26 using OpConversionPattern::OpConversionPattern;
27 LogicalResult
matchAndRewrite(DimOp op,ArrayRef<Value> operands,ConversionPatternRewriter & rewriter) const28 matchAndRewrite(DimOp op, ArrayRef<Value> operands,
29 ConversionPatternRewriter &rewriter) const override {
30 DimOp::Adaptor adaptor(operands);
31 rewriter.replaceOpWithNewOp<DimOp>(op, adaptor.memrefOrTensor(),
32 adaptor.index());
33 return success();
34 }
35 };
36 } // namespace
37
38 namespace {
39 class BufferizeDynamicTensorFromElementsOp
40 : public OpConversionPattern<DynamicTensorFromElementsOp> {
41 public:
42 using OpConversionPattern::OpConversionPattern;
43
44 LogicalResult
matchAndRewrite(DynamicTensorFromElementsOp op,ArrayRef<Value> operands,ConversionPatternRewriter & rewriter) const45 matchAndRewrite(DynamicTensorFromElementsOp op, ArrayRef<Value> operands,
46 ConversionPatternRewriter &rewriter) const final {
47 // Allocate memory.
48 Location loc = op.getLoc();
49 DynamicTensorFromElementsOp::Adaptor transformed(operands);
50 RankedTensorType tensorType = op.getType().cast<RankedTensorType>();
51 MemRefType memrefType =
52 MemRefType::get(tensorType.getShape(), tensorType.getElementType());
53 Value result =
54 rewriter.create<AllocOp>(loc, memrefType, transformed.dynamicExtents());
55
56 // Collect loop bounds.
57 int64_t rank = tensorType.getRank();
58 Value zero = rewriter.create<ConstantIndexOp>(loc, 0);
59 Value one = rewriter.create<ConstantIndexOp>(loc, 1);
60 SmallVector<Value, 4> lowerBounds(rank, zero);
61 SmallVector<Value, 4> steps(rank, one);
62 SmallVector<Value, 4> upperBounds;
63 int nextDynamicIndex = 0;
64 for (int i = 0; i < rank; i++) {
65 Value upperBound =
66 tensorType.isDynamicDim(i)
67 ? transformed.dynamicExtents()[nextDynamicIndex++]
68 : rewriter.create<ConstantIndexOp>(loc, memrefType.getDimSize(i));
69 upperBounds.push_back(upperBound);
70 }
71
72 // Generate tensor elements with a parallel loop.
73 rewriter.create<scf::ParallelOp>(
74 loc, lowerBounds, upperBounds, steps,
75 [&](OpBuilder &b, Location loc, ValueRange ivs) {
76 BlockAndValueMapping mapping;
77 mapping.map(op.body().getArguments(), ivs);
78 for (auto &nestedOp : op.getBody()->without_terminator())
79 b.clone(nestedOp, mapping);
80 auto yieldOp = cast<YieldOp>(op.getBody()->getTerminator());
81 b.create<StoreOp>(loc, mapping.lookup(yieldOp.value()), result, ivs);
82 b.create<scf::YieldOp>(loc);
83 });
84
85 rewriter.replaceOp(op, {result});
86 return success();
87 }
88 };
89 } // namespace
90
91 namespace {
92 class BufferizeExtractElementOp : public OpConversionPattern<ExtractElementOp> {
93 public:
94 using OpConversionPattern::OpConversionPattern;
95 LogicalResult
matchAndRewrite(ExtractElementOp op,ArrayRef<Value> operands,ConversionPatternRewriter & rewriter) const96 matchAndRewrite(ExtractElementOp op, ArrayRef<Value> operands,
97 ConversionPatternRewriter &rewriter) const override {
98 ExtractElementOp::Adaptor adaptor(operands);
99 rewriter.replaceOpWithNewOp<LoadOp>(op, adaptor.aggregate(),
100 adaptor.indices());
101 return success();
102 }
103 };
104 } // namespace
105
106 namespace {
107 class BufferizeSelectOp : public OpConversionPattern<SelectOp> {
108 public:
109 using OpConversionPattern::OpConversionPattern;
110 LogicalResult
matchAndRewrite(SelectOp op,ArrayRef<Value> operands,ConversionPatternRewriter & rewriter) const111 matchAndRewrite(SelectOp op, ArrayRef<Value> operands,
112 ConversionPatternRewriter &rewriter) const override {
113 if (!op.condition().getType().isa<IntegerType>())
114 return rewriter.notifyMatchFailure(op, "requires scalar condition");
115
116 SelectOp::Adaptor adaptor(operands);
117 rewriter.replaceOpWithNewOp<SelectOp>(
118 op, adaptor.condition(), adaptor.true_value(), adaptor.false_value());
119 return success();
120 }
121 };
122 } // namespace
123
124 namespace {
125 class BufferizeTensorCastOp : public OpConversionPattern<TensorCastOp> {
126 public:
127 using OpConversionPattern::OpConversionPattern;
128 LogicalResult
matchAndRewrite(TensorCastOp op,ArrayRef<Value> operands,ConversionPatternRewriter & rewriter) const129 matchAndRewrite(TensorCastOp op, ArrayRef<Value> operands,
130 ConversionPatternRewriter &rewriter) const override {
131 auto resultType = getTypeConverter()->convertType(op.getType());
132 rewriter.replaceOpWithNewOp<MemRefCastOp>(op, resultType, operands[0]);
133 return success();
134 }
135 };
136 } // namespace
137
138 namespace {
139 class BufferizeTensorFromElementsOp
140 : public OpConversionPattern<TensorFromElementsOp> {
141 public:
142 using OpConversionPattern::OpConversionPattern;
143 LogicalResult
matchAndRewrite(TensorFromElementsOp op,ArrayRef<Value> operands,ConversionPatternRewriter & rewriter) const144 matchAndRewrite(TensorFromElementsOp op, ArrayRef<Value> operands,
145 ConversionPatternRewriter &rewriter) const override {
146 int numberOfElements = op.elements().size();
147 auto resultType = MemRefType::get(
148 {numberOfElements}, op.getType().cast<TensorType>().getElementType());
149 Value result = rewriter.create<AllocOp>(op.getLoc(), resultType);
150 for (auto element : llvm::enumerate(op.elements())) {
151 Value index =
152 rewriter.create<ConstantIndexOp>(op.getLoc(), element.index());
153 rewriter.create<StoreOp>(op.getLoc(), element.value(), result, index);
154 }
155 rewriter.replaceOp(op, {result});
156 return success();
157 }
158 };
159 } // namespace
160
populateStdBufferizePatterns(MLIRContext * context,BufferizeTypeConverter & typeConverter,OwningRewritePatternList & patterns)161 void mlir::populateStdBufferizePatterns(MLIRContext *context,
162 BufferizeTypeConverter &typeConverter,
163 OwningRewritePatternList &patterns) {
164 patterns.insert<
165 // clang-format off
166 BufferizeDimOp,
167 BufferizeDynamicTensorFromElementsOp,
168 BufferizeExtractElementOp,
169 BufferizeSelectOp,
170 BufferizeTensorCastOp,
171 BufferizeTensorFromElementsOp
172 // clang-format on
173 >(typeConverter, context);
174 }
175
176 namespace {
177 struct StdBufferizePass : public StdBufferizeBase<StdBufferizePass> {
runOnFunction__anonb36373770811::StdBufferizePass178 void runOnFunction() override {
179 auto *context = &getContext();
180 BufferizeTypeConverter typeConverter;
181 OwningRewritePatternList patterns;
182 ConversionTarget target(*context);
183
184 target.addLegalDialect<StandardOpsDialect>();
185 target.addLegalDialect<scf::SCFDialect>();
186
187 populateStdBufferizePatterns(context, typeConverter, patterns);
188 target.addIllegalOp<DynamicTensorFromElementsOp, ExtractElementOp,
189 TensorCastOp, TensorFromElementsOp>();
190 // We only bufferize the case of tensor selected type and scalar condition,
191 // as that boils down to a select over memref descriptors (don't need to
192 // touch the data).
193 target.addDynamicallyLegalOp<SelectOp>([&](SelectOp op) {
194 return typeConverter.isLegal(op.getType()) ||
195 !op.condition().getType().isa<IntegerType>();
196 });
197 target.addDynamicallyLegalOp<DimOp>(
198 [&](DimOp op) { return typeConverter.isLegal(op); });
199 if (failed(
200 applyPartialConversion(getFunction(), target, std::move(patterns))))
201 signalPassFailure();
202 }
203 };
204 } // namespace
205
createStdBufferizePass()206 std::unique_ptr<Pass> mlir::createStdBufferizePass() {
207 return std::make_unique<StdBufferizePass>();
208 }
209