1 //===- Bufferize.cpp - Bufferization of linalg ops ------------------===// 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 #include "mlir/Transforms/Bufferize.h" 10 #include "PassDetail.h" 11 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 12 #include "mlir/Dialect/Linalg/Passes.h" 13 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 14 #include "mlir/Dialect/Linalg/Utils/Utils.h" 15 #include "mlir/Dialect/Math/IR/Math.h" 16 #include "mlir/Dialect/StandardOps/Transforms/Passes.h" 17 #include "mlir/Dialect/StandardOps/Utils/Utils.h" 18 #include "mlir/Dialect/Vector/VectorOps.h" 19 #include "mlir/IR/BuiltinDialect.h" 20 #include "mlir/IR/Operation.h" 21 #include "mlir/Pass/Pass.h" 22 23 using namespace ::mlir; 24 using namespace ::mlir::linalg; 25 26 static Value cloneMemref(Location loc, Value memref, OpBuilder &b) { 27 auto memrefType = memref.getType().cast<MemRefType>(); 28 auto alloc = b.create<memref::AllocOp>(loc, memrefType, 29 getDynOperands(loc, memref, b)); 30 b.create<linalg::CopyOp>(loc, memref, alloc); 31 return alloc; 32 } 33 34 static LogicalResult 35 allocateBuffersForResults(Location loc, LinalgOp linalgOp, ValueRange outputs, 36 SmallVectorImpl<Value> &resultBuffers, OpBuilder &b) { 37 // Lazily compute loopRanges. 38 SmallVector<Range, 4> loopRanges; 39 40 // Allocate a buffer for every tensor result. 41 assert(linalgOp.getNumOutputs() == linalgOp->getNumResults()); 42 for (auto en : llvm::enumerate(linalgOp->getResultTypes())) { 43 size_t resultIndex = en.index(); 44 Type resultType = en.value(); 45 46 auto tensorType = resultType.dyn_cast<RankedTensorType>(); 47 if (tensorType == nullptr) { 48 linalgOp.emitOpError() 49 << "tensor to buffer conversion expects ranked tensor results"; 50 return failure(); 51 } 52 auto tensorShape = tensorType.getShape(); 53 auto memrefType = MemRefType::get(tensorShape, tensorType.getElementType()); 54 Value resultTensor = outputs[resultIndex]; 55 56 // Clone output buffers whose value is actually used. 57 if (linalgOp.payloadUsesValueFromOutputOperandIndex(resultIndex)) { 58 resultBuffers.push_back(cloneMemref(loc, resultTensor, b)); 59 continue; 60 } 61 62 // Allocate buffers for statically-shaped results. 63 if (memrefType.hasStaticShape()) { 64 resultBuffers.push_back(b.create<memref::AllocOp>(loc, memrefType)); 65 continue; 66 } 67 68 resultBuffers.push_back(b.create<memref::AllocOp>( 69 loc, memrefType, getDynOperands(loc, resultTensor, b))); 70 } 71 return success(); 72 } 73 74 /// Specialization for `linalg::GenericOp` and `linalg::IndexedGenericOp`. 75 /// A pattern to convert Generic Linalg operations which work on tensors to 76 /// use buffers. BufferPlacement pass should be later used to move 77 /// Alloc operations to the correct positions and insert the missing Dealloc 78 /// operations in the correct places. 79 template <typename GenericOpTy> 80 static void 81 finalizeBufferAllocationForGenericOp(ConversionPatternRewriter &rewriter, 82 GenericOpTy genericOp, ValueRange inputs, 83 ValueRange outputs) { 84 // Generate a new linalg operation that works on buffers. 85 auto newGenericOp = rewriter.create<GenericOpTy>( 86 genericOp.getLoc(), 87 /*resultTensorTypes=*/llvm::None, 88 /*inputs=*/inputs, 89 /*outputs=*/outputs, genericOp.indexing_maps(), 90 genericOp.iterator_types(), genericOp.docAttr(), 91 genericOp.library_callAttr(), genericOp.sparseAttr()); 92 93 // Create a new block in the region of the new Generic Op. 94 Block *oldBlock = genericOp.getBody(); 95 Region &newRegion = newGenericOp.region(); 96 Block *newBlock = rewriter.createBlock(&newRegion, newRegion.begin(), 97 oldBlock->getArgumentTypes()); 98 99 // Clone the body of the old block to the new block. 100 BlockAndValueMapping mapping; 101 mapping.map(oldBlock->getArguments(), newBlock->getArguments()); 102 103 OpBuilder::InsertionGuard guard(rewriter); 104 rewriter.setInsertionPointToEnd(newBlock); 105 for (auto &op : oldBlock->getOperations()) { 106 Operation *clonedOp = rewriter.clone(op, mapping); 107 mapping.map(op.getResults(), clonedOp->getResults()); 108 } 109 110 // Replace the results of the old op with the new output buffers. 111 rewriter.replaceOp(genericOp, outputs); 112 } 113 114 /// Specialization for all other `linalg::LinalgOp`. 115 static void finalizeBufferAllocation(ConversionPatternRewriter &rewriter, 116 linalg::LinalgOp linalgOp, 117 ValueRange inputs, ValueRange outputs) { 118 assert(!isa<linalg::GenericOp>(linalgOp.getOperation())); 119 assert(!isa<linalg::IndexedGenericOp>(linalgOp.getOperation())); 120 SmallVector<Value, 8> newOperands = inputs; 121 newOperands.append(outputs.begin(), outputs.end()); 122 auto otherOperands = linalgOp.getAssumedNonShapedOperands(); 123 newOperands.append(otherOperands.begin(), otherOperands.end()); 124 linalgOp.clone(rewriter, linalgOp.getLoc(), 125 /*resultTypes=*/ArrayRef<Type>{}, newOperands); 126 // Replace the results of the old op with the new output buffers. 127 rewriter.replaceOp(linalgOp, outputs); 128 } 129 130 //===----------------------------------------------------------------------===// 131 // Bufferization patterns. 132 //===----------------------------------------------------------------------===// 133 134 namespace { 135 136 /// Conversion pattern that replaces `linalg.init_tensor` with allocation. 137 class BufferizeInitTensorOp : public OpConversionPattern<InitTensorOp> { 138 public: 139 using OpConversionPattern<InitTensorOp>::OpConversionPattern; 140 141 LogicalResult 142 matchAndRewrite(InitTensorOp op, ArrayRef<Value> operands, 143 ConversionPatternRewriter &rewriter) const final { 144 linalg::InitTensorOpAdaptor adaptor(operands, op->getAttrDictionary()); 145 rewriter.replaceOpWithNewOp<memref::AllocOp>( 146 op, getTypeConverter()->convertType(op.getType()).cast<MemRefType>(), 147 adaptor.sizes()); 148 return success(); 149 } 150 }; 151 152 /// Conversion pattern that replaces `linalg.tensor_reshape` with 153 /// `linalg.reshape`. 154 class BufferizeTensorReshapeOp : public OpConversionPattern<TensorReshapeOp> { 155 public: 156 using OpConversionPattern<TensorReshapeOp>::OpConversionPattern; 157 158 LogicalResult 159 matchAndRewrite(TensorReshapeOp op, ArrayRef<Value> operands, 160 ConversionPatternRewriter &rewriter) const final { 161 linalg::TensorReshapeOpAdaptor adaptor(operands, op->getAttrDictionary()); 162 rewriter.replaceOpWithNewOp<linalg::ReshapeOp>( 163 op, getTypeConverter()->convertType(op.getType()).cast<MemRefType>(), 164 adaptor.src(), adaptor.reassociation()); 165 return success(); 166 } 167 }; 168 169 /// Conversion pattern that bufferizes `linalg.fill` operation. 170 class BufferizeFillOp : public OpConversionPattern<FillOp> { 171 public: 172 using OpConversionPattern<FillOp>::OpConversionPattern; 173 174 LogicalResult 175 matchAndRewrite(FillOp op, ArrayRef<Value> operands, 176 ConversionPatternRewriter &rewriter) const final { 177 linalg::FillOpAdaptor adaptor(operands, op->getAttrDictionary()); 178 if (!op.output().getType().isa<TensorType>()) 179 return rewriter.notifyMatchFailure(op, 180 "operand must be of a tensor type"); 181 182 rewriter.create<FillOp>(op.getLoc(), adaptor.output(), adaptor.value()); 183 rewriter.replaceOp(op, adaptor.output()); 184 185 return success(); 186 } 187 }; 188 189 /// Generic conversion pattern that matches any LinalgOp. This avoids template 190 /// instantiating one pattern for each LinalgOp. 191 class BufferizeAnyLinalgOp : public OpInterfaceConversionPattern<LinalgOp> { 192 public: 193 using OpInterfaceConversionPattern<LinalgOp>::OpInterfaceConversionPattern; 194 195 LogicalResult 196 matchAndRewrite(LinalgOp op, ArrayRef<Value> operands, 197 ConversionPatternRewriter &rewriter) const final { 198 // GenericOpAdaptor below expects an `operand_segment_sizes` attribute. 199 if (!op->hasAttr("operand_segment_sizes")) 200 return failure(); 201 202 // We abuse the GenericOpAdaptor here. 203 // TODO: Manually create an Adaptor that captures inputs and outputs for all 204 // linalg::LinalgOp interface ops. 205 linalg::GenericOpAdaptor adaptor(operands, op->getAttrDictionary()); 206 207 Location loc = op.getLoc(); 208 SmallVector<Value, 2> newOutputBuffers; 209 210 if (failed(allocateBuffersForResults(loc, op, adaptor.outputs(), 211 newOutputBuffers, rewriter))) { 212 return op.emitOpError() 213 << "Failed to allocate buffers for tensor results."; 214 } 215 216 // Delegate to the linalg generic pattern. 217 if (auto genericOp = dyn_cast<linalg::GenericOp>(*op)) { 218 finalizeBufferAllocationForGenericOp<GenericOp>( 219 rewriter, genericOp, adaptor.inputs(), newOutputBuffers); 220 return success(); 221 } 222 223 // Delegate to the linalg indexed generic pattern. 224 if (auto genericOp = dyn_cast<linalg::IndexedGenericOp>(*op)) { 225 finalizeBufferAllocationForGenericOp<IndexedGenericOp>( 226 rewriter, genericOp, adaptor.inputs(), newOutputBuffers); 227 return success(); 228 } 229 230 finalizeBufferAllocation(rewriter, op, adaptor.inputs(), newOutputBuffers); 231 return success(); 232 } 233 }; 234 235 /// Convert `subtensor %t [offsets][sizes][strides] -> %st` to an alloc + copy 236 /// pattern. 237 /// ``` 238 /// %a = alloc(sizes) 239 /// %sv = subview %source [offsets][sizes][strides] 240 /// linalg_copy(%sv, %a) 241 /// ``` 242 /// 243 /// This pattern is arguable a std pattern once linalg::CopyOp becomes 244 /// std::CopyOp. 245 class SubTensorOpConverter : public OpConversionPattern<SubTensorOp> { 246 public: 247 using OpConversionPattern<SubTensorOp>::OpConversionPattern; 248 249 LogicalResult 250 matchAndRewrite(SubTensorOp op, ArrayRef<Value> operands, 251 ConversionPatternRewriter &rewriter) const final { 252 SubTensorOpAdaptor adaptor(operands, op->getAttrDictionary()); 253 Value sourceMemref = adaptor.source(); 254 assert(sourceMemref.getType().isa<MemRefType>()); 255 256 MemRefType subviewMemRefType = 257 getTypeConverter()->convertType(op.getType()).cast<MemRefType>(); 258 // op.sizes() capture exactly the dynamic alloc operands matching the 259 // subviewMemRefType thanks to subview/subtensor canonicalization and 260 // verification. 261 Value alloc = rewriter.create<memref::AllocOp>( 262 op.getLoc(), subviewMemRefType, op.sizes()); 263 Value subView = rewriter.create<memref::SubViewOp>( 264 op.getLoc(), sourceMemref, op.getMixedOffsets(), op.getMixedSizes(), 265 op.getMixedStrides()); 266 rewriter.create<linalg::CopyOp>(op.getLoc(), subView, alloc); 267 rewriter.replaceOp(op, alloc); 268 return success(); 269 } 270 }; 271 272 /// Convert `subtensor_insert %source into %dest [offsets][sizes][strides] -> 273 /// %t` to an buffer_cast + subview + copy + tensor_load pattern. 274 /// buffer_cast and tensor_load are inserted automatically by the 275 /// conversion infra: 276 /// ``` 277 /// %sv = subview %dest [offsets][sizes][strides] 278 /// linalg_copy(%source, %sv) 279 /// // replace with %dest 280 /// ``` 281 /// 282 /// This pattern is arguable a std pattern once linalg::CopyOp becomes 283 /// std::CopyOp. 284 class SubTensorInsertOpConverter 285 : public OpConversionPattern<SubTensorInsertOp> { 286 public: 287 using OpConversionPattern<SubTensorInsertOp>::OpConversionPattern; 288 289 LogicalResult 290 matchAndRewrite(SubTensorInsertOp op, ArrayRef<Value> operands, 291 ConversionPatternRewriter &rewriter) const final { 292 SubTensorInsertOpAdaptor adaptor(operands, op->getAttrDictionary()); 293 Value sourceMemRef = adaptor.source(); 294 assert(sourceMemRef.getType().isa<MemRefType>()); 295 296 // For now, be conservative and copy the converted input memref. 297 // In general, the converted input memref here could be aliased or could 298 // point into constant memory, so mutating it would lead to miscompilations. 299 Value destMemRef = cloneMemref(op.getLoc(), adaptor.dest(), rewriter); 300 assert(destMemRef.getType().isa<MemRefType>()); 301 302 // Take a subview to copy the small memref. 303 Value subview = rewriter.create<memref::SubViewOp>( 304 op.getLoc(), destMemRef, op.getMixedOffsets(), op.getMixedSizes(), 305 op.getMixedStrides()); 306 // Copy the small memref. 307 rewriter.create<linalg::CopyOp>(op.getLoc(), sourceMemRef, subview); 308 rewriter.replaceOp(op, destMemRef); 309 return success(); 310 } 311 }; 312 } // namespace 313 314 namespace { 315 /// Converts Linalg operations that work on tensor-type operands or results to 316 /// work on buffers. 317 struct LinalgBufferizePass : public LinalgBufferizeBase<LinalgBufferizePass> { 318 void runOnOperation() override { 319 MLIRContext &context = getContext(); 320 ConversionTarget target(context); 321 BufferizeTypeConverter typeConverter; 322 323 // Mark all Standard operations legal. 324 target.addLegalDialect<AffineDialect, math::MathDialect, 325 memref::MemRefDialect, StandardOpsDialect>(); 326 target.addIllegalOp<InitTensorOp, SubTensorOp, SubTensorInsertOp>(); 327 328 // Mark all Linalg operations illegal as long as they work on tensors. 329 auto isLegalOperation = [&](Operation *op) { 330 return typeConverter.isLegal(op); 331 }; 332 target.addDynamicallyLegalDialect<linalg::LinalgDialect>(isLegalOperation); 333 target.addDynamicallyLegalOp<ConstantOp>(isLegalOperation); 334 335 RewritePatternSet patterns(&context); 336 populateLinalgBufferizePatterns(typeConverter, patterns); 337 if (failed(applyPartialConversion(getOperation(), target, 338 std::move(patterns)))) 339 signalPassFailure(); 340 } 341 }; 342 } // end anonymous namespace 343 344 std::unique_ptr<OperationPass<FuncOp>> mlir::createLinalgBufferizePass() { 345 return std::make_unique<LinalgBufferizePass>(); 346 } 347 348 void mlir::linalg::populateLinalgBufferizePatterns( 349 BufferizeTypeConverter &typeConverter, RewritePatternSet &patterns) { 350 // TODO: Drop this once tensor constants work in standard. 351 // clang-format off 352 patterns.add< 353 BufferizeAnyLinalgOp, 354 BufferizeFillOp, 355 BufferizeInitTensorOp, 356 BufferizeTensorReshapeOp, 357 SubTensorOpConverter, 358 SubTensorInsertOpConverter 359 >(typeConverter, patterns.getContext()); 360 // clang-format on 361 } 362