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, 149 Operation *inlinePoint, BlockAndValueMapping &mapper, 150 ValueRange resultsToReplace, TypeRange regionResultTypes, 151 Optional<Location> inlineLoc, bool shouldCloneInlinedRegion, 152 Operation *call) { 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 // The insertion point must be within a block. 165 Block *insertBlock = inlinePoint->getBlock(); 166 if (!insertBlock) 167 return failure(); 168 Region *insertRegion = insertBlock->getParent(); 169 170 // Check that the operations within the source region are valid to inline. 171 if (!interface.isLegalToInline(insertRegion, src, shouldCloneInlinedRegion, 172 mapper) || 173 !isLegalToInline(interface, src, insertRegion, shouldCloneInlinedRegion, 174 mapper)) 175 return failure(); 176 177 // Split the insertion block. 178 Block *postInsertBlock = 179 insertBlock->splitBlock(++inlinePoint->getIterator()); 180 181 // Check to see if the region is being cloned, or moved inline. In either 182 // case, move the new blocks after the 'insertBlock' to improve IR 183 // readability. 184 if (shouldCloneInlinedRegion) 185 src->cloneInto(insertRegion, postInsertBlock->getIterator(), mapper); 186 else 187 insertRegion->getBlocks().splice(postInsertBlock->getIterator(), 188 src->getBlocks(), src->begin(), 189 src->end()); 190 191 // Get the range of newly inserted blocks. 192 auto newBlocks = llvm::make_range(std::next(insertBlock->getIterator()), 193 postInsertBlock->getIterator()); 194 Block *firstNewBlock = &*newBlocks.begin(); 195 196 // Remap the locations of the inlined operations if a valid source location 197 // was provided. 198 if (inlineLoc && !inlineLoc->isa<UnknownLoc>()) 199 remapInlinedLocations(newBlocks, *inlineLoc); 200 201 // If the blocks were moved in-place, make sure to remap any necessary 202 // operands. 203 if (!shouldCloneInlinedRegion) 204 remapInlinedOperands(newBlocks, mapper); 205 206 // Process the newly inlined blocks. 207 if (call) 208 interface.processInlinedCallBlocks(call, newBlocks); 209 interface.processInlinedBlocks(newBlocks); 210 211 // Handle the case where only a single block was inlined. 212 if (std::next(newBlocks.begin()) == newBlocks.end()) { 213 // Have the interface handle the terminator of this block. 214 auto *firstBlockTerminator = firstNewBlock->getTerminator(); 215 interface.handleTerminator(firstBlockTerminator, 216 llvm::to_vector<6>(resultsToReplace)); 217 firstBlockTerminator->erase(); 218 219 // Merge the post insert block into the cloned entry block. 220 firstNewBlock->getOperations().splice(firstNewBlock->end(), 221 postInsertBlock->getOperations()); 222 postInsertBlock->erase(); 223 } else { 224 // Otherwise, there were multiple blocks inlined. Add arguments to the post 225 // insertion block to represent the results to replace. 226 for (auto resultToRepl : llvm::enumerate(resultsToReplace)) { 227 resultToRepl.value().replaceAllUsesWith(postInsertBlock->addArgument( 228 regionResultTypes[resultToRepl.index()])); 229 } 230 231 /// Handle the terminators for each of the new blocks. 232 for (auto &newBlock : newBlocks) 233 interface.handleTerminator(newBlock.getTerminator(), postInsertBlock); 234 } 235 236 // Splice the instructions of the inlined entry block into the insert block. 237 insertBlock->getOperations().splice(insertBlock->end(), 238 firstNewBlock->getOperations()); 239 firstNewBlock->erase(); 240 return success(); 241 } 242 243 static LogicalResult 244 inlineRegionImpl(InlinerInterface &interface, Region *src, 245 Operation *inlinePoint, ValueRange inlinedOperands, 246 ValueRange resultsToReplace, Optional<Location> inlineLoc, 247 bool shouldCloneInlinedRegion, Operation *call) { 248 // We expect the region to have at least one block. 249 if (src->empty()) 250 return failure(); 251 252 auto *entryBlock = &src->front(); 253 if (inlinedOperands.size() != entryBlock->getNumArguments()) 254 return failure(); 255 256 // Map the provided call operands to the arguments of the region. 257 BlockAndValueMapping mapper; 258 for (unsigned i = 0, e = inlinedOperands.size(); i != e; ++i) { 259 // Verify that the types of the provided values match the function argument 260 // types. 261 BlockArgument regionArg = entryBlock->getArgument(i); 262 if (inlinedOperands[i].getType() != regionArg.getType()) 263 return failure(); 264 mapper.map(regionArg, inlinedOperands[i]); 265 } 266 267 // Call into the main region inliner function. 268 return inlineRegionImpl(interface, src, inlinePoint, mapper, resultsToReplace, 269 resultsToReplace.getTypes(), inlineLoc, 270 shouldCloneInlinedRegion, call); 271 } 272 273 LogicalResult mlir::inlineRegion(InlinerInterface &interface, Region *src, 274 Operation *inlinePoint, 275 BlockAndValueMapping &mapper, 276 ValueRange resultsToReplace, 277 TypeRange regionResultTypes, 278 Optional<Location> inlineLoc, 279 bool shouldCloneInlinedRegion) { 280 return inlineRegionImpl(interface, src, inlinePoint, mapper, resultsToReplace, 281 regionResultTypes, inlineLoc, 282 shouldCloneInlinedRegion, 283 /*call=*/nullptr); 284 } 285 286 LogicalResult mlir::inlineRegion(InlinerInterface &interface, Region *src, 287 Operation *inlinePoint, 288 ValueRange inlinedOperands, 289 ValueRange resultsToReplace, 290 Optional<Location> inlineLoc, 291 bool shouldCloneInlinedRegion) { 292 return inlineRegionImpl(interface, src, inlinePoint, inlinedOperands, 293 resultsToReplace, inlineLoc, shouldCloneInlinedRegion, 294 /*call=*/nullptr); 295 } 296 297 /// Utility function used to generate a cast operation from the given interface, 298 /// or return nullptr if a cast could not be generated. 299 static Value materializeConversion(const DialectInlinerInterface *interface, 300 SmallVectorImpl<Operation *> &castOps, 301 OpBuilder &castBuilder, Value arg, Type type, 302 Location conversionLoc) { 303 if (!interface) 304 return nullptr; 305 306 // Check to see if the interface for the call can materialize a conversion. 307 Operation *castOp = interface->materializeCallConversion(castBuilder, arg, 308 type, conversionLoc); 309 if (!castOp) 310 return nullptr; 311 castOps.push_back(castOp); 312 313 // Ensure that the generated cast is correct. 314 assert(castOp->getNumOperands() == 1 && castOp->getOperand(0) == arg && 315 castOp->getNumResults() == 1 && *castOp->result_type_begin() == type); 316 return castOp->getResult(0); 317 } 318 319 /// This function inlines a given region, 'src', of a callable operation, 320 /// 'callable', into the location defined by the given call operation. This 321 /// function returns failure if inlining is not possible, success otherwise. On 322 /// failure, no changes are made to the module. 'shouldCloneInlinedRegion' 323 /// corresponds to whether the source region should be cloned into the 'call' or 324 /// spliced directly. 325 LogicalResult mlir::inlineCall(InlinerInterface &interface, 326 CallOpInterface call, 327 CallableOpInterface callable, Region *src, 328 bool shouldCloneInlinedRegion) { 329 // We expect the region to have at least one block. 330 if (src->empty()) 331 return failure(); 332 auto *entryBlock = &src->front(); 333 ArrayRef<Type> callableResultTypes = callable.getCallableResults(); 334 335 // Make sure that the number of arguments and results matchup between the call 336 // and the region. 337 SmallVector<Value, 8> callOperands(call.getArgOperands()); 338 SmallVector<Value, 8> callResults(call->getResults()); 339 if (callOperands.size() != entryBlock->getNumArguments() || 340 callResults.size() != callableResultTypes.size()) 341 return failure(); 342 343 // A set of cast operations generated to matchup the signature of the region 344 // with the signature of the call. 345 SmallVector<Operation *, 4> castOps; 346 castOps.reserve(callOperands.size() + callResults.size()); 347 348 // Functor used to cleanup generated state on failure. 349 auto cleanupState = [&] { 350 for (auto *op : castOps) { 351 op->getResult(0).replaceAllUsesWith(op->getOperand(0)); 352 op->erase(); 353 } 354 return failure(); 355 }; 356 357 // Builder used for any conversion operations that need to be materialized. 358 OpBuilder castBuilder(call); 359 Location castLoc = call.getLoc(); 360 const auto *callInterface = interface.getInterfaceFor(call->getDialect()); 361 362 // Map the provided call operands to the arguments of the region. 363 BlockAndValueMapping mapper; 364 for (unsigned i = 0, e = callOperands.size(); i != e; ++i) { 365 BlockArgument regionArg = entryBlock->getArgument(i); 366 Value operand = callOperands[i]; 367 368 // If the call operand doesn't match the expected region argument, try to 369 // generate a cast. 370 Type regionArgType = regionArg.getType(); 371 if (operand.getType() != regionArgType) { 372 if (!(operand = materializeConversion(callInterface, castOps, castBuilder, 373 operand, regionArgType, castLoc))) 374 return cleanupState(); 375 } 376 mapper.map(regionArg, operand); 377 } 378 379 // Ensure that the resultant values of the call match the callable. 380 castBuilder.setInsertionPointAfter(call); 381 for (unsigned i = 0, e = callResults.size(); i != e; ++i) { 382 Value callResult = callResults[i]; 383 if (callResult.getType() == callableResultTypes[i]) 384 continue; 385 386 // Generate a conversion that will produce the original type, so that the IR 387 // is still valid after the original call gets replaced. 388 Value castResult = 389 materializeConversion(callInterface, castOps, castBuilder, callResult, 390 callResult.getType(), castLoc); 391 if (!castResult) 392 return cleanupState(); 393 callResult.replaceAllUsesWith(castResult); 394 castResult.getDefiningOp()->replaceUsesOfWith(castResult, callResult); 395 } 396 397 // Check that it is legal to inline the callable into the call. 398 if (!interface.isLegalToInline(call, callable, shouldCloneInlinedRegion)) 399 return cleanupState(); 400 401 // Attempt to inline the call. 402 if (failed(inlineRegionImpl(interface, src, call, mapper, callResults, 403 callableResultTypes, call.getLoc(), 404 shouldCloneInlinedRegion, call))) 405 return cleanupState(); 406 return success(); 407 } 408