1 //===- InliningUtils.cpp ---- Misc utilities for inlining -----------------===// 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 // This file implements miscellaneous inlining utilities. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Transforms/InliningUtils.h" 14 15 #include "mlir/IR/BlockAndValueMapping.h" 16 #include "mlir/IR/Builders.h" 17 #include "mlir/IR/BuiltinOps.h" 18 #include "mlir/IR/Operation.h" 19 #include "llvm/ADT/MapVector.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 23 #define DEBUG_TYPE "inlining" 24 25 using namespace mlir; 26 27 /// Remap locations from the inlined blocks with CallSiteLoc locations with the 28 /// provided caller location. 29 static void 30 remapInlinedLocations(iterator_range<Region::iterator> inlinedBlocks, 31 Location callerLoc) { 32 DenseMap<Location, Location> mappedLocations; 33 auto remapOpLoc = [&](Operation *op) { 34 auto it = mappedLocations.find(op->getLoc()); 35 if (it == mappedLocations.end()) { 36 auto newLoc = CallSiteLoc::get(op->getLoc(), callerLoc); 37 it = mappedLocations.try_emplace(op->getLoc(), newLoc).first; 38 } 39 op->setLoc(it->second); 40 }; 41 for (auto &block : inlinedBlocks) 42 block.walk(remapOpLoc); 43 } 44 45 static void remapInlinedOperands(iterator_range<Region::iterator> inlinedBlocks, 46 BlockAndValueMapping &mapper) { 47 auto remapOperands = [&](Operation *op) { 48 for (auto &operand : op->getOpOperands()) 49 if (auto mappedOp = mapper.lookupOrNull(operand.get())) 50 operand.set(mappedOp); 51 }; 52 for (auto &block : inlinedBlocks) 53 block.walk(remapOperands); 54 } 55 56 //===----------------------------------------------------------------------===// 57 // InlinerInterface 58 //===----------------------------------------------------------------------===// 59 60 bool InlinerInterface::isLegalToInline(Operation *call, Operation *callable, 61 bool wouldBeCloned) const { 62 if (auto *handler = getInterfaceFor(call)) 63 return handler->isLegalToInline(call, callable, wouldBeCloned); 64 return false; 65 } 66 67 bool InlinerInterface::isLegalToInline( 68 Region *dest, Region *src, bool wouldBeCloned, 69 BlockAndValueMapping &valueMapping) const { 70 // Regions can always be inlined into functions. 71 if (isa<FuncOp>(dest->getParentOp())) 72 return true; 73 74 if (auto *handler = getInterfaceFor(dest->getParentOp())) 75 return handler->isLegalToInline(dest, src, wouldBeCloned, valueMapping); 76 return false; 77 } 78 79 bool InlinerInterface::isLegalToInline( 80 Operation *op, Region *dest, bool wouldBeCloned, 81 BlockAndValueMapping &valueMapping) const { 82 if (auto *handler = getInterfaceFor(op)) 83 return handler->isLegalToInline(op, dest, wouldBeCloned, valueMapping); 84 return false; 85 } 86 87 bool InlinerInterface::shouldAnalyzeRecursively(Operation *op) const { 88 auto *handler = getInterfaceFor(op); 89 return handler ? handler->shouldAnalyzeRecursively(op) : true; 90 } 91 92 /// Handle the given inlined terminator by replacing it with a new operation 93 /// as necessary. 94 void InlinerInterface::handleTerminator(Operation *op, Block *newDest) const { 95 auto *handler = getInterfaceFor(op); 96 assert(handler && "expected valid dialect handler"); 97 handler->handleTerminator(op, newDest); 98 } 99 100 /// Handle the given inlined terminator by replacing it with a new operation 101 /// as necessary. 102 void InlinerInterface::handleTerminator(Operation *op, 103 ArrayRef<Value> valuesToRepl) const { 104 auto *handler = getInterfaceFor(op); 105 assert(handler && "expected valid dialect handler"); 106 handler->handleTerminator(op, valuesToRepl); 107 } 108 109 void InlinerInterface::processInlinedCallBlocks( 110 Operation *call, iterator_range<Region::iterator> inlinedBlocks) const { 111 auto *handler = getInterfaceFor(call); 112 assert(handler && "expected valid dialect handler"); 113 handler->processInlinedCallBlocks(call, inlinedBlocks); 114 } 115 116 /// Utility to check that all of the operations within 'src' can be inlined. 117 static bool isLegalToInline(InlinerInterface &interface, Region *src, 118 Region *insertRegion, bool shouldCloneInlinedRegion, 119 BlockAndValueMapping &valueMapping) { 120 for (auto &block : *src) { 121 for (auto &op : block) { 122 // Check this operation. 123 if (!interface.isLegalToInline(&op, insertRegion, 124 shouldCloneInlinedRegion, valueMapping)) { 125 LLVM_DEBUG({ 126 llvm::dbgs() << "* Illegal to inline because of op: "; 127 op.dump(); 128 }); 129 return false; 130 } 131 // Check any nested regions. 132 if (interface.shouldAnalyzeRecursively(&op) && 133 llvm::any_of(op.getRegions(), [&](Region ®ion) { 134 return !isLegalToInline(interface, ®ion, insertRegion, 135 shouldCloneInlinedRegion, valueMapping); 136 })) 137 return false; 138 } 139 } 140 return true; 141 } 142 143 //===----------------------------------------------------------------------===// 144 // Inline Methods 145 //===----------------------------------------------------------------------===// 146 147 static LogicalResult 148 inlineRegionImpl(InlinerInterface &interface, Region *src, Block *inlineBlock, 149 Block::iterator inlinePoint, BlockAndValueMapping &mapper, 150 ValueRange resultsToReplace, TypeRange regionResultTypes, 151 Optional<Location> inlineLoc, bool shouldCloneInlinedRegion, 152 Operation *call = nullptr) { 153 assert(resultsToReplace.size() == regionResultTypes.size()); 154 // We expect the region to have at least one block. 155 if (src->empty()) 156 return failure(); 157 158 // Check that all of the region arguments have been mapped. 159 auto *srcEntryBlock = &src->front(); 160 if (llvm::any_of(srcEntryBlock->getArguments(), 161 [&](BlockArgument arg) { return !mapper.contains(arg); })) 162 return failure(); 163 164 // Check that the operations within the source region are valid to inline. 165 Region *insertRegion = inlineBlock->getParent(); 166 if (!interface.isLegalToInline(insertRegion, src, shouldCloneInlinedRegion, 167 mapper) || 168 !isLegalToInline(interface, src, insertRegion, shouldCloneInlinedRegion, 169 mapper)) 170 return failure(); 171 172 // Check to see if the region is being cloned, or moved inline. In either 173 // case, move the new blocks after the 'insertBlock' to improve IR 174 // readability. 175 Block *postInsertBlock = inlineBlock->splitBlock(inlinePoint); 176 if (shouldCloneInlinedRegion) 177 src->cloneInto(insertRegion, postInsertBlock->getIterator(), mapper); 178 else 179 insertRegion->getBlocks().splice(postInsertBlock->getIterator(), 180 src->getBlocks(), src->begin(), 181 src->end()); 182 183 // Get the range of newly inserted blocks. 184 auto newBlocks = llvm::make_range(std::next(inlineBlock->getIterator()), 185 postInsertBlock->getIterator()); 186 Block *firstNewBlock = &*newBlocks.begin(); 187 188 // Remap the locations of the inlined operations if a valid source location 189 // was provided. 190 if (inlineLoc && !inlineLoc->isa<UnknownLoc>()) 191 remapInlinedLocations(newBlocks, *inlineLoc); 192 193 // If the blocks were moved in-place, make sure to remap any necessary 194 // operands. 195 if (!shouldCloneInlinedRegion) 196 remapInlinedOperands(newBlocks, mapper); 197 198 // Process the newly inlined blocks. 199 if (call) 200 interface.processInlinedCallBlocks(call, newBlocks); 201 interface.processInlinedBlocks(newBlocks); 202 203 // Handle the case where only a single block was inlined. 204 if (std::next(newBlocks.begin()) == newBlocks.end()) { 205 // Have the interface handle the terminator of this block. 206 auto *firstBlockTerminator = firstNewBlock->getTerminator(); 207 interface.handleTerminator(firstBlockTerminator, 208 llvm::to_vector<6>(resultsToReplace)); 209 firstBlockTerminator->erase(); 210 211 // Merge the post insert block into the cloned entry block. 212 firstNewBlock->getOperations().splice(firstNewBlock->end(), 213 postInsertBlock->getOperations()); 214 postInsertBlock->erase(); 215 } else { 216 // Otherwise, there were multiple blocks inlined. Add arguments to the post 217 // insertion block to represent the results to replace. 218 for (auto resultToRepl : llvm::enumerate(resultsToReplace)) { 219 resultToRepl.value().replaceAllUsesWith(postInsertBlock->addArgument( 220 regionResultTypes[resultToRepl.index()])); 221 } 222 223 /// Handle the terminators for each of the new blocks. 224 for (auto &newBlock : newBlocks) 225 interface.handleTerminator(newBlock.getTerminator(), postInsertBlock); 226 } 227 228 // Splice the instructions of the inlined entry block into the insert block. 229 inlineBlock->getOperations().splice(inlineBlock->end(), 230 firstNewBlock->getOperations()); 231 firstNewBlock->erase(); 232 return success(); 233 } 234 235 static LogicalResult 236 inlineRegionImpl(InlinerInterface &interface, Region *src, Block *inlineBlock, 237 Block::iterator inlinePoint, ValueRange inlinedOperands, 238 ValueRange resultsToReplace, Optional<Location> inlineLoc, 239 bool shouldCloneInlinedRegion, Operation *call = nullptr) { 240 // We expect the region to have at least one block. 241 if (src->empty()) 242 return failure(); 243 244 auto *entryBlock = &src->front(); 245 if (inlinedOperands.size() != entryBlock->getNumArguments()) 246 return failure(); 247 248 // Map the provided call operands to the arguments of the region. 249 BlockAndValueMapping mapper; 250 for (unsigned i = 0, e = inlinedOperands.size(); i != e; ++i) { 251 // Verify that the types of the provided values match the function argument 252 // types. 253 BlockArgument regionArg = entryBlock->getArgument(i); 254 if (inlinedOperands[i].getType() != regionArg.getType()) 255 return failure(); 256 mapper.map(regionArg, inlinedOperands[i]); 257 } 258 259 // Call into the main region inliner function. 260 return inlineRegionImpl(interface, src, inlineBlock, inlinePoint, mapper, 261 resultsToReplace, resultsToReplace.getTypes(), 262 inlineLoc, shouldCloneInlinedRegion, call); 263 } 264 265 LogicalResult mlir::inlineRegion(InlinerInterface &interface, Region *src, 266 Operation *inlinePoint, 267 BlockAndValueMapping &mapper, 268 ValueRange resultsToReplace, 269 TypeRange regionResultTypes, 270 Optional<Location> inlineLoc, 271 bool shouldCloneInlinedRegion) { 272 return inlineRegion(interface, src, inlinePoint->getBlock(), 273 ++inlinePoint->getIterator(), mapper, resultsToReplace, 274 regionResultTypes, inlineLoc, shouldCloneInlinedRegion); 275 } 276 LogicalResult 277 mlir::inlineRegion(InlinerInterface &interface, Region *src, Block *inlineBlock, 278 Block::iterator inlinePoint, BlockAndValueMapping &mapper, 279 ValueRange resultsToReplace, TypeRange regionResultTypes, 280 Optional<Location> inlineLoc, 281 bool shouldCloneInlinedRegion) { 282 return inlineRegionImpl(interface, src, inlineBlock, inlinePoint, mapper, 283 resultsToReplace, regionResultTypes, inlineLoc, 284 shouldCloneInlinedRegion); 285 } 286 287 LogicalResult mlir::inlineRegion(InlinerInterface &interface, Region *src, 288 Operation *inlinePoint, 289 ValueRange inlinedOperands, 290 ValueRange resultsToReplace, 291 Optional<Location> inlineLoc, 292 bool shouldCloneInlinedRegion) { 293 return inlineRegion(interface, src, inlinePoint->getBlock(), 294 ++inlinePoint->getIterator(), inlinedOperands, 295 resultsToReplace, inlineLoc, shouldCloneInlinedRegion); 296 } 297 LogicalResult 298 mlir::inlineRegion(InlinerInterface &interface, Region *src, Block *inlineBlock, 299 Block::iterator inlinePoint, ValueRange inlinedOperands, 300 ValueRange resultsToReplace, Optional<Location> inlineLoc, 301 bool shouldCloneInlinedRegion) { 302 return inlineRegionImpl(interface, src, inlineBlock, inlinePoint, 303 inlinedOperands, resultsToReplace, inlineLoc, 304 shouldCloneInlinedRegion); 305 } 306 307 /// Utility function used to generate a cast operation from the given interface, 308 /// or return nullptr if a cast could not be generated. 309 static Value materializeConversion(const DialectInlinerInterface *interface, 310 SmallVectorImpl<Operation *> &castOps, 311 OpBuilder &castBuilder, Value arg, Type type, 312 Location conversionLoc) { 313 if (!interface) 314 return nullptr; 315 316 // Check to see if the interface for the call can materialize a conversion. 317 Operation *castOp = interface->materializeCallConversion(castBuilder, arg, 318 type, conversionLoc); 319 if (!castOp) 320 return nullptr; 321 castOps.push_back(castOp); 322 323 // Ensure that the generated cast is correct. 324 assert(castOp->getNumOperands() == 1 && castOp->getOperand(0) == arg && 325 castOp->getNumResults() == 1 && *castOp->result_type_begin() == type); 326 return castOp->getResult(0); 327 } 328 329 /// This function inlines a given region, 'src', of a callable operation, 330 /// 'callable', into the location defined by the given call operation. This 331 /// function returns failure if inlining is not possible, success otherwise. On 332 /// failure, no changes are made to the module. 'shouldCloneInlinedRegion' 333 /// corresponds to whether the source region should be cloned into the 'call' or 334 /// spliced directly. 335 LogicalResult mlir::inlineCall(InlinerInterface &interface, 336 CallOpInterface call, 337 CallableOpInterface callable, Region *src, 338 bool shouldCloneInlinedRegion) { 339 // We expect the region to have at least one block. 340 if (src->empty()) 341 return failure(); 342 auto *entryBlock = &src->front(); 343 ArrayRef<Type> callableResultTypes = callable.getCallableResults(); 344 345 // Make sure that the number of arguments and results matchup between the call 346 // and the region. 347 SmallVector<Value, 8> callOperands(call.getArgOperands()); 348 SmallVector<Value, 8> callResults(call->getResults()); 349 if (callOperands.size() != entryBlock->getNumArguments() || 350 callResults.size() != callableResultTypes.size()) 351 return failure(); 352 353 // A set of cast operations generated to matchup the signature of the region 354 // with the signature of the call. 355 SmallVector<Operation *, 4> castOps; 356 castOps.reserve(callOperands.size() + callResults.size()); 357 358 // Functor used to cleanup generated state on failure. 359 auto cleanupState = [&] { 360 for (auto *op : castOps) { 361 op->getResult(0).replaceAllUsesWith(op->getOperand(0)); 362 op->erase(); 363 } 364 return failure(); 365 }; 366 367 // Builder used for any conversion operations that need to be materialized. 368 OpBuilder castBuilder(call); 369 Location castLoc = call.getLoc(); 370 const auto *callInterface = interface.getInterfaceFor(call->getDialect()); 371 372 // Map the provided call operands to the arguments of the region. 373 BlockAndValueMapping mapper; 374 for (unsigned i = 0, e = callOperands.size(); i != e; ++i) { 375 BlockArgument regionArg = entryBlock->getArgument(i); 376 Value operand = callOperands[i]; 377 378 // If the call operand doesn't match the expected region argument, try to 379 // generate a cast. 380 Type regionArgType = regionArg.getType(); 381 if (operand.getType() != regionArgType) { 382 if (!(operand = materializeConversion(callInterface, castOps, castBuilder, 383 operand, regionArgType, castLoc))) 384 return cleanupState(); 385 } 386 mapper.map(regionArg, operand); 387 } 388 389 // Ensure that the resultant values of the call match the callable. 390 castBuilder.setInsertionPointAfter(call); 391 for (unsigned i = 0, e = callResults.size(); i != e; ++i) { 392 Value callResult = callResults[i]; 393 if (callResult.getType() == callableResultTypes[i]) 394 continue; 395 396 // Generate a conversion that will produce the original type, so that the IR 397 // is still valid after the original call gets replaced. 398 Value castResult = 399 materializeConversion(callInterface, castOps, castBuilder, callResult, 400 callResult.getType(), castLoc); 401 if (!castResult) 402 return cleanupState(); 403 callResult.replaceAllUsesWith(castResult); 404 castResult.getDefiningOp()->replaceUsesOfWith(castResult, callResult); 405 } 406 407 // Check that it is legal to inline the callable into the call. 408 if (!interface.isLegalToInline(call, callable, shouldCloneInlinedRegion)) 409 return cleanupState(); 410 411 // Attempt to inline the call. 412 if (failed(inlineRegionImpl(interface, src, call->getBlock(), 413 ++call->getIterator(), mapper, callResults, 414 callableResultTypes, call.getLoc(), 415 shouldCloneInlinedRegion, call))) 416 return cleanupState(); 417 return success(); 418 } 419