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.getViewType(); 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 = 108 isa<DimOp>(rangeValue.max->getDefiningOp()) 109 ? rangeValue.max 110 : applyMapToValues(b, loc, getAffineDifferenceMap(b.getContext()), 111 {rangeValue.max, rangeValue.min}, folder) 112 .front(); 113 allocSize = muli(folder, allocSize, d).getValue(); 114 fullRanges.push_back(d); 115 partialRanges.push_back(range(folder, zero, dim(subView, rank), one)); 116 } 117 SmallVector<int64_t, 4> dynSizes(fullRanges.size(), -1); 118 auto *buffer = 119 allocBuffer(viewType.getElementType(), allocSize, dynamicBuffers); 120 auto fullLocalView = view( 121 MemRefType::get(dynSizes, viewType.getElementType()), buffer, fullRanges); 122 auto partialLocalView = slice(fullLocalView, partialRanges); 123 return PromotionInfo{buffer, fullLocalView, partialLocalView}; 124 } 125 126 SmallVector<PromotionInfo, 8> 127 mlir::linalg::promoteSubViews(OpBuilder &b, Location loc, 128 ArrayRef<Value *> subViews, bool dynamicBuffers, 129 OperationFolder *folder) { 130 if (subViews.empty()) 131 return {}; 132 133 ScopedContext scope(b, loc); 134 SmallVector<PromotionInfo, 8> res; 135 res.reserve(subViews.size()); 136 DenseMap<Value *, PromotionInfo> promotionInfoMap; 137 for (auto *v : subViews) { 138 SubViewOp subView = cast<SubViewOp>(v->getDefiningOp()); 139 auto viewType = subView.getViewType(); 140 // TODO(ntv): support more cases than just float. 141 if (!viewType.getElementType().isa<FloatType>()) 142 continue; 143 auto promotionInfo = 144 promoteFullTileBuffer(b, loc, subView, dynamicBuffers, folder); 145 promotionInfoMap.insert(std::make_pair(subView.getResult(), promotionInfo)); 146 res.push_back(promotionInfo); 147 } 148 149 for (auto *v : subViews) { 150 SubViewOp subView = cast<SubViewOp>(v->getDefiningOp()); 151 auto info = promotionInfoMap.find(v); 152 if (info == promotionInfoMap.end()) 153 continue; 154 // TODO(ntv): value to fill with should be related to the operation. 155 // For now, just use APFloat(0.0f). 156 auto t = subView.getViewType().getElementType().cast<FloatType>(); 157 Value *fillVal = constant_float(folder, APFloat(0.0f), t); 158 // TODO(ntv): fill is only necessary if `promotionInfo` has a full local 159 // view that is different from the partial local view and we are on the 160 // boundary. 161 fill(info->second.fullLocalView, fillVal); 162 } 163 164 for (auto *v : subViews) { 165 auto info = promotionInfoMap.find(v); 166 if (info == promotionInfoMap.end()) 167 continue; 168 copy(cast<SubViewOp>(v->getDefiningOp()), info->second.partialLocalView); 169 } 170 return res; 171 } 172 173 static void promoteSubViewOperands(LinalgOp op, SetVector<Value *> subViews, 174 bool dynamicBuffers, 175 OperationFolder *folder) { 176 // 1. Promote the specified views and use them in the new op. 177 OpBuilder b(op); 178 ScopedContext scope(b, op.getLoc()); 179 auto promotedBufferAndViews = promoteSubViews( 180 b, op.getLoc(), subViews.getArrayRef(), dynamicBuffers, folder); 181 SmallVector<Value *, 8> opViews; 182 opViews.reserve(op.getNumInputsAndOutputs()); 183 SmallVector<std::pair<Value *, Value *>, 8> writebackViews; 184 writebackViews.reserve(subViews.size()); 185 unsigned promotedIdx = 0; 186 for (auto *view : op.getInputsAndOutputs()) { 187 if (subViews.count(view) != 0) { 188 opViews.push_back(promotedBufferAndViews[promotedIdx].fullLocalView); 189 writebackViews.emplace_back(std::make_pair( 190 view, promotedBufferAndViews[promotedIdx].partialLocalView)); 191 promotedIdx++; 192 } else { 193 opViews.push_back(view); 194 } 195 } 196 197 // 2. Append all other operands as they appear, this enforces that such 198 // operands are not views. This is to support cases such as FillOp taking 199 // extra scalars etc. 200 auto operands = getAssumedNonViewOperands(op); 201 opViews.append(operands.begin(), operands.end()); 202 op.clone(b, op.getLoc(), opViews); 203 204 // 3. Emit write-back for the promoted output views: copy the partial view. 205 for (auto viewAndPartialLocalView : writebackViews) { 206 // Note: use the old op to determine whether the operand view is an output. 207 bool isOutput = 208 op.getIndexOfOutput(viewAndPartialLocalView.first).hasValue(); 209 if (isOutput) 210 copy(viewAndPartialLocalView.second, viewAndPartialLocalView.first); 211 } 212 213 // 4. Dealloc local buffers. 214 for (const auto &pi : promotedBufferAndViews) 215 dealloc(pi.buffer); 216 } 217 218 static void promoteSubViews(FuncOp f, bool dynamicBuffers) { 219 SmallVector<LinalgOp, 8> toErase; 220 OperationFolder folder(f.getContext()); 221 f.walk([dynamicBuffers, &folder, &toErase](LinalgOp op) { 222 // TODO(ntv) some heuristic here to decide what to promote. Atm it is all or 223 // nothing. 224 SetVector<Value *> subViews; 225 for (auto it : op.getInputsAndOutputs()) 226 if (auto sv = dyn_cast_or_null<SubViewOp>(it->getDefiningOp())) 227 subViews.insert(sv); 228 if (!subViews.empty()) { 229 promoteSubViewOperands(op, subViews, dynamicBuffers, &folder); 230 toErase.push_back(op); 231 } 232 }); 233 for (auto op : toErase) 234 op.erase(); 235 } 236 237 namespace { 238 struct LinalgPromotionPass : public FunctionPass<LinalgPromotionPass> { 239 LinalgPromotionPass() = default; 240 LinalgPromotionPass(bool dynamicBuffers) : dynamicBuffers(dynamicBuffers) {} 241 242 void runOnFunction() override { 243 promoteSubViews(getFunction(), dynamicBuffers); 244 } 245 246 bool dynamicBuffers; 247 }; 248 } // namespace 249 250 std::unique_ptr<OpPassBase<FuncOp>> 251 mlir::linalg::createLinalgPromotionPass(bool dynamicBuffers) { 252 return std::make_unique<LinalgPromotionPass>(dynamicBuffers); 253 } 254 255 static PassRegistration<LinalgPromotionPass> 256 pass("linalg-promote-subviews", "promote subview ops to local buffers", [] { 257 return std::make_unique<LinalgPromotionPass>(clPromoteDynamic); 258 }); 259