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 Value *allocBuffer(Type elementType, Value *size, bool dynamicBuffers) { 59 auto *ctx = size->getContext(); 60 auto width = llvm::divideCeil(elementType.getIntOrFloatBitWidth(), 8); 61 if (!dynamicBuffers) 62 if (auto cst = dyn_cast_or_null<ConstantIndexOp>(size->getDefiningOp())) 63 return alloc( 64 MemRefType::get(width * cst.getValue(), IntegerType::get(8, ctx))); 65 Value *mul = muli(constant_index(width), size); 66 return alloc(MemRefType::get(-1, IntegerType::get(8, ctx)), mul); 67 } 68 69 // Performs promotion of a `subView` into a local buffer of the size of the 70 // *ranges* of the `subView`. This produces a buffer whose size may be bigger 71 // than the actual size of the `subView` at the boundaries. 72 // This is related to the full/partial tile problem. 73 // Returns a PromotionInfo containing a `buffer`, `fullLocalView` and 74 // `partialLocalView` such that: 75 // * `buffer` is always the size of the full tile. 76 // * `fullLocalView` is a dense contiguous view into that buffer. 77 // * `partialLocalView` is a dense non-contiguous slice of `fullLocalView` 78 // that corresponds to the size of `subView` and accounting for boundary 79 // effects. 80 // The point of the full tile buffer is that constant static tile sizes are 81 // folded and result in a buffer type with statically known size and alignment 82 // properties. 83 // To account for general boundary effects, padding must be performed on the 84 // boundary tiles. For now this is done with an unconditional `fill` op followed 85 // by a partial `copy` op. 86 static PromotionInfo promoteFullTileBuffer(OpBuilder &b, Location loc, 87 SubViewOp subView, 88 bool dynamicBuffers, 89 OperationFolder *folder) { 90 auto zero = constant_index(folder, 0); 91 auto one = constant_index(folder, 1); 92 93 auto viewType = subView.getType(); 94 auto rank = viewType.getRank(); 95 Value *allocSize = one; 96 SmallVector<Value *, 8> fullRanges, partialRanges; 97 fullRanges.reserve(rank); 98 partialRanges.reserve(rank); 99 for (auto en : llvm::enumerate(subView.getRanges())) { 100 auto rank = en.index(); 101 auto rangeValue = en.value(); 102 Value *d = rangeValue.size; 103 allocSize = muli(folder, allocSize, d).getValue(); 104 fullRanges.push_back(d); 105 partialRanges.push_back(range(folder, zero, dim(subView, rank), one)); 106 } 107 SmallVector<int64_t, 4> dynSizes(fullRanges.size(), -1); 108 auto *buffer = 109 allocBuffer(viewType.getElementType(), allocSize, dynamicBuffers); 110 auto fullLocalView = view( 111 MemRefType::get(dynSizes, viewType.getElementType()), buffer, fullRanges); 112 auto partialLocalView = slice(fullLocalView, partialRanges); 113 return PromotionInfo{buffer, fullLocalView, partialLocalView}; 114 } 115 116 SmallVector<PromotionInfo, 8> 117 mlir::linalg::promoteSubViews(OpBuilder &b, Location loc, 118 ArrayRef<Value *> subViews, bool dynamicBuffers, 119 OperationFolder *folder) { 120 if (subViews.empty()) 121 return {}; 122 123 ScopedContext scope(b, loc); 124 SmallVector<PromotionInfo, 8> res; 125 res.reserve(subViews.size()); 126 DenseMap<Value *, PromotionInfo> promotionInfoMap; 127 for (auto *v : subViews) { 128 SubViewOp subView = cast<SubViewOp>(v->getDefiningOp()); 129 auto viewType = subView.getType(); 130 // TODO(ntv): support more cases than just float. 131 if (!viewType.getElementType().isa<FloatType>()) 132 continue; 133 auto promotionInfo = 134 promoteFullTileBuffer(b, loc, subView, dynamicBuffers, folder); 135 promotionInfoMap.insert(std::make_pair(subView.getResult(), promotionInfo)); 136 res.push_back(promotionInfo); 137 } 138 139 for (auto *v : subViews) { 140 SubViewOp subView = cast<SubViewOp>(v->getDefiningOp()); 141 auto info = promotionInfoMap.find(v); 142 if (info == promotionInfoMap.end()) 143 continue; 144 // TODO(ntv): value to fill with should be related to the operation. 145 // For now, just use APFloat(0.0f). 146 auto t = subView.getType().getElementType().cast<FloatType>(); 147 Value *fillVal = constant_float(folder, APFloat(0.0f), t); 148 // TODO(ntv): fill is only necessary if `promotionInfo` has a full local 149 // view that is different from the partial local view and we are on the 150 // boundary. 151 fill(info->second.fullLocalView, fillVal); 152 } 153 154 for (auto *v : subViews) { 155 auto info = promotionInfoMap.find(v); 156 if (info == promotionInfoMap.end()) 157 continue; 158 copy(cast<SubViewOp>(v->getDefiningOp()), info->second.partialLocalView); 159 } 160 return res; 161 } 162 163 static void promoteSubViewOperands(LinalgOp op, SetVector<Value *> subViews, 164 bool dynamicBuffers, 165 OperationFolder *folder) { 166 // 1. Promote the specified views and use them in the new op. 167 OpBuilder b(op); 168 ScopedContext scope(b, op.getLoc()); 169 auto promotedBufferAndViews = promoteSubViews( 170 b, op.getLoc(), subViews.getArrayRef(), dynamicBuffers, folder); 171 SmallVector<Value *, 8> opViews; 172 opViews.reserve(op.getNumInputsAndOutputs()); 173 SmallVector<std::pair<Value *, Value *>, 8> writebackViews; 174 writebackViews.reserve(subViews.size()); 175 unsigned promotedIdx = 0; 176 for (auto *view : op.getInputsAndOutputs()) { 177 if (subViews.count(view) != 0) { 178 opViews.push_back(promotedBufferAndViews[promotedIdx].fullLocalView); 179 writebackViews.emplace_back(std::make_pair( 180 view, promotedBufferAndViews[promotedIdx].partialLocalView)); 181 promotedIdx++; 182 } else { 183 opViews.push_back(view); 184 } 185 } 186 187 // 2. Append all other operands as they appear, this enforces that such 188 // operands are not views. This is to support cases such as FillOp taking 189 // extra scalars etc. 190 auto operands = getAssumedNonViewOperands(op); 191 opViews.append(operands.begin(), operands.end()); 192 op.clone(b, op.getLoc(), opViews); 193 194 // 3. Emit write-back for the promoted output views: copy the partial view. 195 for (auto viewAndPartialLocalView : writebackViews) { 196 // Note: use the old op to determine whether the operand view is an output. 197 bool isOutput = 198 op.getIndexOfOutput(viewAndPartialLocalView.first).hasValue(); 199 if (isOutput) 200 copy(viewAndPartialLocalView.second, viewAndPartialLocalView.first); 201 } 202 203 // 4. Dealloc local buffers. 204 for (const auto &pi : promotedBufferAndViews) 205 dealloc(pi.buffer); 206 } 207 208 static void promoteSubViews(FuncOp f, bool dynamicBuffers) { 209 SmallVector<LinalgOp, 8> toErase; 210 OperationFolder folder(f.getContext()); 211 f.walk([dynamicBuffers, &folder, &toErase](LinalgOp op) { 212 // TODO(ntv) some heuristic here to decide what to promote. Atm it is all or 213 // nothing. 214 SetVector<Value *> subViews; 215 for (auto it : op.getInputsAndOutputs()) 216 if (auto sv = dyn_cast_or_null<SubViewOp>(it->getDefiningOp())) 217 subViews.insert(sv); 218 if (!subViews.empty()) { 219 promoteSubViewOperands(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