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 static BufferizationOptions::LayoutMapOption 155 parseLayoutMapOption(std::string s) { 156 if (s == "fully-dynamic-layout-map") 157 return BufferizationOptions::LayoutMapOption::FullyDynamicLayoutMap; 158 if (s == "identity-layout-map") 159 return BufferizationOptions::LayoutMapOption::IdentityLayoutMap; 160 if (s == "infer-layout-map") 161 return BufferizationOptions::LayoutMapOption::InferLayoutMap; 162 llvm_unreachable("invalid layout map option"); 163 } 164 165 struct OneShotBufferizePass 166 : public OneShotBufferizeBase<OneShotBufferizePass> { 167 OneShotBufferizePass() : OneShotBufferizeBase<OneShotBufferizePass>() {} 168 169 explicit OneShotBufferizePass(const OneShotBufferizationOptions &options) 170 : options(options) {} 171 172 void getDependentDialects(DialectRegistry ®istry) const override { 173 registry 174 .insert<bufferization::BufferizationDialect, memref::MemRefDialect>(); 175 registerAllocationOpInterfaceExternalModels(registry); 176 } 177 178 void runOnOperation() override { 179 OneShotBufferizationOptions opt; 180 if (!options) { 181 // Make new bufferization options if none were provided when creating the 182 // pass. 183 opt.dropEquivalentFuncResults = dropEquivalentFuncResults; 184 opt.allowReturnAllocs = allowReturnAllocs; 185 opt.allowUnknownOps = allowUnknownOps; 186 opt.alwaysAliasingWithDest = alwaysAliasingWithDest; 187 opt.analysisFuzzerSeed = analysisFuzzerSeed; 188 opt.createDeallocs = createDeallocs; 189 opt.functionBoundaryTypeConversion = 190 parseLayoutMapOption(functionBoundaryTypeConversion); 191 opt.printConflicts = printConflicts; 192 opt.testAnalysisOnly = testAnalysisOnly; 193 opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries; 194 opt.promoteBufferResultsToOutParams = promoteBufferResultsToOutParams; 195 opt.unknownTypeConversion = parseLayoutMapOption(unknownTypeConversion); 196 197 BufferizationOptions::OpFilterEntry::FilterFn filterFn = 198 [&](Operation *op) { 199 // Filter may be specified via options. 200 if (this->dialectFilter.hasValue()) 201 return llvm::find(this->dialectFilter, 202 op->getDialect()->getNamespace()) != 203 this->dialectFilter.end(); 204 // No filter specified: All other ops are allowed. 205 return true; 206 }; 207 opt.allowOperationInFilter(filterFn); 208 } else { 209 opt = *options; 210 } 211 212 ModuleOp moduleOp = getOperation(); 213 if (opt.bufferizeFunctionBoundaries) { 214 if (failed(runOneShotModuleBufferize(moduleOp, opt))) { 215 signalPassFailure(); 216 return; 217 } 218 } else { 219 if (failed(runOneShotBufferize(moduleOp, opt))) { 220 signalPassFailure(); 221 return; 222 } 223 } 224 225 if (opt.testAnalysisOnly) 226 return; 227 228 OpPassManager cleanupPipeline("builtin.module"); 229 cleanupPipeline.addPass(createCanonicalizerPass()); 230 cleanupPipeline.addPass(createCSEPass()); 231 cleanupPipeline.addPass(createLoopInvariantCodeMotionPass()); 232 (void)runPipeline(cleanupPipeline, moduleOp); 233 } 234 235 private: 236 llvm::Optional<OneShotBufferizationOptions> options; 237 }; 238 } // namespace 239 240 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() { 241 return std::make_unique<OneShotBufferizePass>(); 242 } 243 244 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass( 245 const OneShotBufferizationOptions &options) { 246 return std::make_unique<OneShotBufferizePass>(options); 247 } 248 249 std::unique_ptr<OperationPass<func::FuncOp>> 250 mlir::bufferization::createFinalizingBufferizePass() { 251 return std::make_unique<FinalizingBufferizePass>(); 252 } 253 254 //===----------------------------------------------------------------------===// 255 // BufferizableOpInterface-based Bufferization 256 //===----------------------------------------------------------------------===// 257 258 static bool isaTensor(Type t) { return t.isa<TensorType>(); } 259 260 /// Return true if the given op has a tensor result or a tensor operand. 261 static bool hasTensorSemantics(Operation *op) { 262 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) { 263 bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor); 264 bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor); 265 return hasTensorArg || hasTensorResult; 266 } 267 268 bool hasTensorResult = any_of(op->getResultTypes(), isaTensor); 269 bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor); 270 return hasTensorResult || hasTensorOperand; 271 } 272 273 LogicalResult 274 bufferization::finalizeBuffers(Operation *op, 275 const BufferizationOptions &options) { 276 // Hoist buffers. 277 if (failed(hoistBufferAllocations(op, options))) 278 return failure(); 279 280 // Create allocation ops for "leaking buffers", i.e., buffer allocations that 281 // escape block boundaries. If there are no leaking allocs, `hasLeakingAllocs` 282 // is set to `false`. 283 bool hasLeakingAllocs = false; 284 if (failed(createAllocDeallocOps(op, options, /*onlyLeakingAllocs=*/true, 285 &hasLeakingAllocs))) 286 return failure(); 287 288 if (hasLeakingAllocs) { 289 // Promote returned buffers to "out" parameters. 290 // TODO: Pass options to support custom dealloc ops. 291 if (options.promoteBufferResultsToOutParams && isa<ModuleOp>(op) && 292 failed(promoteBufferResultsToOutParams(cast<ModuleOp>(op)))) 293 return failure(); 294 295 // Create deallocation ops for all "leaking buffers" and all buffer 296 // allocations that were added during the above promotion process. 297 // TODO: Pass options to support custom dealloc ops. 298 if (options.createDeallocs && failed(deallocateBuffers(op))) 299 return failure(); 300 } 301 302 // Deallocate all remaining buffers at the end of their parent blocks. 303 if (failed(createAllocDeallocOps(op, options))) 304 return failure(); 305 306 return success(); 307 } 308 309 LogicalResult bufferization::bufferizeOp(Operation *op, 310 const AnalysisState &analysisState) { 311 // Catch incorrect API usage. 312 assert((analysisState.hasDialectState( 313 func::FuncDialect::getDialectNamespace()) || 314 !analysisState.getOptions().bufferizeFunctionBoundaries) && 315 "must use ModuleBufferize to bufferize function boundaries"); 316 317 BufferizationState bufferizationState(analysisState); 318 if (failed(bufferizeOp(op, bufferizationState))) 319 return failure(); 320 if (failed(finalizeBuffers(op, analysisState.getOptions()))) 321 return failure(); 322 return success(); 323 } 324 325 namespace { 326 /// A rewriter that keeps track of extra information during bufferization. 327 class BufferizationRewriter : public IRRewriter { 328 public: 329 BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps, 330 DenseSet<Operation *> &toMemrefOps, 331 const BufferizationOptions &options) 332 : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps), 333 options(options) {} 334 335 protected: 336 void notifyOperationRemoved(Operation *op) override { 337 IRRewriter::notifyOperationRemoved(op); 338 erasedOps.insert(op); 339 // Erase if present. 340 toMemrefOps.erase(op); 341 } 342 343 void notifyOperationInserted(Operation *op) override { 344 IRRewriter::notifyOperationInserted(op); 345 346 // Keep track of to_memref ops. 347 if (isa<ToMemrefOp>(op)) { 348 toMemrefOps.insert(op); 349 return; 350 } 351 352 // Skip to_tensor ops. 353 if (isa<ToTensorOp>(op)) 354 return; 355 356 // Adding new bufferizable ops is not allowed during bufferization. Such ops 357 // would not be analyzed and can lead to surprising behavior. 358 assert((!hasTensorSemantics(op) || !options.isOpAllowed(op)) && 359 "creating new tensor ops is not allowed during bufferization"); 360 } 361 362 private: 363 /// A set of all erased ops. 364 DenseSet<Operation *> &erasedOps; 365 366 /// A set of all to_memref ops. 367 DenseSet<Operation *> &toMemrefOps; 368 369 /// The bufferization options. 370 const BufferizationOptions &options; 371 }; 372 } // namespace 373 374 LogicalResult 375 bufferization::bufferizeOp(Operation *op, 376 BufferizationState &bufferizationState) { 377 const auto &options = bufferizationState.getOptions(); 378 assert(options.unknownTypeConversion != 379 BufferizationOptions::LayoutMapOption::InferLayoutMap && 380 "invalid layout map option"); 381 382 // Keep track of to_memref ops. 383 DenseSet<Operation *> toMemrefOps; 384 op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); }); 385 386 // Gather all bufferizable ops in top-to-bottom order. 387 // 388 // We should ideally know the exact memref type of all operands when 389 // bufferizing an op. (This is the case when bufferizing top-to-bottom.) 390 // Otherwise, we have to use a memref type with a fully dynamic layout map to 391 // avoid copies. We are currently missing patterns for layout maps to 392 // canonicalize away (or canonicalize to more precise layouts). 393 SmallVector<Operation *> worklist; 394 op->walk<WalkOrder::PreOrder>([&](Operation *op) { 395 if (hasTensorSemantics(op)) 396 worklist.push_back(op); 397 }); 398 399 // Keep track of all erased ops. 400 DenseSet<Operation *> erasedOps; 401 402 // Bufferize all ops. 403 BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps, 404 bufferizationState.getOptions()); 405 for (unsigned i = 0; i < worklist.size(); ++i) { 406 Operation *op = worklist[i]; 407 // Skip ops that were erased. 408 if (erasedOps.contains(op)) 409 continue; 410 // Skip ops that are not bufferizable or not allowed. 411 auto bufferizableOp = options.dynCastBufferizableOp(op); 412 if (!bufferizableOp) 413 continue; 414 // Skip ops that no longer have tensor semantics. 415 if (!hasTensorSemantics(op)) 416 continue; 417 // Bufferize the op. 418 rewriter.setInsertionPoint(op); 419 if (failed(bufferizableOp.bufferize(rewriter, bufferizationState))) 420 return op->emitError("failed to bufferize op"); 421 } 422 423 // Fold all to_memref(to_tensor(x)) pairs. 424 for (Operation *op : toMemrefOps) { 425 rewriter.setInsertionPoint(op); 426 (void)bufferization::foldToMemrefToTensorPair(rewriter, 427 cast<ToMemrefOp>(op)); 428 } 429 430 /// Check the result of bufferization. Return an error if an op was not 431 /// bufferized, unless partial bufferization is allowed. 432 if (bufferizationState.getOptions().allowUnknownOps) 433 return success(); 434 435 for (Operation *op : worklist) { 436 // Skip ops that are entirely gone. 437 if (erasedOps.contains(op)) 438 continue; 439 // Ops that no longer have tensor semantics (because they were updated 440 // in-place) are allowed. 441 if (!hasTensorSemantics(op)) 442 continue; 443 // Continue ops that are not allowed. 444 if (!options.isOpAllowed(op)) 445 continue; 446 // Ops without any uses and no side effects will fold away. 447 if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op)) 448 continue; 449 return op->emitError("op was not bufferized"); 450 } 451 452 return success(); 453 } 454 455 namespace { 456 /// This a "no analysis, always copy" AnalysisState. In the absence of an 457 /// analysis, a buffer must be copied each time it is written to. Therefore, all 458 /// OpOperands that bufferize to a memory write must bufferize out-of-place. 459 class AlwaysCopyAnalysisState : public AnalysisState { 460 public: 461 AlwaysCopyAnalysisState(const BufferizationOptions &options) 462 : AnalysisState(options) {} 463 464 AlwaysCopyAnalysisState(const AlwaysCopyAnalysisState &) = delete; 465 466 virtual ~AlwaysCopyAnalysisState() = default; 467 468 /// Return `true` if the given OpResult has been decided to bufferize inplace. 469 bool isInPlace(OpOperand &opOperand) const override { 470 // OpOperands that bufferize to a memory write are out-of-place, i.e., an 471 // alloc and copy is inserted. 472 return !bufferizesToMemoryWrite(opOperand); 473 } 474 475 /// Return true if `v1` and `v2` bufferize to equivalent buffers. 476 bool areEquivalentBufferizedValues(Value v1, Value v2) const override { 477 // There is no analysis, so we do not know if the values are equivalent. The 478 // conservative answer is "false". 479 return false; 480 } 481 }; 482 } // namespace 483 484 LogicalResult bufferization::bufferizeOp(Operation *op, 485 const BufferizationOptions &options) { 486 AlwaysCopyAnalysisState state(options); 487 return bufferizeOp(op, state); 488 } 489 490 BufferizationOptions bufferization::getPartialBufferizationOptions() { 491 BufferizationOptions options; 492 options.allowUnknownOps = true; 493 options.createDeallocs = false; 494 options.unknownTypeConversion = 495 BufferizationOptions::LayoutMapOption::IdentityLayoutMap; 496 return options; 497 } 498