1 //===- Bufferize.cpp - Bufferization utilities ----------------------------===// 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 "PassDetail.h" 10 11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" 12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h" 13 #include "mlir/Dialect/Bufferization/Transforms/Bufferize.h" 14 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h" 15 #include "mlir/Dialect/Bufferization/Transforms/OneShotModuleBufferize.h" 16 #include "mlir/Dialect/Bufferization/Transforms/Passes.h" 17 #include "mlir/Dialect/Func/IR/FuncOps.h" 18 #include "mlir/Dialect/MemRef/IR/MemRef.h" 19 #include "mlir/IR/Operation.h" 20 #include "mlir/Pass/PassManager.h" 21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 22 #include "mlir/Transforms/Passes.h" 23 24 using namespace mlir; 25 using namespace mlir::bufferization; 26 27 //===----------------------------------------------------------------------===// 28 // BufferizeTypeConverter 29 //===----------------------------------------------------------------------===// 30 31 static Value materializeToTensor(OpBuilder &builder, TensorType type, 32 ValueRange inputs, Location loc) { 33 assert(inputs.size() == 1); 34 assert(inputs[0].getType().isa<BaseMemRefType>()); 35 return builder.create<bufferization::ToTensorOp>(loc, type, inputs[0]); 36 } 37 38 /// Registers conversions into BufferizeTypeConverter 39 BufferizeTypeConverter::BufferizeTypeConverter() { 40 // Keep all types unchanged. 41 addConversion([](Type type) { return type; }); 42 // Convert RankedTensorType to MemRefType. 43 addConversion([](RankedTensorType type) -> Type { 44 return MemRefType::get(type.getShape(), type.getElementType()); 45 }); 46 // Convert UnrankedTensorType to UnrankedMemRefType. 47 addConversion([](UnrankedTensorType type) -> Type { 48 return UnrankedMemRefType::get(type.getElementType(), 0); 49 }); 50 addArgumentMaterialization(materializeToTensor); 51 addSourceMaterialization(materializeToTensor); 52 addTargetMaterialization([](OpBuilder &builder, BaseMemRefType type, 53 ValueRange inputs, Location loc) -> Value { 54 assert(inputs.size() == 1 && "expected exactly one input"); 55 56 if (auto inputType = inputs[0].getType().dyn_cast<MemRefType>()) { 57 // MemRef to MemRef cast. 58 assert(inputType != type && "expected different types"); 59 // Unranked to ranked and ranked to unranked casts must be explicit. 60 auto rankedDestType = type.dyn_cast<MemRefType>(); 61 if (!rankedDestType) 62 return nullptr; 63 FailureOr<Value> replacement = 64 castOrReallocMemRefValue(builder, inputs[0], rankedDestType); 65 if (failed(replacement)) 66 return nullptr; 67 return *replacement; 68 } 69 70 if (inputs[0].getType().isa<TensorType>()) { 71 // Tensor to MemRef cast. 72 return builder.create<bufferization::ToMemrefOp>(loc, type, inputs[0]); 73 } 74 75 llvm_unreachable("only tensor/memref input types supported"); 76 }); 77 } 78 79 void mlir::bufferization::populateBufferizeMaterializationLegality( 80 ConversionTarget &target) { 81 target.addLegalOp<bufferization::ToTensorOp, bufferization::ToMemrefOp>(); 82 } 83 84 namespace { 85 // In a finalizing bufferize conversion, we know that all tensors have been 86 // converted to memrefs, thus, this op becomes an identity. 87 class BufferizeToTensorOp 88 : public OpConversionPattern<bufferization::ToTensorOp> { 89 public: 90 using OpConversionPattern::OpConversionPattern; 91 LogicalResult 92 matchAndRewrite(bufferization::ToTensorOp op, OpAdaptor adaptor, 93 ConversionPatternRewriter &rewriter) const override { 94 rewriter.replaceOp(op, adaptor.memref()); 95 return success(); 96 } 97 }; 98 } // namespace 99 100 namespace { 101 // In a finalizing bufferize conversion, we know that all tensors have been 102 // converted to memrefs, thus, this op becomes an identity. 103 class BufferizeToMemrefOp 104 : public OpConversionPattern<bufferization::ToMemrefOp> { 105 public: 106 using OpConversionPattern::OpConversionPattern; 107 LogicalResult 108 matchAndRewrite(bufferization::ToMemrefOp op, OpAdaptor adaptor, 109 ConversionPatternRewriter &rewriter) const override { 110 rewriter.replaceOp(op, adaptor.tensor()); 111 return success(); 112 } 113 }; 114 } // namespace 115 116 void mlir::bufferization::populateEliminateBufferizeMaterializationsPatterns( 117 BufferizeTypeConverter &typeConverter, RewritePatternSet &patterns) { 118 patterns.add<BufferizeToTensorOp, BufferizeToMemrefOp>(typeConverter, 119 patterns.getContext()); 120 } 121 122 namespace { 123 struct FinalizingBufferizePass 124 : public FinalizingBufferizeBase<FinalizingBufferizePass> { 125 using FinalizingBufferizeBase< 126 FinalizingBufferizePass>::FinalizingBufferizeBase; 127 128 void runOnOperation() override { 129 auto func = getOperation(); 130 auto *context = &getContext(); 131 132 BufferizeTypeConverter typeConverter; 133 RewritePatternSet patterns(context); 134 ConversionTarget target(*context); 135 136 populateEliminateBufferizeMaterializationsPatterns(typeConverter, patterns); 137 138 // If all result types are legal, and all block arguments are legal (ensured 139 // by func conversion above), then all types in the program are legal. 140 // 141 // We also check that the operand types are legal to avoid creating invalid 142 // IR. For example, this prevents 143 // populateEliminateBufferizeMaterializationsPatterns from updating the 144 // types of the operands to a return op without updating the enclosing 145 // function. 146 target.markUnknownOpDynamicallyLegal( 147 [&](Operation *op) { return typeConverter.isLegal(op); }); 148 149 if (failed(applyFullConversion(func, target, std::move(patterns)))) 150 signalPassFailure(); 151 } 152 }; 153 154 struct OneShotBufferizePass 155 : public OneShotBufferizeBase<OneShotBufferizePass> { 156 OneShotBufferizePass() : OneShotBufferizeBase<OneShotBufferizePass>() {} 157 158 explicit OneShotBufferizePass(const OneShotBufferizationOptions &options) 159 : options(options) {} 160 161 void getDependentDialects(DialectRegistry ®istry) const override { 162 registry 163 .insert<bufferization::BufferizationDialect, memref::MemRefDialect>(); 164 registerAllocationOpInterfaceExternalModels(registry); 165 } 166 167 void runOnOperation() override { 168 OneShotBufferizationOptions opt; 169 if (!options) { 170 // Make new bufferization options if none were provided when creating the 171 // pass. 172 opt.dropEquivalentFuncResults = dropEquivalentFuncResults; 173 opt.allowReturnAllocs = allowReturnAllocs; 174 opt.allowUnknownOps = allowUnknownOps; 175 opt.alwaysAliasingWithDest = alwaysAliasingWithDest; 176 opt.analysisFuzzerSeed = analysisFuzzerSeed; 177 opt.createDeallocs = createDeallocs; 178 opt.fullyDynamicLayoutMaps = fullyDynamicLayoutMaps; 179 opt.printConflicts = printConflicts; 180 opt.testAnalysisOnly = testAnalysisOnly; 181 opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries; 182 opt.promoteBufferResultsToOutParams = promoteBufferResultsToOutParams; 183 184 BufferizationOptions::OpFilterEntry::FilterFn filterFn = 185 [&](Operation *op) { 186 // Filter may be specified via options. 187 if (this->dialectFilter.hasValue()) 188 return llvm::find(this->dialectFilter, 189 op->getDialect()->getNamespace()) != 190 this->dialectFilter.end(); 191 // No filter specified: All other ops are allowed. 192 return true; 193 }; 194 opt.allowOperationInFilter(filterFn); 195 } else { 196 opt = *options; 197 } 198 199 ModuleOp moduleOp = getOperation(); 200 if (opt.bufferizeFunctionBoundaries) { 201 if (failed(runOneShotModuleBufferize(moduleOp, opt))) { 202 signalPassFailure(); 203 return; 204 } 205 } else { 206 if (failed(runOneShotBufferize(moduleOp, opt))) { 207 signalPassFailure(); 208 return; 209 } 210 } 211 212 if (opt.testAnalysisOnly) 213 return; 214 215 OpPassManager cleanupPipeline("builtin.module"); 216 cleanupPipeline.addPass(createCanonicalizerPass()); 217 cleanupPipeline.addPass(createCSEPass()); 218 cleanupPipeline.addPass(createLoopInvariantCodeMotionPass()); 219 (void)runPipeline(cleanupPipeline, moduleOp); 220 } 221 222 private: 223 llvm::Optional<OneShotBufferizationOptions> options; 224 }; 225 } // namespace 226 227 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() { 228 return std::make_unique<OneShotBufferizePass>(); 229 } 230 231 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass( 232 const OneShotBufferizationOptions &options) { 233 return std::make_unique<OneShotBufferizePass>(options); 234 } 235 236 std::unique_ptr<OperationPass<func::FuncOp>> 237 mlir::bufferization::createFinalizingBufferizePass() { 238 return std::make_unique<FinalizingBufferizePass>(); 239 } 240 241 //===----------------------------------------------------------------------===// 242 // BufferizableOpInterface-based Bufferization 243 //===----------------------------------------------------------------------===// 244 245 static bool isaTensor(Type t) { return t.isa<TensorType>(); } 246 247 /// Return true if the given op has a tensor result or a tensor operand. 248 static bool hasTensorSemantics(Operation *op) { 249 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) { 250 bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor); 251 bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor); 252 return hasTensorArg || hasTensorResult; 253 } 254 255 bool hasTensorResult = any_of(op->getResultTypes(), isaTensor); 256 bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor); 257 return hasTensorResult || hasTensorOperand; 258 } 259 260 LogicalResult 261 bufferization::finalizeBuffers(Operation *op, 262 const BufferizationOptions &options) { 263 // Hoist buffers. 264 if (failed(hoistBufferAllocations(op, options))) 265 return failure(); 266 267 // Create allocation ops for "leaking buffers", i.e., buffer allocations that 268 // escape block boundaries. If there are no leaking allocs, `hasLeakingAllocs` 269 // is set to `false`. 270 bool hasLeakingAllocs = false; 271 if (failed(createAllocDeallocOps(op, options, /*onlyLeakingAllocs=*/true, 272 &hasLeakingAllocs))) 273 return failure(); 274 275 if (hasLeakingAllocs) { 276 // Promote returned buffers to "out" parameters. 277 // TODO: Pass options to support custom dealloc ops. 278 if (options.promoteBufferResultsToOutParams && isa<ModuleOp>(op) && 279 failed(promoteBufferResultsToOutParams(cast<ModuleOp>(op)))) 280 return failure(); 281 282 // Create deallocation ops for all "leaking buffers" and all buffer 283 // allocations that were added during the above promotion process. 284 // TODO: Pass options to support custom dealloc ops. 285 if (options.createDeallocs && failed(deallocateBuffers(op))) 286 return failure(); 287 } 288 289 // Deallocate all remaining buffers at the end of their parent blocks. 290 if (failed(createAllocDeallocOps(op, options))) 291 return failure(); 292 293 return success(); 294 } 295 296 LogicalResult bufferization::bufferizeOp(Operation *op, 297 const AnalysisState &analysisState) { 298 // Catch incorrect API usage. 299 assert((analysisState.hasDialectState( 300 func::FuncDialect::getDialectNamespace()) || 301 !analysisState.getOptions().bufferizeFunctionBoundaries) && 302 "must use ModuleBufferize to bufferize function boundaries"); 303 304 BufferizationState bufferizationState(analysisState); 305 if (failed(bufferizeOp(op, bufferizationState))) 306 return failure(); 307 if (failed(finalizeBuffers(op, analysisState.getOptions()))) 308 return failure(); 309 return success(); 310 } 311 312 namespace { 313 /// A rewriter that keeps track of extra information during bufferization. 314 class BufferizationRewriter : public IRRewriter { 315 public: 316 BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps, 317 DenseSet<Operation *> &toMemrefOps, 318 const BufferizationOptions &options) 319 : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps), 320 options(options) {} 321 322 protected: 323 void notifyOperationRemoved(Operation *op) override { 324 IRRewriter::notifyOperationRemoved(op); 325 erasedOps.insert(op); 326 // Erase if present. 327 toMemrefOps.erase(op); 328 } 329 330 void notifyOperationInserted(Operation *op) override { 331 IRRewriter::notifyOperationInserted(op); 332 333 // Keep track of to_memref ops. 334 if (isa<ToMemrefOp>(op)) { 335 toMemrefOps.insert(op); 336 return; 337 } 338 339 // Skip to_tensor ops. 340 if (isa<ToTensorOp>(op)) 341 return; 342 343 // Adding new bufferizable ops is not allowed during bufferization. Such ops 344 // would not be analyzed and can lead to surprising behavior. 345 assert((!hasTensorSemantics(op) || !options.isOpAllowed(op)) && 346 "creating new tensor ops is not allowed during bufferization"); 347 } 348 349 private: 350 /// A set of all erased ops. 351 DenseSet<Operation *> &erasedOps; 352 353 /// A set of all to_memref ops. 354 DenseSet<Operation *> &toMemrefOps; 355 356 /// The bufferization options. 357 const BufferizationOptions &options; 358 }; 359 } // namespace 360 361 LogicalResult 362 bufferization::bufferizeOp(Operation *op, 363 BufferizationState &bufferizationState) { 364 const auto &options = bufferizationState.getOptions(); 365 366 // Keep track of to_memref ops. 367 DenseSet<Operation *> toMemrefOps; 368 op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); }); 369 370 // Gather all bufferizable ops in top-to-bottom order. 371 // 372 // We should ideally know the exact memref type of all operands when 373 // bufferizing an op. (This is the case when bufferizing top-to-bottom.) 374 // Otherwise, we have to use a memref type with a fully dynamic layout map, 375 // which has to canonicalize away. This is less efficient. 376 // 377 // If "fullyDynamicLayoutMaps = false", we would have to insert buffer copies 378 // to fold ("finalize") to_memref(to_tensor(x)) ops with non-cast-compatible 379 // layout maps when doing a traversal other than top-to-bottom. These would 380 // not easily fold away. 381 SmallVector<Operation *> worklist; 382 op->walk<WalkOrder::PreOrder>([&](Operation *op) { 383 if (hasTensorSemantics(op)) 384 worklist.push_back(op); 385 }); 386 387 // Keep track of all erased ops. 388 DenseSet<Operation *> erasedOps; 389 390 // Bufferize all ops. 391 BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps, 392 bufferizationState.getOptions()); 393 for (unsigned i = 0; i < worklist.size(); ++i) { 394 Operation *op = worklist[i]; 395 // Skip ops that were erased. 396 if (erasedOps.contains(op)) 397 continue; 398 // Skip ops that are not bufferizable or not allowed. 399 auto bufferizableOp = options.dynCastBufferizableOp(op); 400 if (!bufferizableOp) 401 continue; 402 // Skip ops that no longer have tensor semantics. 403 if (!hasTensorSemantics(op)) 404 continue; 405 // Bufferize the op. 406 rewriter.setInsertionPoint(op); 407 (void)bufferizableOp.bufferize(rewriter, bufferizationState); 408 } 409 410 // Fold all to_memref(to_tensor(x)) pairs. 411 for (Operation *op : toMemrefOps) { 412 rewriter.setInsertionPoint(op); 413 (void)bufferization::foldToMemrefToTensorPair(rewriter, 414 cast<ToMemrefOp>(op)); 415 } 416 417 /// Check the result of bufferization. Return an error if an op was not 418 /// bufferized, unless partial bufferization is allowed. 419 if (bufferizationState.getOptions().allowUnknownOps) 420 return success(); 421 422 for (Operation *op : worklist) { 423 // Skip ops that are entirely gone. 424 if (erasedOps.contains(op)) 425 continue; 426 // Ops that no longer have tensor semantics (because they were updated 427 // in-place) are allowed. 428 if (!hasTensorSemantics(op)) 429 continue; 430 // Continue ops that are not allowed. 431 if (!options.isOpAllowed(op)) 432 continue; 433 // Ops without any uses and no side effects will fold away. 434 if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op)) 435 continue; 436 return op->emitError("op was not bufferized"); 437 } 438 439 return success(); 440 } 441 442 namespace { 443 /// This a "no analysis, always copy" AnalysisState. In the absence of an 444 /// analysis, a buffer must be copied each time it is written to. Therefore, all 445 /// OpOperands that bufferize to a memory write must bufferize out-of-place. 446 class AlwaysCopyAnalysisState : public AnalysisState { 447 public: 448 AlwaysCopyAnalysisState(const BufferizationOptions &options) 449 : AnalysisState(options) {} 450 451 AlwaysCopyAnalysisState(const AlwaysCopyAnalysisState &) = delete; 452 453 virtual ~AlwaysCopyAnalysisState() = default; 454 455 /// Return `true` if the given OpResult has been decided to bufferize inplace. 456 bool isInPlace(OpOperand &opOperand) const override { 457 // OpOperands that bufferize to a memory write are out-of-place, i.e., an 458 // alloc and copy is inserted. 459 return !bufferizesToMemoryWrite(opOperand); 460 } 461 462 /// Return true if `v1` and `v2` bufferize to equivalent buffers. 463 bool areEquivalentBufferizedValues(Value v1, Value v2) const override { 464 // There is no analysis, so we do not know if the values are equivalent. The 465 // conservative answer is "false". 466 return false; 467 } 468 }; 469 } // namespace 470 471 LogicalResult bufferization::bufferizeOp(Operation *op, 472 const BufferizationOptions &options) { 473 AlwaysCopyAnalysisState state(options); 474 return bufferizeOp(op, state); 475 } 476 477 BufferizationOptions bufferization::getPartialBufferizationOptions() { 478 BufferizationOptions options; 479 options.allowUnknownOps = true; 480 options.createDeallocs = false; 481 options.fullyDynamicLayoutMaps = false; 482 return options; 483 } 484