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