1 //===- Promotion.cpp - Implementation of linalg Promotion -----------------===//
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 the linalg dialect Promotion pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Affine/EDSC/Intrinsics.h"
15 #include "mlir/Dialect/Linalg/EDSC/FoldedIntrinsics.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
18 #include "mlir/Dialect/Linalg/Passes.h"
19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
20 #include "mlir/Dialect/Linalg/Utils/Utils.h"
21 #include "mlir/Dialect/SCF/SCF.h"
22 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
23 #include "mlir/IR/AffineExpr.h"
24 #include "mlir/IR/AffineExprVisitor.h"
25 #include "mlir/IR/AffineMap.h"
26 #include "mlir/Support/LLVM.h"
27 #include "mlir/Transforms/FoldUtils.h"
28 #include "llvm/ADT/MapVector.h"
29 #include "llvm/Support/CommandLine.h"
30 
31 using namespace mlir;
32 using namespace mlir::edsc;
33 using namespace mlir::edsc::intrinsics;
34 using namespace mlir::linalg;
35 using namespace mlir::scf;
36 
37 using llvm::MapVector;
38 
39 using folded_affine_min = FoldedValueBuilder<AffineMinOp>;
40 using folded_linalg_range = FoldedValueBuilder<linalg::RangeOp>;
41 using folded_std_dim = FoldedValueBuilder<DimOp>;
42 using folded_std_subview = FoldedValueBuilder<SubViewOp>;
43 using folded_std_view = FoldedValueBuilder<ViewOp>;
44 
45 #define DEBUG_TYPE "linalg-promotion"
46 
47 /// If `size` comes from an AffineMinOp and one of the values of AffineMinOp
48 /// is a constant then return a new value set to the smallest such constant.
49 /// Otherwise return size.
50 static Value extractSmallestConstantBoundingSize(OpBuilder &b, Location loc,
51                                                  Value size) {
52   Optional<int64_t> boundingConst = {};
53   if (auto affineMinOp = size.getDefiningOp<AffineMinOp>()) {
54     for (auto e : affineMinOp.getAffineMap().getResults())
55       if (auto cst = e.dyn_cast<AffineConstantExpr>())
56         boundingConst = boundingConst
57                             ? std::min(boundingConst.getValue(), cst.getValue())
58                             : cst.getValue();
59   } else if (auto constIndexOp = size.getDefiningOp<ConstantOp>()) {
60     if (constIndexOp.getType().isa<IndexType>())
61       boundingConst = constIndexOp.value().cast<IntegerAttr>().getInt();
62   }
63   return boundingConst && *boundingConst >= 0
64              ? b.create<ConstantIndexOp>(loc, *boundingConst)
65              : size;
66 }
67 
68 /// Alloc a new buffer of `size`. If `dynamicBuffers` is true allocate exactly
69 /// the size needed, otherwise try to allocate a static bounding box.
70 static Value allocBuffer(Type elementType, Value size, bool dynamicBuffers,
71                          OperationFolder *folder,
72                          Optional<unsigned> alignment = None) {
73   auto *ctx = size.getContext();
74   auto width = llvm::divideCeil(elementType.getIntOrFloatBitWidth(), 8);
75   IntegerAttr alignment_attr;
76   if (alignment.hasValue())
77     alignment_attr =
78         IntegerAttr::get(IntegerType::get(64, ctx), alignment.getValue());
79   if (!dynamicBuffers)
80     if (auto cst = size.getDefiningOp<ConstantIndexOp>())
81       return std_alloc(
82           MemRefType::get(width * cst.getValue(), IntegerType::get(8, ctx)),
83           ValueRange{}, alignment_attr);
84   Value mul =
85       folded_std_muli(folder, folded_std_constant_index(folder, width), size);
86   return std_alloc(MemRefType::get(-1, IntegerType::get(8, ctx)), mul,
87                    alignment_attr);
88 }
89 
90 /// Default allocation callback function. This allocates a promoted buffer when
91 /// no call back to do so is provided. The default is to allocate a
92 /// memref<..xi8> and return a view to get a memref type of shape
93 /// boundingSubViewSize.
94 static Optional<Value>
95 allocBufferCallBack(OpBuilder &builder, SubViewOp subView,
96                     ArrayRef<Value> boundingSubViewSize, bool dynamicBuffers,
97                     Optional<unsigned> alignment, OperationFolder *folder) {
98   ShapedType viewType = subView.getType();
99   int64_t rank = viewType.getRank();
100   (void)rank;
101   assert(rank > 0 && boundingSubViewSize.size() == static_cast<size_t>(rank));
102   auto zero = folded_std_constant_index(folder, 0);
103   auto one = folded_std_constant_index(folder, 1);
104 
105   Value allocSize = one;
106   for (auto size : llvm::enumerate(boundingSubViewSize))
107     allocSize = folded_std_muli(folder, allocSize, size.value());
108   Value buffer = allocBuffer(viewType.getElementType(), allocSize,
109                              dynamicBuffers, folder, alignment);
110   SmallVector<int64_t, 4> dynSizes(boundingSubViewSize.size(),
111                                    ShapedType::kDynamicSize);
112   Value view = folded_std_view(
113       folder, MemRefType::get(dynSizes, viewType.getElementType()), buffer,
114       zero, boundingSubViewSize);
115   return view;
116 }
117 
118 /// Default implementation of deallocation of the buffer use for promotion. It
119 /// expects to get the same value that the default allocation method returned,
120 /// i.e. result of a ViewOp.
121 static LogicalResult deallocCallBack(OpBuilder &b, Value fullLocalView) {
122   auto viewOp = fullLocalView.getDefiningOp<ViewOp>();
123   assert(viewOp && "expected full local view to be a ViewOp");
124   std_dealloc(viewOp.source());
125   return success();
126 }
127 
128 namespace {
129 
130 /// Helper struct that captures the information required to apply the
131 /// transformation on each op. This bridges the abstraction gap with the
132 /// user-facing API which exposes positional arguments to control which operands
133 /// are promoted.
134 struct LinalgOpInstancePromotionOptions {
135   LinalgOpInstancePromotionOptions(LinalgOp op,
136                                    const LinalgPromotionOptions &options);
137   /// SubViews to promote.
138   MapVector<unsigned, Value> subViews;
139   /// True if the full view should be used for the promoted buffer.
140   DenseMap<Value, bool> useFullTileBuffers;
141 
142   /// Callback functions for allocation and deallocation of promoted buffers, as
143   /// well as to copy the data into and out of these buffers.
144   AllocBufferCallbackFn allocationFn;
145   DeallocBufferCallbackFn deallocationFn;
146   CopyCallbackFn copyInFn;
147   CopyCallbackFn copyOutFn;
148 
149   /// Allow the use of dynamicaly-sized buffers.
150   bool dynamicBuffers;
151   /// Alignment of promoted buffer.
152   Optional<unsigned> alignment;
153 };
154 
155 struct PromotionInfo {
156   Value fullLocalView;
157   Value partialLocalView;
158 };
159 } // namespace
160 
161 LinalgOpInstancePromotionOptions::LinalgOpInstancePromotionOptions(
162     LinalgOp linalgOp, const LinalgPromotionOptions &options)
163     : subViews(), dynamicBuffers(options.dynamicBuffers),
164       alignment(options.alignment) {
165   unsigned nBuffers = linalgOp.getNumInputsAndOutputBuffers();
166   auto vUseFullTileBuffers =
167       options.useFullTileBuffers.getValueOr(llvm::SmallBitVector());
168   vUseFullTileBuffers.resize(nBuffers, options.useFullTileBuffersDefault);
169 
170   for (unsigned idx = 0; idx != nBuffers; ++idx) {
171     if (options.operandsToPromote && !options.operandsToPromote->count(idx))
172       continue;
173     auto *op = linalgOp.getBuffer(idx).getDefiningOp();
174     if (auto sv = dyn_cast_or_null<SubViewOp>(op)) {
175       subViews[idx] = sv;
176       useFullTileBuffers[sv] = vUseFullTileBuffers[idx];
177     }
178   }
179 
180   allocationFn =
181       (options.allocationFn ? *(options.allocationFn)
182                             : [&](OpBuilder &builder, SubViewOp subViewOp,
183                                   ArrayRef<Value> boundingSubViewSize,
184                                   OperationFolder *folder) -> Optional<Value> {
185         return allocBufferCallBack(builder, subViewOp, boundingSubViewSize,
186                                    dynamicBuffers, alignment, folder);
187       });
188   deallocationFn =
189       (options.deallocationFn ? *(options.deallocationFn) : deallocCallBack);
190   auto defaultCopyCallBack = [&](OpBuilder &builder, Value src,
191                                  Value dst) -> LogicalResult {
192     linalg_copy(src, dst);
193     return success();
194   };
195   copyInFn = (options.copyInFn ? *(options.copyInFn) : defaultCopyCallBack);
196   copyOutFn = (options.copyOutFn ? *(options.copyOutFn) : defaultCopyCallBack);
197 }
198 
199 // Performs promotion of a `subView` into a local buffer of the size of the
200 // *ranges* of the `subView`. This produces a buffer whose size may be bigger
201 // than the actual size of the `subView` at the boundaries.
202 // This is related to the full/partial tile problem.
203 // Returns a PromotionInfo containing a `buffer`, `fullLocalView` and
204 // `partialLocalView` such that:
205 //   * `buffer` is always the size of the full tile.
206 //   * `fullLocalView` is a dense contiguous view into that buffer.
207 //   * `partialLocalView` is a dense non-contiguous slice of `fullLocalView`
208 //     that corresponds to the size of `subView` and accounting for boundary
209 //     effects.
210 // The point of the full tile buffer is that constant static tile sizes are
211 // folded and result in a buffer type with statically known size and alignment
212 // properties.
213 // To account for general boundary effects, padding must be performed on the
214 // boundary tiles. For now this is done with an unconditional `fill` op followed
215 // by a partial `copy` op.
216 static Optional<PromotionInfo>
217 promoteSubviewAsNewBuffer(OpBuilder &b, Location loc, SubViewOp subView,
218                           LinalgOpInstancePromotionOptions const &options,
219                           OperationFolder *folder) {
220   auto viewType = subView.getType();
221   auto rank = viewType.getRank();
222   SmallVector<Value, 4> fullSizes, partialSizes;
223   fullSizes.reserve(rank);
224   partialSizes.reserve(rank);
225   for (auto en : llvm::enumerate(subView.getOrCreateRanges(b, loc))) {
226     auto rangeValue = en.value();
227     // Try to extract a tight constant.
228     LLVM_DEBUG(llvm::dbgs() << "Extract tightest: " << rangeValue.size << "\n");
229     Value size = extractSmallestConstantBoundingSize(b, loc, rangeValue.size);
230     LLVM_DEBUG(llvm::dbgs() << "Extracted tightest: " << size << "\n");
231     fullSizes.push_back(size);
232     partialSizes.push_back(folded_std_dim(folder, subView, en.index()));
233   }
234   SmallVector<int64_t, 4> dynSizes(fullSizes.size(), -1);
235   // If a callback is not specified, then use the default implementation for
236   // allocating the promoted buffer.
237   Optional<Value> fullLocalView =
238       options.allocationFn(b, subView, fullSizes, folder);
239   if (!fullLocalView)
240     return {};
241   auto zero = folded_std_constant_index(folder, 0);
242   auto one = folded_std_constant_index(folder, 1);
243   SmallVector<Value, 4> zeros(fullSizes.size(), zero);
244   SmallVector<Value, 4> ones(fullSizes.size(), one);
245   auto partialLocalView =
246       folded_std_subview(folder, *fullLocalView, zeros, partialSizes, ones);
247   return PromotionInfo{*fullLocalView, partialLocalView};
248 }
249 
250 static Optional<MapVector<unsigned, PromotionInfo>>
251 promoteSubViews(OpBuilder &b, Location loc,
252                 LinalgOpInstancePromotionOptions options,
253                 OperationFolder *folder) {
254   if (options.subViews.empty())
255     return {};
256 
257   ScopedContext scope(b, loc);
258   MapVector<unsigned, PromotionInfo> promotionInfoMap;
259 
260   for (auto v : options.subViews) {
261     SubViewOp subView = cast<SubViewOp>(v.second.getDefiningOp());
262     Optional<PromotionInfo> promotionInfo =
263         promoteSubviewAsNewBuffer(b, loc, subView, options, folder);
264     if (!promotionInfo)
265       return {};
266     promotionInfoMap[v.first] = *promotionInfo;
267 
268     // Only fill the buffer if the full local view is used
269     if (!options.useFullTileBuffers[v.second])
270       continue;
271     Value fillVal;
272     if (auto t = subView.getType().getElementType().dyn_cast<FloatType>())
273       fillVal = folded_std_constant(folder, FloatAttr::get(t, 0.0));
274     else if (auto t =
275                  subView.getType().getElementType().dyn_cast<IntegerType>())
276       fillVal = folded_std_constant_int(folder, 0, t);
277     linalg_fill(promotionInfo->fullLocalView, fillVal);
278   }
279 
280   // Copy data into the promoted buffers. Use callback if provided.
281   for (auto v : options.subViews) {
282     auto info = promotionInfoMap.find(v.first);
283     if (info == promotionInfoMap.end())
284       continue;
285     if (failed(options.copyInFn(b, cast<SubViewOp>(v.second.getDefiningOp()),
286                                 info->second.partialLocalView)))
287       return {};
288   }
289   return promotionInfoMap;
290 }
291 
292 static Optional<LinalgOp>
293 promoteSubViews(OpBuilder &b, LinalgOp op,
294                 LinalgOpInstancePromotionOptions options,
295                 OperationFolder *folder) {
296   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
297 
298   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
299     // TODO(ntv): add a level of indirection to linalg.generic.
300     if (convOp.padding())
301       return {};
302   }
303 
304   // 1. Promote the specified views and use them in the new op.
305   auto loc = op.getLoc();
306   auto promotedBuffersAndViews = promoteSubViews(b, loc, options, folder);
307   if (!promotedBuffersAndViews ||
308       promotedBuffersAndViews->size() != options.subViews.size())
309     return {};
310 
311   // 2. Append all other operands as they appear, this enforces that such
312   // operands are not views. This is to support cases such as FillOp taking
313   // extra scalars etc.  Keep a reference to output buffers;
314   SmallVector<Value, 8> opViews;
315   opViews.reserve(op.getNumInputsAndOutputs());
316   SmallVector<std::pair<Value, Value>, 8> writebackViews;
317   writebackViews.reserve(promotedBuffersAndViews->size());
318   for (auto view : llvm::enumerate(op.getInputsAndOutputBuffers())) {
319     if (options.subViews.count(view.index()) != 0) {
320       if (options.useFullTileBuffers[view.value()])
321         opViews.push_back(
322             (*promotedBuffersAndViews)[view.index()].fullLocalView);
323       else
324         opViews.push_back(
325             (*promotedBuffersAndViews)[view.index()].partialLocalView);
326       if (view.index() >= op.getNumInputs())
327         writebackViews.emplace_back(std::make_pair(
328             view.value(),
329             (*promotedBuffersAndViews)[view.index()].partialLocalView));
330     } else {
331       opViews.push_back(view.value());
332     }
333   }
334   op.getOperation()->setOperands(0, opViews.size(), opViews);
335 
336   OpBuilder::InsertionGuard guard(b);
337   b.setInsertionPointAfter(op);
338   ScopedContext scope(b, loc);
339   // 3. Emit write-back for the promoted output views: copy the partial view.
340   for (auto viewAndPartialLocalView : writebackViews) {
341     if (failed(options.copyOutFn(b, viewAndPartialLocalView.second,
342                                  viewAndPartialLocalView.first)))
343       return {};
344   }
345 
346   // 4. Dealloc all local buffers.
347   for (const auto &pi : *promotedBuffersAndViews) {
348     options.deallocationFn(b, pi.second.fullLocalView);
349   }
350   return op;
351 }
352 
353 LogicalResult
354 mlir::linalg::promoteSubviewsPrecondition(Operation *op,
355                                           LinalgPromotionOptions options) {
356   LinalgOp linOp = dyn_cast<LinalgOp>(op);
357   // Transformation applies to buffers only.
358   if (!linOp || !linOp.hasBufferSemantics())
359     return failure();
360   // Check that at least one of the requested operands is indeed a subview.
361   for (auto en : llvm::enumerate(linOp.getInputsAndOutputBuffers())) {
362     auto sv = isa_and_nonnull<SubViewOp>(en.value().getDefiningOp());
363     if (sv) {
364       if (!options.operandsToPromote.hasValue() ||
365           options.operandsToPromote->count(en.index()))
366         return success();
367     }
368   }
369   // TODO: Check all subviews requested are bound by a static constant.
370   // TODO: Check that the total footprint fits within a given size.
371   return failure();
372 }
373 
374 Optional<LinalgOp> mlir::linalg::promoteSubViews(OpBuilder &b,
375                                                  LinalgOp linalgOp,
376                                                  LinalgPromotionOptions options,
377                                                  OperationFolder *folder) {
378   LinalgOpInstancePromotionOptions linalgOptions(linalgOp, options);
379   return ::promoteSubViews(
380       b, linalgOp, LinalgOpInstancePromotionOptions(linalgOp, options), folder);
381 }
382 
383 namespace {
384 struct LinalgPromotionPass : public LinalgPromotionBase<LinalgPromotionPass> {
385   LinalgPromotionPass() = default;
386   LinalgPromotionPass(bool dynamicBuffers) {
387     this->dynamicBuffers = dynamicBuffers;
388   }
389 
390   void runOnFunction() override {
391     OperationFolder folder(&getContext());
392     getFunction().walk([this, &folder](LinalgOp op) {
393       auto options = LinalgPromotionOptions().setDynamicBuffers(dynamicBuffers);
394       if (failed(promoteSubviewsPrecondition(op, options)))
395         return;
396       LLVM_DEBUG(llvm::dbgs() << "Promote: " << *(op.getOperation()) << "\n");
397       OpBuilder b(op);
398       promoteSubViews(b, op, options, &folder);
399     });
400   }
401 };
402 } // namespace
403 
404 // TODO: support more transformation options in the pass.
405 std::unique_ptr<OperationPass<FuncOp>>
406 mlir::createLinalgPromotionPass(bool dynamicBuffers) {
407   return std::make_unique<LinalgPromotionPass>(dynamicBuffers);
408 }
409 std::unique_ptr<OperationPass<FuncOp>> mlir::createLinalgPromotionPass() {
410   return std::make_unique<LinalgPromotionPass>();
411 }
412