xref: /llvm-project/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp (revision 2bdf33cc4c733342fc83081bc7410ac5e9a24f55)
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   // 1. Promote the specified views and use them in the new op.
159   ScopedContext scope(b, op.getLoc());
160   auto promotedBufferAndViews = promoteSubViews(
161       b, op.getLoc(), subViews.getArrayRef(), dynamicBuffers, folder);
162   SmallVector<Value, 8> opViews;
163   opViews.reserve(op.getNumInputsAndOutputs());
164   SmallVector<std::pair<Value, Value>, 8> writebackViews;
165   writebackViews.reserve(subViews.size());
166   unsigned promotedIdx = 0;
167   for (auto view : op.getInputsAndOutputs()) {
168     if (subViews.count(view) != 0) {
169       opViews.push_back(promotedBufferAndViews[promotedIdx].fullLocalView);
170       writebackViews.emplace_back(std::make_pair(
171           view, promotedBufferAndViews[promotedIdx].partialLocalView));
172       promotedIdx++;
173     } else {
174       opViews.push_back(view);
175     }
176   }
177 
178   // 2. Append all other operands as they appear, this enforces that such
179   // operands are not views. This is to support cases such as FillOp taking
180   // extra scalars etc.
181   auto operands = getAssumedNonViewOperands(op);
182   opViews.append(operands.begin(), operands.end());
183   LinalgOp res = op.clone(b, op.getLoc(), opViews);
184 
185   // 3. Emit write-back for the promoted output views: copy the partial view.
186   for (auto viewAndPartialLocalView : writebackViews) {
187     // WARNING: MUST use the old op to determine whether the operand view is an
188     // output.
189     bool isOutput =
190         op.getIndexOfOutput(viewAndPartialLocalView.first).hasValue();
191     if (isOutput)
192       copy(viewAndPartialLocalView.second, viewAndPartialLocalView.first);
193   }
194 
195   // 4. Dealloc local buffers.
196   for (const auto &pi : promotedBufferAndViews)
197     dealloc(pi.buffer);
198 
199   return res;
200 }
201 
202 static void promoteSubViews(FuncOp f, bool dynamicBuffers) {
203   SmallVector<LinalgOp, 8> toErase;
204   OperationFolder folder(f.getContext());
205   f.walk([dynamicBuffers, &folder, &toErase](LinalgOp op) {
206     // TODO(ntv) some heuristic here to decide what to promote. Atm it is all or
207     // nothing.
208     SetVector<Value> subViews;
209     OpBuilder b(op);
210     for (auto it : op.getInputsAndOutputs())
211       if (auto sv = dyn_cast_or_null<SubViewOp>(it.getDefiningOp()))
212         subViews.insert(sv);
213     if (!subViews.empty()) {
214       promoteSubViewOperands(b, op, subViews, dynamicBuffers, &folder);
215       toErase.push_back(op);
216     }
217   });
218   for (auto op : toErase)
219     op.erase();
220 }
221 
222 namespace {
223 struct LinalgPromotionPass : public FunctionPass<LinalgPromotionPass> {
224   LinalgPromotionPass() = default;
225   LinalgPromotionPass(bool dynamicBuffers) : dynamicBuffers(dynamicBuffers) {}
226 
227   void runOnFunction() override {
228     promoteSubViews(getFunction(), dynamicBuffers);
229   }
230 
231   bool dynamicBuffers;
232 };
233 } // namespace
234 
235 std::unique_ptr<OpPassBase<FuncOp>>
236 mlir::linalg::createLinalgPromotionPass(bool dynamicBuffers) {
237   return std::make_unique<LinalgPromotionPass>(dynamicBuffers);
238 }
239 
240 static PassRegistration<LinalgPromotionPass>
241     pass("linalg-promote-subviews", "promote subview ops to local buffers", [] {
242       return std::make_unique<LinalgPromotionPass>(clPromoteDynamic);
243     });
244