xref: /llvm-project/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp (revision 0bd6390b541e8a95ee4d2fc8abcdcaf1d7c580cb)
1 //===- Promotion.cpp - Implementation of linalg Promotion -----------------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 //
18 // This file implements the linalg dialect Promotion pass.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
23 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
24 #include "mlir/Dialect/Linalg/Passes.h"
25 #include "mlir/Dialect/Linalg/Utils/Intrinsics.h"
26 #include "mlir/Dialect/Linalg/Utils/Utils.h"
27 #include "mlir/Dialect/LoopOps/LoopOps.h"
28 #include "mlir/EDSC/Helpers.h"
29 #include "mlir/IR/AffineExpr.h"
30 #include "mlir/IR/AffineExprVisitor.h"
31 #include "mlir/IR/AffineMap.h"
32 #include "mlir/IR/OpImplementation.h"
33 #include "mlir/Pass/Pass.h"
34 #include "mlir/Support/LLVM.h"
35 #include "mlir/Support/STLExtras.h"
36 #include "mlir/Transforms/FoldUtils.h"
37 
38 #include "llvm/ADT/SetVector.h"
39 #include "llvm/Support/CommandLine.h"
40 
41 using namespace mlir;
42 using namespace mlir::edsc;
43 using namespace mlir::edsc::intrinsics;
44 using namespace mlir::linalg;
45 using namespace mlir::linalg::intrinsics;
46 using namespace mlir::loop;
47 
48 using llvm::SetVector;
49 
50 #define DEBUG_TYPE "linalg-promotion"
51 
52 static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options");
53 static llvm::cl::opt<bool> clPromoteDynamic(
54     "test-linalg-promote-dynamic",
55     llvm::cl::desc("Test generation of dynamic promoted buffers"),
56     llvm::cl::cat(clOptionsCategory), llvm::cl::init(false));
57 
58 static AffineMap getAffineDifferenceMap(MLIRContext *context) {
59   AffineExpr d0(getAffineDimExpr(0, context)), d1(getAffineDimExpr(1, context));
60   return AffineMap::get(2, 0, {d0 - d1});
61 }
62 
63 static Value *allocBuffer(Type elementType, Value *size, bool dynamicBuffers) {
64   auto *ctx = size->getContext();
65   auto width = llvm::divideCeil(elementType.getIntOrFloatBitWidth(), 8);
66   if (!dynamicBuffers)
67     if (auto cst = dyn_cast_or_null<ConstantIndexOp>(size->getDefiningOp()))
68       return alloc(
69           MemRefType::get(width * cst.getValue(), IntegerType::get(8, ctx)));
70   Value *mul = muli(constant_index(width), size);
71   return alloc(MemRefType::get(-1, IntegerType::get(8, ctx)), mul);
72 }
73 
74 // Performs promotion of a `subView` into a local buffer of the size of the
75 // *ranges* of the `subView`. This produces a buffer whose size may be bigger
76 // than the actual size of the `subView` at the boundaries.
77 // This is related to the full/partial tile problem.
78 // Returns a PromotionInfo containing a `buffer`, `fullLocalView` and
79 // `partialLocalView` such that:
80 //   * `buffer` is always the size of the full tile.
81 //   * `fullLocalView` is a dense contiguous view into that buffer.
82 //   * `partialLocalView` is a dense non-contiguous slice of `fullLocalView`
83 //     that corresponds to the size of `subView` and accounting for boundary
84 //     effects.
85 // The point of the full tile buffer is that constant static tile sizes are
86 // folded and result in a buffer type with statically known size and alignment
87 // properties.
88 // To account for general boundary effects, padding must be performed on the
89 // boundary tiles. For now this is done with an unconditional `fill` op followed
90 // by a partial `copy` op.
91 static PromotionInfo promoteFullTileBuffer(OpBuilder &b, Location loc,
92                                            SubViewOp subView,
93                                            bool dynamicBuffers,
94                                            OperationFolder *folder) {
95   auto zero = constant_index(folder, 0);
96   auto one = constant_index(folder, 1);
97 
98   auto viewType = subView.getType();
99   auto rank = viewType.getRank();
100   Value *allocSize = one;
101   SmallVector<Value *, 8> fullRanges, partialRanges;
102   fullRanges.reserve(rank);
103   partialRanges.reserve(rank);
104   for (auto en : llvm::enumerate(subView.getRanges())) {
105     auto rank = en.index();
106     auto rangeValue = en.value();
107     Value *d = rangeValue.size;
108     allocSize = muli(folder, allocSize, d).getValue();
109     fullRanges.push_back(d);
110     partialRanges.push_back(range(folder, zero, dim(subView, rank), one));
111   }
112   SmallVector<int64_t, 4> dynSizes(fullRanges.size(), -1);
113   auto *buffer =
114       allocBuffer(viewType.getElementType(), allocSize, dynamicBuffers);
115   auto fullLocalView = view(
116       MemRefType::get(dynSizes, viewType.getElementType()), buffer, fullRanges);
117   auto partialLocalView = slice(fullLocalView, partialRanges);
118   return PromotionInfo{buffer, fullLocalView, partialLocalView};
119 }
120 
121 SmallVector<PromotionInfo, 8>
122 mlir::linalg::promoteSubViews(OpBuilder &b, Location loc,
123                               ArrayRef<Value *> subViews, bool dynamicBuffers,
124                               OperationFolder *folder) {
125   if (subViews.empty())
126     return {};
127 
128   ScopedContext scope(b, loc);
129   SmallVector<PromotionInfo, 8> res;
130   res.reserve(subViews.size());
131   DenseMap<Value *, PromotionInfo> promotionInfoMap;
132   for (auto *v : subViews) {
133     SubViewOp subView = cast<SubViewOp>(v->getDefiningOp());
134     auto viewType = subView.getType();
135     // TODO(ntv): support more cases than just float.
136     if (!viewType.getElementType().isa<FloatType>())
137       continue;
138     auto promotionInfo =
139         promoteFullTileBuffer(b, loc, subView, dynamicBuffers, folder);
140     promotionInfoMap.insert(std::make_pair(subView.getResult(), promotionInfo));
141     res.push_back(promotionInfo);
142   }
143 
144   for (auto *v : subViews) {
145     SubViewOp subView = cast<SubViewOp>(v->getDefiningOp());
146     auto info = promotionInfoMap.find(v);
147     if (info == promotionInfoMap.end())
148       continue;
149     // TODO(ntv): value to fill with should be related to the operation.
150     // For now, just use APFloat(0.0f).
151     auto t = subView.getType().getElementType().cast<FloatType>();
152     Value *fillVal = constant_float(folder, APFloat(0.0f), t);
153     // TODO(ntv): fill is only necessary if `promotionInfo` has a full local
154     // view that is different from the partial local view and we are on the
155     // boundary.
156     fill(info->second.fullLocalView, fillVal);
157   }
158 
159   for (auto *v : subViews) {
160     auto info = promotionInfoMap.find(v);
161     if (info == promotionInfoMap.end())
162       continue;
163     copy(cast<SubViewOp>(v->getDefiningOp()), info->second.partialLocalView);
164   }
165   return res;
166 }
167 
168 static void promoteSubViewOperands(LinalgOp op, SetVector<Value *> subViews,
169                                    bool dynamicBuffers,
170                                    OperationFolder *folder) {
171   // 1. Promote the specified views and use them in the new op.
172   OpBuilder b(op);
173   ScopedContext scope(b, op.getLoc());
174   auto promotedBufferAndViews = promoteSubViews(
175       b, op.getLoc(), subViews.getArrayRef(), dynamicBuffers, folder);
176   SmallVector<Value *, 8> opViews;
177   opViews.reserve(op.getNumInputsAndOutputs());
178   SmallVector<std::pair<Value *, Value *>, 8> writebackViews;
179   writebackViews.reserve(subViews.size());
180   unsigned promotedIdx = 0;
181   for (auto *view : op.getInputsAndOutputs()) {
182     if (subViews.count(view) != 0) {
183       opViews.push_back(promotedBufferAndViews[promotedIdx].fullLocalView);
184       writebackViews.emplace_back(std::make_pair(
185           view, promotedBufferAndViews[promotedIdx].partialLocalView));
186       promotedIdx++;
187     } else {
188       opViews.push_back(view);
189     }
190   }
191 
192   // 2. Append all other operands as they appear, this enforces that such
193   // operands are not views. This is to support cases such as FillOp taking
194   // extra scalars etc.
195   auto operands = getAssumedNonViewOperands(op);
196   opViews.append(operands.begin(), operands.end());
197   op.clone(b, op.getLoc(), opViews);
198 
199   // 3. Emit write-back for the promoted output views: copy the partial view.
200   for (auto viewAndPartialLocalView : writebackViews) {
201     // Note: use the old op to determine whether the operand view is an output.
202     bool isOutput =
203         op.getIndexOfOutput(viewAndPartialLocalView.first).hasValue();
204     if (isOutput)
205       copy(viewAndPartialLocalView.second, viewAndPartialLocalView.first);
206   }
207 
208   // 4. Dealloc local buffers.
209   for (const auto &pi : promotedBufferAndViews)
210     dealloc(pi.buffer);
211 }
212 
213 static void promoteSubViews(FuncOp f, bool dynamicBuffers) {
214   SmallVector<LinalgOp, 8> toErase;
215   OperationFolder folder(f.getContext());
216   f.walk([dynamicBuffers, &folder, &toErase](LinalgOp op) {
217     // TODO(ntv) some heuristic here to decide what to promote. Atm it is all or
218     // nothing.
219     SetVector<Value *> subViews;
220     for (auto it : op.getInputsAndOutputs())
221       if (auto sv = dyn_cast_or_null<SubViewOp>(it->getDefiningOp()))
222         subViews.insert(sv);
223     if (!subViews.empty()) {
224       promoteSubViewOperands(op, subViews, dynamicBuffers, &folder);
225       toErase.push_back(op);
226     }
227   });
228   for (auto op : toErase)
229     op.erase();
230 }
231 
232 namespace {
233 struct LinalgPromotionPass : public FunctionPass<LinalgPromotionPass> {
234   LinalgPromotionPass() = default;
235   LinalgPromotionPass(bool dynamicBuffers) : dynamicBuffers(dynamicBuffers) {}
236 
237   void runOnFunction() override {
238     promoteSubViews(getFunction(), dynamicBuffers);
239   }
240 
241   bool dynamicBuffers;
242 };
243 } // namespace
244 
245 std::unique_ptr<OpPassBase<FuncOp>>
246 mlir::linalg::createLinalgPromotionPass(bool dynamicBuffers) {
247   return std::make_unique<LinalgPromotionPass>(dynamicBuffers);
248 }
249 
250 static PassRegistration<LinalgPromotionPass>
251     pass("linalg-promote-subviews", "promote subview ops to local buffers", [] {
252       return std::make_unique<LinalgPromotionPass>(clPromoteDynamic);
253     });
254