1 //===- InlineFunction.cpp - Code to perform function 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 inlining of a function into a call site, resolving 10 // parameters and the return value as appropriate. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/None.h" 16 #include "llvm/ADT/Optional.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/BlockFrequencyInfo.h" 26 #include "llvm/Analysis/CallGraph.h" 27 #include "llvm/Analysis/CaptureTracking.h" 28 #include "llvm/Analysis/EHPersonalities.h" 29 #include "llvm/Analysis/InstructionSimplify.h" 30 #include "llvm/Analysis/ObjCARCAnalysisUtils.h" 31 #include "llvm/Analysis/ObjCARCUtil.h" 32 #include "llvm/Analysis/ProfileSummaryInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/Analysis/VectorUtils.h" 35 #include "llvm/IR/Argument.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/Constant.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DIBuilder.h" 41 #include "llvm/IR/DataLayout.h" 42 #include "llvm/IR/DebugInfoMetadata.h" 43 #include "llvm/IR/DebugLoc.h" 44 #include "llvm/IR/DerivedTypes.h" 45 #include "llvm/IR/Dominators.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/IRBuilder.h" 48 #include "llvm/IR/InstrTypes.h" 49 #include "llvm/IR/Instruction.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/IntrinsicInst.h" 52 #include "llvm/IR/Intrinsics.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/MDBuilder.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Module.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/User.h" 59 #include "llvm/IR/Value.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 64 #include "llvm/Transforms/Utils/Cloning.h" 65 #include "llvm/Transforms/Utils/Local.h" 66 #include "llvm/Transforms/Utils/ValueMapper.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstdint> 70 #include <iterator> 71 #include <limits> 72 #include <string> 73 #include <utility> 74 #include <vector> 75 76 using namespace llvm; 77 using ProfileCount = Function::ProfileCount; 78 79 static cl::opt<bool> 80 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true), 81 cl::Hidden, 82 cl::desc("Convert noalias attributes to metadata during inlining.")); 83 84 static cl::opt<bool> 85 UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden, 86 cl::ZeroOrMore, cl::init(true), 87 cl::desc("Use the llvm.experimental.noalias.scope.decl " 88 "intrinsic during inlining.")); 89 90 // Disabled by default, because the added alignment assumptions may increase 91 // compile-time and block optimizations. This option is not suitable for use 92 // with frontends that emit comprehensive parameter alignment annotations. 93 static cl::opt<bool> 94 PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining", 95 cl::init(false), cl::Hidden, 96 cl::desc("Convert align attributes to assumptions during inlining.")); 97 98 static cl::opt<bool> UpdateReturnAttributes( 99 "update-return-attrs", cl::init(true), cl::Hidden, 100 cl::desc("Update return attributes on calls within inlined body")); 101 102 static cl::opt<unsigned> InlinerAttributeWindow( 103 "max-inst-checked-for-throw-during-inlining", cl::Hidden, 104 cl::desc("the maximum number of instructions analyzed for may throw during " 105 "attribute inference in inlined body"), 106 cl::init(4)); 107 108 namespace { 109 110 /// A class for recording information about inlining a landing pad. 111 class LandingPadInliningInfo { 112 /// Destination of the invoke's unwind. 113 BasicBlock *OuterResumeDest; 114 115 /// Destination for the callee's resume. 116 BasicBlock *InnerResumeDest = nullptr; 117 118 /// LandingPadInst associated with the invoke. 119 LandingPadInst *CallerLPad = nullptr; 120 121 /// PHI for EH values from landingpad insts. 122 PHINode *InnerEHValuesPHI = nullptr; 123 124 SmallVector<Value*, 8> UnwindDestPHIValues; 125 126 public: 127 LandingPadInliningInfo(InvokeInst *II) 128 : OuterResumeDest(II->getUnwindDest()) { 129 // If there are PHI nodes in the unwind destination block, we need to keep 130 // track of which values came into them from the invoke before removing 131 // the edge from this block. 132 BasicBlock *InvokeBB = II->getParent(); 133 BasicBlock::iterator I = OuterResumeDest->begin(); 134 for (; isa<PHINode>(I); ++I) { 135 // Save the value to use for this edge. 136 PHINode *PHI = cast<PHINode>(I); 137 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB)); 138 } 139 140 CallerLPad = cast<LandingPadInst>(I); 141 } 142 143 /// The outer unwind destination is the target of 144 /// unwind edges introduced for calls within the inlined function. 145 BasicBlock *getOuterResumeDest() const { 146 return OuterResumeDest; 147 } 148 149 BasicBlock *getInnerResumeDest(); 150 151 LandingPadInst *getLandingPadInst() const { return CallerLPad; } 152 153 /// Forward the 'resume' instruction to the caller's landing pad block. 154 /// When the landing pad block has only one predecessor, this is 155 /// a simple branch. When there is more than one predecessor, we need to 156 /// split the landing pad block after the landingpad instruction and jump 157 /// to there. 158 void forwardResume(ResumeInst *RI, 159 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads); 160 161 /// Add incoming-PHI values to the unwind destination block for the given 162 /// basic block, using the values for the original invoke's source block. 163 void addIncomingPHIValuesFor(BasicBlock *BB) const { 164 addIncomingPHIValuesForInto(BB, OuterResumeDest); 165 } 166 167 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const { 168 BasicBlock::iterator I = dest->begin(); 169 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { 170 PHINode *phi = cast<PHINode>(I); 171 phi->addIncoming(UnwindDestPHIValues[i], src); 172 } 173 } 174 }; 175 176 } // end anonymous namespace 177 178 /// Get or create a target for the branch from ResumeInsts. 179 BasicBlock *LandingPadInliningInfo::getInnerResumeDest() { 180 if (InnerResumeDest) return InnerResumeDest; 181 182 // Split the landing pad. 183 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator(); 184 InnerResumeDest = 185 OuterResumeDest->splitBasicBlock(SplitPoint, 186 OuterResumeDest->getName() + ".body"); 187 188 // The number of incoming edges we expect to the inner landing pad. 189 const unsigned PHICapacity = 2; 190 191 // Create corresponding new PHIs for all the PHIs in the outer landing pad. 192 Instruction *InsertPoint = &InnerResumeDest->front(); 193 BasicBlock::iterator I = OuterResumeDest->begin(); 194 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { 195 PHINode *OuterPHI = cast<PHINode>(I); 196 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity, 197 OuterPHI->getName() + ".lpad-body", 198 InsertPoint); 199 OuterPHI->replaceAllUsesWith(InnerPHI); 200 InnerPHI->addIncoming(OuterPHI, OuterResumeDest); 201 } 202 203 // Create a PHI for the exception values. 204 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity, 205 "eh.lpad-body", InsertPoint); 206 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI); 207 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest); 208 209 // All done. 210 return InnerResumeDest; 211 } 212 213 /// Forward the 'resume' instruction to the caller's landing pad block. 214 /// When the landing pad block has only one predecessor, this is a simple 215 /// branch. When there is more than one predecessor, we need to split the 216 /// landing pad block after the landingpad instruction and jump to there. 217 void LandingPadInliningInfo::forwardResume( 218 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { 219 BasicBlock *Dest = getInnerResumeDest(); 220 BasicBlock *Src = RI->getParent(); 221 222 BranchInst::Create(Dest, Src); 223 224 // Update the PHIs in the destination. They were inserted in an order which 225 // makes this work. 226 addIncomingPHIValuesForInto(Src, Dest); 227 228 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src); 229 RI->eraseFromParent(); 230 } 231 232 /// Helper for getUnwindDestToken/getUnwindDestTokenHelper. 233 static Value *getParentPad(Value *EHPad) { 234 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 235 return FPI->getParentPad(); 236 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 237 } 238 239 using UnwindDestMemoTy = DenseMap<Instruction *, Value *>; 240 241 /// Helper for getUnwindDestToken that does the descendant-ward part of 242 /// the search. 243 static Value *getUnwindDestTokenHelper(Instruction *EHPad, 244 UnwindDestMemoTy &MemoMap) { 245 SmallVector<Instruction *, 8> Worklist(1, EHPad); 246 247 while (!Worklist.empty()) { 248 Instruction *CurrentPad = Worklist.pop_back_val(); 249 // We only put pads on the worklist that aren't in the MemoMap. When 250 // we find an unwind dest for a pad we may update its ancestors, but 251 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad, 252 // so they should never get updated while queued on the worklist. 253 assert(!MemoMap.count(CurrentPad)); 254 Value *UnwindDestToken = nullptr; 255 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) { 256 if (CatchSwitch->hasUnwindDest()) { 257 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI(); 258 } else { 259 // Catchswitch doesn't have a 'nounwind' variant, and one might be 260 // annotated as "unwinds to caller" when really it's nounwind (see 261 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the 262 // parent's unwind dest from this. We can check its catchpads' 263 // descendants, since they might include a cleanuppad with an 264 // "unwinds to caller" cleanupret, which can be trusted. 265 for (auto HI = CatchSwitch->handler_begin(), 266 HE = CatchSwitch->handler_end(); 267 HI != HE && !UnwindDestToken; ++HI) { 268 BasicBlock *HandlerBlock = *HI; 269 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI()); 270 for (User *Child : CatchPad->users()) { 271 // Intentionally ignore invokes here -- since the catchswitch is 272 // marked "unwind to caller", it would be a verifier error if it 273 // contained an invoke which unwinds out of it, so any invoke we'd 274 // encounter must unwind to some child of the catch. 275 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child)) 276 continue; 277 278 Instruction *ChildPad = cast<Instruction>(Child); 279 auto Memo = MemoMap.find(ChildPad); 280 if (Memo == MemoMap.end()) { 281 // Haven't figured out this child pad yet; queue it. 282 Worklist.push_back(ChildPad); 283 continue; 284 } 285 // We've already checked this child, but might have found that 286 // it offers no proof either way. 287 Value *ChildUnwindDestToken = Memo->second; 288 if (!ChildUnwindDestToken) 289 continue; 290 // We already know the child's unwind dest, which can either 291 // be ConstantTokenNone to indicate unwind to caller, or can 292 // be another child of the catchpad. Only the former indicates 293 // the unwind dest of the catchswitch. 294 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) { 295 UnwindDestToken = ChildUnwindDestToken; 296 break; 297 } 298 assert(getParentPad(ChildUnwindDestToken) == CatchPad); 299 } 300 } 301 } 302 } else { 303 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad); 304 for (User *U : CleanupPad->users()) { 305 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) { 306 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest()) 307 UnwindDestToken = RetUnwindDest->getFirstNonPHI(); 308 else 309 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext()); 310 break; 311 } 312 Value *ChildUnwindDestToken; 313 if (auto *Invoke = dyn_cast<InvokeInst>(U)) { 314 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI(); 315 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) { 316 Instruction *ChildPad = cast<Instruction>(U); 317 auto Memo = MemoMap.find(ChildPad); 318 if (Memo == MemoMap.end()) { 319 // Haven't resolved this child yet; queue it and keep searching. 320 Worklist.push_back(ChildPad); 321 continue; 322 } 323 // We've checked this child, but still need to ignore it if it 324 // had no proof either way. 325 ChildUnwindDestToken = Memo->second; 326 if (!ChildUnwindDestToken) 327 continue; 328 } else { 329 // Not a relevant user of the cleanuppad 330 continue; 331 } 332 // In a well-formed program, the child/invoke must either unwind to 333 // an(other) child of the cleanup, or exit the cleanup. In the 334 // first case, continue searching. 335 if (isa<Instruction>(ChildUnwindDestToken) && 336 getParentPad(ChildUnwindDestToken) == CleanupPad) 337 continue; 338 UnwindDestToken = ChildUnwindDestToken; 339 break; 340 } 341 } 342 // If we haven't found an unwind dest for CurrentPad, we may have queued its 343 // children, so move on to the next in the worklist. 344 if (!UnwindDestToken) 345 continue; 346 347 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits 348 // any ancestors of CurrentPad up to but not including UnwindDestToken's 349 // parent pad. Record this in the memo map, and check to see if the 350 // original EHPad being queried is one of the ones exited. 351 Value *UnwindParent; 352 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken)) 353 UnwindParent = getParentPad(UnwindPad); 354 else 355 UnwindParent = nullptr; 356 bool ExitedOriginalPad = false; 357 for (Instruction *ExitedPad = CurrentPad; 358 ExitedPad && ExitedPad != UnwindParent; 359 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) { 360 // Skip over catchpads since they just follow their catchswitches. 361 if (isa<CatchPadInst>(ExitedPad)) 362 continue; 363 MemoMap[ExitedPad] = UnwindDestToken; 364 ExitedOriginalPad |= (ExitedPad == EHPad); 365 } 366 367 if (ExitedOriginalPad) 368 return UnwindDestToken; 369 370 // Continue the search. 371 } 372 373 // No definitive information is contained within this funclet. 374 return nullptr; 375 } 376 377 /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad, 378 /// return that pad instruction. If it unwinds to caller, return 379 /// ConstantTokenNone. If it does not have a definitive unwind destination, 380 /// return nullptr. 381 /// 382 /// This routine gets invoked for calls in funclets in inlinees when inlining 383 /// an invoke. Since many funclets don't have calls inside them, it's queried 384 /// on-demand rather than building a map of pads to unwind dests up front. 385 /// Determining a funclet's unwind dest may require recursively searching its 386 /// descendants, and also ancestors and cousins if the descendants don't provide 387 /// an answer. Since most funclets will have their unwind dest immediately 388 /// available as the unwind dest of a catchswitch or cleanupret, this routine 389 /// searches top-down from the given pad and then up. To avoid worst-case 390 /// quadratic run-time given that approach, it uses a memo map to avoid 391 /// re-processing funclet trees. The callers that rewrite the IR as they go 392 /// take advantage of this, for correctness, by checking/forcing rewritten 393 /// pads' entries to match the original callee view. 394 static Value *getUnwindDestToken(Instruction *EHPad, 395 UnwindDestMemoTy &MemoMap) { 396 // Catchpads unwind to the same place as their catchswitch; 397 // redirct any queries on catchpads so the code below can 398 // deal with just catchswitches and cleanuppads. 399 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad)) 400 EHPad = CPI->getCatchSwitch(); 401 402 // Check if we've already determined the unwind dest for this pad. 403 auto Memo = MemoMap.find(EHPad); 404 if (Memo != MemoMap.end()) 405 return Memo->second; 406 407 // Search EHPad and, if necessary, its descendants. 408 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap); 409 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0)); 410 if (UnwindDestToken) 411 return UnwindDestToken; 412 413 // No information is available for this EHPad from itself or any of its 414 // descendants. An unwind all the way out to a pad in the caller would 415 // need also to agree with the unwind dest of the parent funclet, so 416 // search up the chain to try to find a funclet with information. Put 417 // null entries in the memo map to avoid re-processing as we go up. 418 MemoMap[EHPad] = nullptr; 419 #ifndef NDEBUG 420 SmallPtrSet<Instruction *, 4> TempMemos; 421 TempMemos.insert(EHPad); 422 #endif 423 Instruction *LastUselessPad = EHPad; 424 Value *AncestorToken; 425 for (AncestorToken = getParentPad(EHPad); 426 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken); 427 AncestorToken = getParentPad(AncestorToken)) { 428 // Skip over catchpads since they just follow their catchswitches. 429 if (isa<CatchPadInst>(AncestorPad)) 430 continue; 431 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we 432 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this 433 // call to getUnwindDestToken, that would mean that AncestorPad had no 434 // information in itself, its descendants, or its ancestors. If that 435 // were the case, then we should also have recorded the lack of information 436 // for the descendant that we're coming from. So assert that we don't 437 // find a null entry in the MemoMap for AncestorPad. 438 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]); 439 auto AncestorMemo = MemoMap.find(AncestorPad); 440 if (AncestorMemo == MemoMap.end()) { 441 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap); 442 } else { 443 UnwindDestToken = AncestorMemo->second; 444 } 445 if (UnwindDestToken) 446 break; 447 LastUselessPad = AncestorPad; 448 MemoMap[LastUselessPad] = nullptr; 449 #ifndef NDEBUG 450 TempMemos.insert(LastUselessPad); 451 #endif 452 } 453 454 // We know that getUnwindDestTokenHelper was called on LastUselessPad and 455 // returned nullptr (and likewise for EHPad and any of its ancestors up to 456 // LastUselessPad), so LastUselessPad has no information from below. Since 457 // getUnwindDestTokenHelper must investigate all downward paths through 458 // no-information nodes to prove that a node has no information like this, 459 // and since any time it finds information it records it in the MemoMap for 460 // not just the immediately-containing funclet but also any ancestors also 461 // exited, it must be the case that, walking downward from LastUselessPad, 462 // visiting just those nodes which have not been mapped to an unwind dest 463 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since 464 // they are just used to keep getUnwindDestTokenHelper from repeating work), 465 // any node visited must have been exhaustively searched with no information 466 // for it found. 467 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad); 468 while (!Worklist.empty()) { 469 Instruction *UselessPad = Worklist.pop_back_val(); 470 auto Memo = MemoMap.find(UselessPad); 471 if (Memo != MemoMap.end() && Memo->second) { 472 // Here the name 'UselessPad' is a bit of a misnomer, because we've found 473 // that it is a funclet that does have information about unwinding to 474 // a particular destination; its parent was a useless pad. 475 // Since its parent has no information, the unwind edge must not escape 476 // the parent, and must target a sibling of this pad. This local unwind 477 // gives us no information about EHPad. Leave it and the subtree rooted 478 // at it alone. 479 assert(getParentPad(Memo->second) == getParentPad(UselessPad)); 480 continue; 481 } 482 // We know we don't have information for UselesPad. If it has an entry in 483 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos 484 // added on this invocation of getUnwindDestToken; if a previous invocation 485 // recorded nullptr, it would have had to prove that the ancestors of 486 // UselessPad, which include LastUselessPad, had no information, and that 487 // in turn would have required proving that the descendants of 488 // LastUselesPad, which include EHPad, have no information about 489 // LastUselessPad, which would imply that EHPad was mapped to nullptr in 490 // the MemoMap on that invocation, which isn't the case if we got here. 491 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad)); 492 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind 493 // information that we'd be contradicting by making a map entry for it 494 // (which is something that getUnwindDestTokenHelper must have proved for 495 // us to get here). Just assert on is direct users here; the checks in 496 // this downward walk at its descendants will verify that they don't have 497 // any unwind edges that exit 'UselessPad' either (i.e. they either have no 498 // unwind edges or unwind to a sibling). 499 MemoMap[UselessPad] = UnwindDestToken; 500 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) { 501 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad"); 502 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) { 503 auto *CatchPad = HandlerBlock->getFirstNonPHI(); 504 for (User *U : CatchPad->users()) { 505 assert( 506 (!isa<InvokeInst>(U) || 507 (getParentPad( 508 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == 509 CatchPad)) && 510 "Expected useless pad"); 511 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) 512 Worklist.push_back(cast<Instruction>(U)); 513 } 514 } 515 } else { 516 assert(isa<CleanupPadInst>(UselessPad)); 517 for (User *U : UselessPad->users()) { 518 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad"); 519 assert((!isa<InvokeInst>(U) || 520 (getParentPad( 521 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == 522 UselessPad)) && 523 "Expected useless pad"); 524 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) 525 Worklist.push_back(cast<Instruction>(U)); 526 } 527 } 528 } 529 530 return UnwindDestToken; 531 } 532 533 /// When we inline a basic block into an invoke, 534 /// we have to turn all of the calls that can throw into invokes. 535 /// This function analyze BB to see if there are any calls, and if so, 536 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI 537 /// nodes in that block with the values specified in InvokeDestPHIValues. 538 static BasicBlock *HandleCallsInBlockInlinedThroughInvoke( 539 BasicBlock *BB, BasicBlock *UnwindEdge, 540 UnwindDestMemoTy *FuncletUnwindMap = nullptr) { 541 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 542 Instruction *I = &*BBI++; 543 544 // We only need to check for function calls: inlined invoke 545 // instructions require no special handling. 546 CallInst *CI = dyn_cast<CallInst>(I); 547 548 if (!CI || CI->doesNotThrow() || CI->isInlineAsm()) 549 continue; 550 551 // We do not need to (and in fact, cannot) convert possibly throwing calls 552 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into 553 // invokes. The caller's "segment" of the deoptimization continuation 554 // attached to the newly inlined @llvm.experimental_deoptimize 555 // (resp. @llvm.experimental.guard) call should contain the exception 556 // handling logic, if any. 557 if (auto *F = CI->getCalledFunction()) 558 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize || 559 F->getIntrinsicID() == Intrinsic::experimental_guard) 560 continue; 561 562 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) { 563 // This call is nested inside a funclet. If that funclet has an unwind 564 // destination within the inlinee, then unwinding out of this call would 565 // be UB. Rewriting this call to an invoke which targets the inlined 566 // invoke's unwind dest would give the call's parent funclet multiple 567 // unwind destinations, which is something that subsequent EH table 568 // generation can't handle and that the veirifer rejects. So when we 569 // see such a call, leave it as a call. 570 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]); 571 Value *UnwindDestToken = 572 getUnwindDestToken(FuncletPad, *FuncletUnwindMap); 573 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) 574 continue; 575 #ifndef NDEBUG 576 Instruction *MemoKey; 577 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad)) 578 MemoKey = CatchPad->getCatchSwitch(); 579 else 580 MemoKey = FuncletPad; 581 assert(FuncletUnwindMap->count(MemoKey) && 582 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken && 583 "must get memoized to avoid confusing later searches"); 584 #endif // NDEBUG 585 } 586 587 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge); 588 return BB; 589 } 590 return nullptr; 591 } 592 593 /// If we inlined an invoke site, we need to convert calls 594 /// in the body of the inlined function into invokes. 595 /// 596 /// II is the invoke instruction being inlined. FirstNewBlock is the first 597 /// block of the inlined code (the last block is the end of the function), 598 /// and InlineCodeInfo is information about the code that got inlined. 599 static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock, 600 ClonedCodeInfo &InlinedCodeInfo) { 601 BasicBlock *InvokeDest = II->getUnwindDest(); 602 603 Function *Caller = FirstNewBlock->getParent(); 604 605 // The inlined code is currently at the end of the function, scan from the 606 // start of the inlined code to its end, checking for stuff we need to 607 // rewrite. 608 LandingPadInliningInfo Invoke(II); 609 610 // Get all of the inlined landing pad instructions. 611 SmallPtrSet<LandingPadInst*, 16> InlinedLPads; 612 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end(); 613 I != E; ++I) 614 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) 615 InlinedLPads.insert(II->getLandingPadInst()); 616 617 // Append the clauses from the outer landing pad instruction into the inlined 618 // landing pad instructions. 619 LandingPadInst *OuterLPad = Invoke.getLandingPadInst(); 620 for (LandingPadInst *InlinedLPad : InlinedLPads) { 621 unsigned OuterNum = OuterLPad->getNumClauses(); 622 InlinedLPad->reserveClauses(OuterNum); 623 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx) 624 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx)); 625 if (OuterLPad->isCleanup()) 626 InlinedLPad->setCleanup(true); 627 } 628 629 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); 630 BB != E; ++BB) { 631 if (InlinedCodeInfo.ContainsCalls) 632 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( 633 &*BB, Invoke.getOuterResumeDest())) 634 // Update any PHI nodes in the exceptional block to indicate that there 635 // is now a new entry in them. 636 Invoke.addIncomingPHIValuesFor(NewBB); 637 638 // Forward any resumes that are remaining here. 639 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) 640 Invoke.forwardResume(RI, InlinedLPads); 641 } 642 643 // Now that everything is happy, we have one final detail. The PHI nodes in 644 // the exception destination block still have entries due to the original 645 // invoke instruction. Eliminate these entries (which might even delete the 646 // PHI node) now. 647 InvokeDest->removePredecessor(II->getParent()); 648 } 649 650 /// If we inlined an invoke site, we need to convert calls 651 /// in the body of the inlined function into invokes. 652 /// 653 /// II is the invoke instruction being inlined. FirstNewBlock is the first 654 /// block of the inlined code (the last block is the end of the function), 655 /// and InlineCodeInfo is information about the code that got inlined. 656 static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock, 657 ClonedCodeInfo &InlinedCodeInfo) { 658 BasicBlock *UnwindDest = II->getUnwindDest(); 659 Function *Caller = FirstNewBlock->getParent(); 660 661 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!"); 662 663 // If there are PHI nodes in the unwind destination block, we need to keep 664 // track of which values came into them from the invoke before removing the 665 // edge from this block. 666 SmallVector<Value *, 8> UnwindDestPHIValues; 667 BasicBlock *InvokeBB = II->getParent(); 668 for (Instruction &I : *UnwindDest) { 669 // Save the value to use for this edge. 670 PHINode *PHI = dyn_cast<PHINode>(&I); 671 if (!PHI) 672 break; 673 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB)); 674 } 675 676 // Add incoming-PHI values to the unwind destination block for the given basic 677 // block, using the values for the original invoke's source block. 678 auto UpdatePHINodes = [&](BasicBlock *Src) { 679 BasicBlock::iterator I = UnwindDest->begin(); 680 for (Value *V : UnwindDestPHIValues) { 681 PHINode *PHI = cast<PHINode>(I); 682 PHI->addIncoming(V, Src); 683 ++I; 684 } 685 }; 686 687 // This connects all the instructions which 'unwind to caller' to the invoke 688 // destination. 689 UnwindDestMemoTy FuncletUnwindMap; 690 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); 691 BB != E; ++BB) { 692 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) { 693 if (CRI->unwindsToCaller()) { 694 auto *CleanupPad = CRI->getCleanupPad(); 695 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI); 696 CRI->eraseFromParent(); 697 UpdatePHINodes(&*BB); 698 // Finding a cleanupret with an unwind destination would confuse 699 // subsequent calls to getUnwindDestToken, so map the cleanuppad 700 // to short-circuit any such calls and recognize this as an "unwind 701 // to caller" cleanup. 702 assert(!FuncletUnwindMap.count(CleanupPad) || 703 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad])); 704 FuncletUnwindMap[CleanupPad] = 705 ConstantTokenNone::get(Caller->getContext()); 706 } 707 } 708 709 Instruction *I = BB->getFirstNonPHI(); 710 if (!I->isEHPad()) 711 continue; 712 713 Instruction *Replacement = nullptr; 714 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { 715 if (CatchSwitch->unwindsToCaller()) { 716 Value *UnwindDestToken; 717 if (auto *ParentPad = 718 dyn_cast<Instruction>(CatchSwitch->getParentPad())) { 719 // This catchswitch is nested inside another funclet. If that 720 // funclet has an unwind destination within the inlinee, then 721 // unwinding out of this catchswitch would be UB. Rewriting this 722 // catchswitch to unwind to the inlined invoke's unwind dest would 723 // give the parent funclet multiple unwind destinations, which is 724 // something that subsequent EH table generation can't handle and 725 // that the veirifer rejects. So when we see such a call, leave it 726 // as "unwind to caller". 727 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap); 728 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) 729 continue; 730 } else { 731 // This catchswitch has no parent to inherit constraints from, and 732 // none of its descendants can have an unwind edge that exits it and 733 // targets another funclet in the inlinee. It may or may not have a 734 // descendant that definitively has an unwind to caller. In either 735 // case, we'll have to assume that any unwinds out of it may need to 736 // be routed to the caller, so treat it as though it has a definitive 737 // unwind to caller. 738 UnwindDestToken = ConstantTokenNone::get(Caller->getContext()); 739 } 740 auto *NewCatchSwitch = CatchSwitchInst::Create( 741 CatchSwitch->getParentPad(), UnwindDest, 742 CatchSwitch->getNumHandlers(), CatchSwitch->getName(), 743 CatchSwitch); 744 for (BasicBlock *PadBB : CatchSwitch->handlers()) 745 NewCatchSwitch->addHandler(PadBB); 746 // Propagate info for the old catchswitch over to the new one in 747 // the unwind map. This also serves to short-circuit any subsequent 748 // checks for the unwind dest of this catchswitch, which would get 749 // confused if they found the outer handler in the callee. 750 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken; 751 Replacement = NewCatchSwitch; 752 } 753 } else if (!isa<FuncletPadInst>(I)) { 754 llvm_unreachable("unexpected EHPad!"); 755 } 756 757 if (Replacement) { 758 Replacement->takeName(I); 759 I->replaceAllUsesWith(Replacement); 760 I->eraseFromParent(); 761 UpdatePHINodes(&*BB); 762 } 763 } 764 765 if (InlinedCodeInfo.ContainsCalls) 766 for (Function::iterator BB = FirstNewBlock->getIterator(), 767 E = Caller->end(); 768 BB != E; ++BB) 769 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( 770 &*BB, UnwindDest, &FuncletUnwindMap)) 771 // Update any PHI nodes in the exceptional block to indicate that there 772 // is now a new entry in them. 773 UpdatePHINodes(NewBB); 774 775 // Now that everything is happy, we have one final detail. The PHI nodes in 776 // the exception destination block still have entries due to the original 777 // invoke instruction. Eliminate these entries (which might even delete the 778 // PHI node) now. 779 UnwindDest->removePredecessor(InvokeBB); 780 } 781 782 /// When inlining a call site that has !llvm.mem.parallel_loop_access, 783 /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should 784 /// be propagated to all memory-accessing cloned instructions. 785 static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart, 786 Function::iterator FEnd) { 787 MDNode *MemParallelLoopAccess = 788 CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 789 MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group); 790 MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope); 791 MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias); 792 if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias) 793 return; 794 795 for (BasicBlock &BB : make_range(FStart, FEnd)) { 796 for (Instruction &I : BB) { 797 // This metadata is only relevant for instructions that access memory. 798 if (!I.mayReadOrWriteMemory()) 799 continue; 800 801 if (MemParallelLoopAccess) { 802 // TODO: This probably should not overwrite MemParalleLoopAccess. 803 MemParallelLoopAccess = MDNode::concatenate( 804 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access), 805 MemParallelLoopAccess); 806 I.setMetadata(LLVMContext::MD_mem_parallel_loop_access, 807 MemParallelLoopAccess); 808 } 809 810 if (AccessGroup) 811 I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups( 812 I.getMetadata(LLVMContext::MD_access_group), AccessGroup)); 813 814 if (AliasScope) 815 I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate( 816 I.getMetadata(LLVMContext::MD_alias_scope), AliasScope)); 817 818 if (NoAlias) 819 I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate( 820 I.getMetadata(LLVMContext::MD_noalias), NoAlias)); 821 } 822 } 823 } 824 825 /// Utility for cloning !noalias and !alias.scope metadata. When a code region 826 /// using scoped alias metadata is inlined, the aliasing relationships may not 827 /// hold between the two version. It is necessary to create a deep clone of the 828 /// metadata, putting the two versions in separate scope domains. 829 class ScopedAliasMetadataDeepCloner { 830 using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>; 831 SetVector<const MDNode *> MD; 832 MetadataMap MDMap; 833 void addRecursiveMetadataUses(); 834 835 public: 836 ScopedAliasMetadataDeepCloner(const Function *F); 837 838 /// Create a new clone of the scoped alias metadata, which will be used by 839 /// subsequent remap() calls. 840 void clone(); 841 842 /// Remap instructions in the given range from the original to the cloned 843 /// metadata. 844 void remap(Function::iterator FStart, Function::iterator FEnd); 845 }; 846 847 ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner( 848 const Function *F) { 849 for (const BasicBlock &BB : *F) { 850 for (const Instruction &I : BB) { 851 if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) 852 MD.insert(M); 853 if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) 854 MD.insert(M); 855 856 // We also need to clone the metadata in noalias intrinsics. 857 if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 858 MD.insert(Decl->getScopeList()); 859 } 860 } 861 addRecursiveMetadataUses(); 862 } 863 864 void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() { 865 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end()); 866 while (!Queue.empty()) { 867 const MDNode *M = cast<MDNode>(Queue.pop_back_val()); 868 for (const Metadata *Op : M->operands()) 869 if (const MDNode *OpMD = dyn_cast<MDNode>(Op)) 870 if (MD.insert(OpMD)) 871 Queue.push_back(OpMD); 872 } 873 } 874 875 void ScopedAliasMetadataDeepCloner::clone() { 876 assert(MDMap.empty() && "clone() already called ?"); 877 878 SmallVector<TempMDTuple, 16> DummyNodes; 879 for (const MDNode *I : MD) { 880 DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), None)); 881 MDMap[I].reset(DummyNodes.back().get()); 882 } 883 884 // Create new metadata nodes to replace the dummy nodes, replacing old 885 // metadata references with either a dummy node or an already-created new 886 // node. 887 SmallVector<Metadata *, 4> NewOps; 888 for (const MDNode *I : MD) { 889 for (const Metadata *Op : I->operands()) { 890 if (const MDNode *M = dyn_cast<MDNode>(Op)) 891 NewOps.push_back(MDMap[M]); 892 else 893 NewOps.push_back(const_cast<Metadata *>(Op)); 894 } 895 896 MDNode *NewM = MDNode::get(I->getContext(), NewOps); 897 MDTuple *TempM = cast<MDTuple>(MDMap[I]); 898 assert(TempM->isTemporary() && "Expected temporary node"); 899 900 TempM->replaceAllUsesWith(NewM); 901 NewOps.clear(); 902 } 903 } 904 905 void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart, 906 Function::iterator FEnd) { 907 if (MDMap.empty()) 908 return; // Nothing to do. 909 910 for (BasicBlock &BB : make_range(FStart, FEnd)) { 911 for (Instruction &I : BB) { 912 // TODO: The null checks for the MDMap.lookup() results should no longer 913 // be necessary. 914 if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) 915 if (MDNode *MNew = MDMap.lookup(M)) 916 I.setMetadata(LLVMContext::MD_alias_scope, MNew); 917 918 if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) 919 if (MDNode *MNew = MDMap.lookup(M)) 920 I.setMetadata(LLVMContext::MD_noalias, MNew); 921 922 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 923 if (MDNode *MNew = MDMap.lookup(Decl->getScopeList())) 924 Decl->setScopeList(MNew); 925 } 926 } 927 } 928 929 /// If the inlined function has noalias arguments, 930 /// then add new alias scopes for each noalias argument, tag the mapped noalias 931 /// parameters with noalias metadata specifying the new scope, and tag all 932 /// non-derived loads, stores and memory intrinsics with the new alias scopes. 933 static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap, 934 const DataLayout &DL, AAResults *CalleeAAR) { 935 if (!EnableNoAliasConversion) 936 return; 937 938 const Function *CalledFunc = CB.getCalledFunction(); 939 SmallVector<const Argument *, 4> NoAliasArgs; 940 941 for (const Argument &Arg : CalledFunc->args()) 942 if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty()) 943 NoAliasArgs.push_back(&Arg); 944 945 if (NoAliasArgs.empty()) 946 return; 947 948 // To do a good job, if a noalias variable is captured, we need to know if 949 // the capture point dominates the particular use we're considering. 950 DominatorTree DT; 951 DT.recalculate(const_cast<Function&>(*CalledFunc)); 952 953 // noalias indicates that pointer values based on the argument do not alias 954 // pointer values which are not based on it. So we add a new "scope" for each 955 // noalias function argument. Accesses using pointers based on that argument 956 // become part of that alias scope, accesses using pointers not based on that 957 // argument are tagged as noalias with that scope. 958 959 DenseMap<const Argument *, MDNode *> NewScopes; 960 MDBuilder MDB(CalledFunc->getContext()); 961 962 // Create a new scope domain for this function. 963 MDNode *NewDomain = 964 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName()); 965 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) { 966 const Argument *A = NoAliasArgs[i]; 967 968 std::string Name = std::string(CalledFunc->getName()); 969 if (A->hasName()) { 970 Name += ": %"; 971 Name += A->getName(); 972 } else { 973 Name += ": argument "; 974 Name += utostr(i); 975 } 976 977 // Note: We always create a new anonymous root here. This is true regardless 978 // of the linkage of the callee because the aliasing "scope" is not just a 979 // property of the callee, but also all control dependencies in the caller. 980 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name); 981 NewScopes.insert(std::make_pair(A, NewScope)); 982 983 if (UseNoAliasIntrinsic) { 984 // Introduce a llvm.experimental.noalias.scope.decl for the noalias 985 // argument. 986 MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope); 987 auto *NoAliasDecl = 988 IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList); 989 // Ignore the result for now. The result will be used when the 990 // llvm.noalias intrinsic is introduced. 991 (void)NoAliasDecl; 992 } 993 } 994 995 // Iterate over all new instructions in the map; for all memory-access 996 // instructions, add the alias scope metadata. 997 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end(); 998 VMI != VMIE; ++VMI) { 999 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) { 1000 if (!VMI->second) 1001 continue; 1002 1003 Instruction *NI = dyn_cast<Instruction>(VMI->second); 1004 if (!NI) 1005 continue; 1006 1007 bool IsArgMemOnlyCall = false, IsFuncCall = false; 1008 SmallVector<const Value *, 2> PtrArgs; 1009 1010 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) 1011 PtrArgs.push_back(LI->getPointerOperand()); 1012 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) 1013 PtrArgs.push_back(SI->getPointerOperand()); 1014 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I)) 1015 PtrArgs.push_back(VAAI->getPointerOperand()); 1016 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I)) 1017 PtrArgs.push_back(CXI->getPointerOperand()); 1018 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) 1019 PtrArgs.push_back(RMWI->getPointerOperand()); 1020 else if (const auto *Call = dyn_cast<CallBase>(I)) { 1021 // If we know that the call does not access memory, then we'll still 1022 // know that about the inlined clone of this call site, and we don't 1023 // need to add metadata. 1024 if (Call->doesNotAccessMemory()) 1025 continue; 1026 1027 IsFuncCall = true; 1028 if (CalleeAAR) { 1029 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call); 1030 1031 // We'll retain this knowledge without additional metadata. 1032 if (AAResults::onlyAccessesInaccessibleMem(MRB)) 1033 continue; 1034 1035 if (AAResults::onlyAccessesArgPointees(MRB)) 1036 IsArgMemOnlyCall = true; 1037 } 1038 1039 for (Value *Arg : Call->args()) { 1040 // We need to check the underlying objects of all arguments, not just 1041 // the pointer arguments, because we might be passing pointers as 1042 // integers, etc. 1043 // However, if we know that the call only accesses pointer arguments, 1044 // then we only need to check the pointer arguments. 1045 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy()) 1046 continue; 1047 1048 PtrArgs.push_back(Arg); 1049 } 1050 } 1051 1052 // If we found no pointers, then this instruction is not suitable for 1053 // pairing with an instruction to receive aliasing metadata. 1054 // However, if this is a call, this we might just alias with none of the 1055 // noalias arguments. 1056 if (PtrArgs.empty() && !IsFuncCall) 1057 continue; 1058 1059 // It is possible that there is only one underlying object, but you 1060 // need to go through several PHIs to see it, and thus could be 1061 // repeated in the Objects list. 1062 SmallPtrSet<const Value *, 4> ObjSet; 1063 SmallVector<Metadata *, 4> Scopes, NoAliases; 1064 1065 SmallSetVector<const Argument *, 4> NAPtrArgs; 1066 for (const Value *V : PtrArgs) { 1067 SmallVector<const Value *, 4> Objects; 1068 getUnderlyingObjects(V, Objects, /* LI = */ nullptr); 1069 1070 for (const Value *O : Objects) 1071 ObjSet.insert(O); 1072 } 1073 1074 // Figure out if we're derived from anything that is not a noalias 1075 // argument. 1076 bool CanDeriveViaCapture = false, UsesAliasingPtr = false; 1077 for (const Value *V : ObjSet) { 1078 // Is this value a constant that cannot be derived from any pointer 1079 // value (we need to exclude constant expressions, for example, that 1080 // are formed from arithmetic on global symbols). 1081 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) || 1082 isa<ConstantPointerNull>(V) || 1083 isa<ConstantDataVector>(V) || isa<UndefValue>(V); 1084 if (IsNonPtrConst) 1085 continue; 1086 1087 // If this is anything other than a noalias argument, then we cannot 1088 // completely describe the aliasing properties using alias.scope 1089 // metadata (and, thus, won't add any). 1090 if (const Argument *A = dyn_cast<Argument>(V)) { 1091 if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias)) 1092 UsesAliasingPtr = true; 1093 } else { 1094 UsesAliasingPtr = true; 1095 } 1096 1097 // If this is not some identified function-local object (which cannot 1098 // directly alias a noalias argument), or some other argument (which, 1099 // by definition, also cannot alias a noalias argument), then we could 1100 // alias a noalias argument that has been captured). 1101 if (!isa<Argument>(V) && 1102 !isIdentifiedFunctionLocal(const_cast<Value*>(V))) 1103 CanDeriveViaCapture = true; 1104 } 1105 1106 // A function call can always get captured noalias pointers (via other 1107 // parameters, globals, etc.). 1108 if (IsFuncCall && !IsArgMemOnlyCall) 1109 CanDeriveViaCapture = true; 1110 1111 // First, we want to figure out all of the sets with which we definitely 1112 // don't alias. Iterate over all noalias set, and add those for which: 1113 // 1. The noalias argument is not in the set of objects from which we 1114 // definitely derive. 1115 // 2. The noalias argument has not yet been captured. 1116 // An arbitrary function that might load pointers could see captured 1117 // noalias arguments via other noalias arguments or globals, and so we 1118 // must always check for prior capture. 1119 for (const Argument *A : NoAliasArgs) { 1120 if (!ObjSet.count(A) && (!CanDeriveViaCapture || 1121 // It might be tempting to skip the 1122 // PointerMayBeCapturedBefore check if 1123 // A->hasNoCaptureAttr() is true, but this is 1124 // incorrect because nocapture only guarantees 1125 // that no copies outlive the function, not 1126 // that the value cannot be locally captured. 1127 !PointerMayBeCapturedBefore(A, 1128 /* ReturnCaptures */ false, 1129 /* StoreCaptures */ false, I, &DT))) 1130 NoAliases.push_back(NewScopes[A]); 1131 } 1132 1133 if (!NoAliases.empty()) 1134 NI->setMetadata(LLVMContext::MD_noalias, 1135 MDNode::concatenate( 1136 NI->getMetadata(LLVMContext::MD_noalias), 1137 MDNode::get(CalledFunc->getContext(), NoAliases))); 1138 1139 // Next, we want to figure out all of the sets to which we might belong. 1140 // We might belong to a set if the noalias argument is in the set of 1141 // underlying objects. If there is some non-noalias argument in our list 1142 // of underlying objects, then we cannot add a scope because the fact 1143 // that some access does not alias with any set of our noalias arguments 1144 // cannot itself guarantee that it does not alias with this access 1145 // (because there is some pointer of unknown origin involved and the 1146 // other access might also depend on this pointer). We also cannot add 1147 // scopes to arbitrary functions unless we know they don't access any 1148 // non-parameter pointer-values. 1149 bool CanAddScopes = !UsesAliasingPtr; 1150 if (CanAddScopes && IsFuncCall) 1151 CanAddScopes = IsArgMemOnlyCall; 1152 1153 if (CanAddScopes) 1154 for (const Argument *A : NoAliasArgs) { 1155 if (ObjSet.count(A)) 1156 Scopes.push_back(NewScopes[A]); 1157 } 1158 1159 if (!Scopes.empty()) 1160 NI->setMetadata( 1161 LLVMContext::MD_alias_scope, 1162 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope), 1163 MDNode::get(CalledFunc->getContext(), Scopes))); 1164 } 1165 } 1166 } 1167 1168 static bool MayContainThrowingOrExitingCall(Instruction *Begin, 1169 Instruction *End) { 1170 1171 assert(Begin->getParent() == End->getParent() && 1172 "Expected to be in same basic block!"); 1173 unsigned NumInstChecked = 0; 1174 // Check that all instructions in the range [Begin, End) are guaranteed to 1175 // transfer execution to successor. 1176 for (auto &I : make_range(Begin->getIterator(), End->getIterator())) 1177 if (NumInstChecked++ > InlinerAttributeWindow || 1178 !isGuaranteedToTransferExecutionToSuccessor(&I)) 1179 return true; 1180 return false; 1181 } 1182 1183 static AttrBuilder IdentifyValidAttributes(CallBase &CB) { 1184 1185 AttrBuilder AB(CB.getAttributes(), AttributeList::ReturnIndex); 1186 if (AB.empty()) 1187 return AB; 1188 AttrBuilder Valid; 1189 // Only allow these white listed attributes to be propagated back to the 1190 // callee. This is because other attributes may only be valid on the call 1191 // itself, i.e. attributes such as signext and zeroext. 1192 if (auto DerefBytes = AB.getDereferenceableBytes()) 1193 Valid.addDereferenceableAttr(DerefBytes); 1194 if (auto DerefOrNullBytes = AB.getDereferenceableOrNullBytes()) 1195 Valid.addDereferenceableOrNullAttr(DerefOrNullBytes); 1196 if (AB.contains(Attribute::NoAlias)) 1197 Valid.addAttribute(Attribute::NoAlias); 1198 if (AB.contains(Attribute::NonNull)) 1199 Valid.addAttribute(Attribute::NonNull); 1200 return Valid; 1201 } 1202 1203 static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) { 1204 if (!UpdateReturnAttributes) 1205 return; 1206 1207 AttrBuilder Valid = IdentifyValidAttributes(CB); 1208 if (Valid.empty()) 1209 return; 1210 auto *CalledFunction = CB.getCalledFunction(); 1211 auto &Context = CalledFunction->getContext(); 1212 1213 for (auto &BB : *CalledFunction) { 1214 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()); 1215 if (!RI || !isa<CallBase>(RI->getOperand(0))) 1216 continue; 1217 auto *RetVal = cast<CallBase>(RI->getOperand(0)); 1218 // Sanity check that the cloned RetVal exists and is a call, otherwise we 1219 // cannot add the attributes on the cloned RetVal. 1220 // Simplification during inlining could have transformed the cloned 1221 // instruction. 1222 auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal)); 1223 if (!NewRetVal) 1224 continue; 1225 // Backward propagation of attributes to the returned value may be incorrect 1226 // if it is control flow dependent. 1227 // Consider: 1228 // @callee { 1229 // %rv = call @foo() 1230 // %rv2 = call @bar() 1231 // if (%rv2 != null) 1232 // return %rv2 1233 // if (%rv == null) 1234 // exit() 1235 // return %rv 1236 // } 1237 // caller() { 1238 // %val = call nonnull @callee() 1239 // } 1240 // Here we cannot add the nonnull attribute on either foo or bar. So, we 1241 // limit the check to both RetVal and RI are in the same basic block and 1242 // there are no throwing/exiting instructions between these instructions. 1243 if (RI->getParent() != RetVal->getParent() || 1244 MayContainThrowingOrExitingCall(RetVal, RI)) 1245 continue; 1246 // Add to the existing attributes of NewRetVal, i.e. the cloned call 1247 // instruction. 1248 // NB! When we have the same attribute already existing on NewRetVal, but 1249 // with a differing value, the AttributeList's merge API honours the already 1250 // existing attribute value (i.e. attributes such as dereferenceable, 1251 // dereferenceable_or_null etc). See AttrBuilder::merge for more details. 1252 AttributeList AL = NewRetVal->getAttributes(); 1253 AttributeList NewAL = 1254 AL.addAttributes(Context, AttributeList::ReturnIndex, Valid); 1255 NewRetVal->setAttributes(NewAL); 1256 } 1257 } 1258 1259 /// If the inlined function has non-byval align arguments, then 1260 /// add @llvm.assume-based alignment assumptions to preserve this information. 1261 static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) { 1262 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache) 1263 return; 1264 1265 AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller()); 1266 auto &DL = CB.getCaller()->getParent()->getDataLayout(); 1267 1268 // To avoid inserting redundant assumptions, we should check for assumptions 1269 // already in the caller. To do this, we might need a DT of the caller. 1270 DominatorTree DT; 1271 bool DTCalculated = false; 1272 1273 Function *CalledFunc = CB.getCalledFunction(); 1274 for (Argument &Arg : CalledFunc->args()) { 1275 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0; 1276 if (Align && !Arg.hasPassPointeeByValueCopyAttr() && !Arg.hasNUses(0)) { 1277 if (!DTCalculated) { 1278 DT.recalculate(*CB.getCaller()); 1279 DTCalculated = true; 1280 } 1281 1282 // If we can already prove the asserted alignment in the context of the 1283 // caller, then don't bother inserting the assumption. 1284 Value *ArgVal = CB.getArgOperand(Arg.getArgNo()); 1285 if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= Align) 1286 continue; 1287 1288 CallInst *NewAsmp = 1289 IRBuilder<>(&CB).CreateAlignmentAssumption(DL, ArgVal, Align); 1290 AC->registerAssumption(cast<AssumeInst>(NewAsmp)); 1291 } 1292 } 1293 } 1294 1295 /// Once we have cloned code over from a callee into the caller, 1296 /// update the specified callgraph to reflect the changes we made. 1297 /// Note that it's possible that not all code was copied over, so only 1298 /// some edges of the callgraph may remain. 1299 static void UpdateCallGraphAfterInlining(CallBase &CB, 1300 Function::iterator FirstNewBlock, 1301 ValueToValueMapTy &VMap, 1302 InlineFunctionInfo &IFI) { 1303 CallGraph &CG = *IFI.CG; 1304 const Function *Caller = CB.getCaller(); 1305 const Function *Callee = CB.getCalledFunction(); 1306 CallGraphNode *CalleeNode = CG[Callee]; 1307 CallGraphNode *CallerNode = CG[Caller]; 1308 1309 // Since we inlined some uninlined call sites in the callee into the caller, 1310 // add edges from the caller to all of the callees of the callee. 1311 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end(); 1312 1313 // Consider the case where CalleeNode == CallerNode. 1314 CallGraphNode::CalledFunctionsVector CallCache; 1315 if (CalleeNode == CallerNode) { 1316 CallCache.assign(I, E); 1317 I = CallCache.begin(); 1318 E = CallCache.end(); 1319 } 1320 1321 for (; I != E; ++I) { 1322 // Skip 'refererence' call records. 1323 if (!I->first) 1324 continue; 1325 1326 const Value *OrigCall = *I->first; 1327 1328 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall); 1329 // Only copy the edge if the call was inlined! 1330 if (VMI == VMap.end() || VMI->second == nullptr) 1331 continue; 1332 1333 // If the call was inlined, but then constant folded, there is no edge to 1334 // add. Check for this case. 1335 auto *NewCall = dyn_cast<CallBase>(VMI->second); 1336 if (!NewCall) 1337 continue; 1338 1339 // We do not treat intrinsic calls like real function calls because we 1340 // expect them to become inline code; do not add an edge for an intrinsic. 1341 if (NewCall->getCalledFunction() && 1342 NewCall->getCalledFunction()->isIntrinsic()) 1343 continue; 1344 1345 // Remember that this call site got inlined for the client of 1346 // InlineFunction. 1347 IFI.InlinedCalls.push_back(NewCall); 1348 1349 // It's possible that inlining the callsite will cause it to go from an 1350 // indirect to a direct call by resolving a function pointer. If this 1351 // happens, set the callee of the new call site to a more precise 1352 // destination. This can also happen if the call graph node of the caller 1353 // was just unnecessarily imprecise. 1354 if (!I->second->getFunction()) 1355 if (Function *F = NewCall->getCalledFunction()) { 1356 // Indirect call site resolved to direct call. 1357 CallerNode->addCalledFunction(NewCall, CG[F]); 1358 1359 continue; 1360 } 1361 1362 CallerNode->addCalledFunction(NewCall, I->second); 1363 } 1364 1365 // Update the call graph by deleting the edge from Callee to Caller. We must 1366 // do this after the loop above in case Caller and Callee are the same. 1367 CallerNode->removeCallEdgeFor(*cast<CallBase>(&CB)); 1368 } 1369 1370 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M, 1371 BasicBlock *InsertBlock, 1372 InlineFunctionInfo &IFI) { 1373 Type *AggTy = cast<PointerType>(Src->getType())->getElementType(); 1374 IRBuilder<> Builder(InsertBlock, InsertBlock->begin()); 1375 1376 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy)); 1377 1378 // Always generate a memcpy of alignment 1 here because we don't know 1379 // the alignment of the src pointer. Other optimizations can infer 1380 // better alignment. 1381 Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src, 1382 /*SrcAlign*/ Align(1), Size); 1383 } 1384 1385 /// When inlining a call site that has a byval argument, 1386 /// we have to make the implicit memcpy explicit by adding it. 1387 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall, 1388 const Function *CalledFunc, 1389 InlineFunctionInfo &IFI, 1390 unsigned ByValAlignment) { 1391 PointerType *ArgTy = cast<PointerType>(Arg->getType()); 1392 Type *AggTy = ArgTy->getElementType(); 1393 1394 Function *Caller = TheCall->getFunction(); 1395 const DataLayout &DL = Caller->getParent()->getDataLayout(); 1396 1397 // If the called function is readonly, then it could not mutate the caller's 1398 // copy of the byval'd memory. In this case, it is safe to elide the copy and 1399 // temporary. 1400 if (CalledFunc->onlyReadsMemory()) { 1401 // If the byval argument has a specified alignment that is greater than the 1402 // passed in pointer, then we either have to round up the input pointer or 1403 // give up on this transformation. 1404 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment. 1405 return Arg; 1406 1407 AssumptionCache *AC = 1408 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 1409 1410 // If the pointer is already known to be sufficiently aligned, or if we can 1411 // round it up to a larger alignment, then we don't need a temporary. 1412 if (getOrEnforceKnownAlignment(Arg, Align(ByValAlignment), DL, TheCall, 1413 AC) >= ByValAlignment) 1414 return Arg; 1415 1416 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad 1417 // for code quality, but rarely happens and is required for correctness. 1418 } 1419 1420 // Create the alloca. If we have DataLayout, use nice alignment. 1421 Align Alignment(DL.getPrefTypeAlignment(AggTy)); 1422 1423 // If the byval had an alignment specified, we *must* use at least that 1424 // alignment, as it is required by the byval argument (and uses of the 1425 // pointer inside the callee). 1426 Alignment = max(Alignment, MaybeAlign(ByValAlignment)); 1427 1428 Value *NewAlloca = 1429 new AllocaInst(AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment, 1430 Arg->getName(), &*Caller->begin()->begin()); 1431 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca)); 1432 1433 // Uses of the argument in the function should use our new alloca 1434 // instead. 1435 return NewAlloca; 1436 } 1437 1438 // Check whether this Value is used by a lifetime intrinsic. 1439 static bool isUsedByLifetimeMarker(Value *V) { 1440 for (User *U : V->users()) 1441 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) 1442 if (II->isLifetimeStartOrEnd()) 1443 return true; 1444 return false; 1445 } 1446 1447 // Check whether the given alloca already has 1448 // lifetime.start or lifetime.end intrinsics. 1449 static bool hasLifetimeMarkers(AllocaInst *AI) { 1450 Type *Ty = AI->getType(); 1451 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(), 1452 Ty->getPointerAddressSpace()); 1453 if (Ty == Int8PtrTy) 1454 return isUsedByLifetimeMarker(AI); 1455 1456 // Do a scan to find all the casts to i8*. 1457 for (User *U : AI->users()) { 1458 if (U->getType() != Int8PtrTy) continue; 1459 if (U->stripPointerCasts() != AI) continue; 1460 if (isUsedByLifetimeMarker(U)) 1461 return true; 1462 } 1463 return false; 1464 } 1465 1466 /// Return the result of AI->isStaticAlloca() if AI were moved to the entry 1467 /// block. Allocas used in inalloca calls and allocas of dynamic array size 1468 /// cannot be static. 1469 static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) { 1470 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca(); 1471 } 1472 1473 /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL 1474 /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache. 1475 static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt, 1476 LLVMContext &Ctx, 1477 DenseMap<const MDNode *, MDNode *> &IANodes) { 1478 auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes); 1479 return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(), 1480 OrigDL.getScope(), IA); 1481 } 1482 1483 /// Update inlined instructions' line numbers to 1484 /// to encode location where these instructions are inlined. 1485 static void fixupLineNumbers(Function *Fn, Function::iterator FI, 1486 Instruction *TheCall, bool CalleeHasDebugInfo) { 1487 const DebugLoc &TheCallDL = TheCall->getDebugLoc(); 1488 if (!TheCallDL) 1489 return; 1490 1491 auto &Ctx = Fn->getContext(); 1492 DILocation *InlinedAtNode = TheCallDL; 1493 1494 // Create a unique call site, not to be confused with any other call from the 1495 // same location. 1496 InlinedAtNode = DILocation::getDistinct( 1497 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(), 1498 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt()); 1499 1500 // Cache the inlined-at nodes as they're built so they are reused, without 1501 // this every instruction's inlined-at chain would become distinct from each 1502 // other. 1503 DenseMap<const MDNode *, MDNode *> IANodes; 1504 1505 // Check if we are not generating inline line tables and want to use 1506 // the call site location instead. 1507 bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables"); 1508 1509 for (; FI != Fn->end(); ++FI) { 1510 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); 1511 BI != BE; ++BI) { 1512 // Loop metadata needs to be updated so that the start and end locs 1513 // reference inlined-at locations. 1514 auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes]( 1515 const DILocation &Loc) -> DILocation * { 1516 return inlineDebugLoc(&Loc, InlinedAtNode, Ctx, IANodes).get(); 1517 }; 1518 updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc); 1519 1520 if (!NoInlineLineTables) 1521 if (DebugLoc DL = BI->getDebugLoc()) { 1522 DebugLoc IDL = 1523 inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes); 1524 BI->setDebugLoc(IDL); 1525 continue; 1526 } 1527 1528 if (CalleeHasDebugInfo && !NoInlineLineTables) 1529 continue; 1530 1531 // If the inlined instruction has no line number, or if inline info 1532 // is not being generated, make it look as if it originates from the call 1533 // location. This is important for ((__always_inline, __nodebug__)) 1534 // functions which must use caller location for all instructions in their 1535 // function body. 1536 1537 // Don't update static allocas, as they may get moved later. 1538 if (auto *AI = dyn_cast<AllocaInst>(BI)) 1539 if (allocaWouldBeStaticInEntry(AI)) 1540 continue; 1541 1542 BI->setDebugLoc(TheCallDL); 1543 } 1544 1545 // Remove debug info intrinsics if we're not keeping inline info. 1546 if (NoInlineLineTables) { 1547 BasicBlock::iterator BI = FI->begin(); 1548 while (BI != FI->end()) { 1549 if (isa<DbgInfoIntrinsic>(BI)) { 1550 BI = BI->eraseFromParent(); 1551 continue; 1552 } 1553 ++BI; 1554 } 1555 } 1556 1557 } 1558 } 1559 1560 /// Update the block frequencies of the caller after a callee has been inlined. 1561 /// 1562 /// Each block cloned into the caller has its block frequency scaled by the 1563 /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of 1564 /// callee's entry block gets the same frequency as the callsite block and the 1565 /// relative frequencies of all cloned blocks remain the same after cloning. 1566 static void updateCallerBFI(BasicBlock *CallSiteBlock, 1567 const ValueToValueMapTy &VMap, 1568 BlockFrequencyInfo *CallerBFI, 1569 BlockFrequencyInfo *CalleeBFI, 1570 const BasicBlock &CalleeEntryBlock) { 1571 SmallPtrSet<BasicBlock *, 16> ClonedBBs; 1572 for (auto Entry : VMap) { 1573 if (!isa<BasicBlock>(Entry.first) || !Entry.second) 1574 continue; 1575 auto *OrigBB = cast<BasicBlock>(Entry.first); 1576 auto *ClonedBB = cast<BasicBlock>(Entry.second); 1577 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency(); 1578 if (!ClonedBBs.insert(ClonedBB).second) { 1579 // Multiple blocks in the callee might get mapped to one cloned block in 1580 // the caller since we prune the callee as we clone it. When that happens, 1581 // we want to use the maximum among the original blocks' frequencies. 1582 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency(); 1583 if (NewFreq > Freq) 1584 Freq = NewFreq; 1585 } 1586 CallerBFI->setBlockFreq(ClonedBB, Freq); 1587 } 1588 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock)); 1589 CallerBFI->setBlockFreqAndScale( 1590 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(), 1591 ClonedBBs); 1592 } 1593 1594 /// Update the branch metadata for cloned call instructions. 1595 static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, 1596 const ProfileCount &CalleeEntryCount, 1597 const CallBase &TheCall, ProfileSummaryInfo *PSI, 1598 BlockFrequencyInfo *CallerBFI) { 1599 if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() || 1600 CalleeEntryCount.getCount() < 1) 1601 return; 1602 auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None; 1603 int64_t CallCount = 1604 std::min(CallSiteCount.getValueOr(0), CalleeEntryCount.getCount()); 1605 updateProfileCallee(Callee, -CallCount, &VMap); 1606 } 1607 1608 void llvm::updateProfileCallee( 1609 Function *Callee, int64_t entryDelta, 1610 const ValueMap<const Value *, WeakTrackingVH> *VMap) { 1611 auto CalleeCount = Callee->getEntryCount(); 1612 if (!CalleeCount.hasValue()) 1613 return; 1614 1615 uint64_t priorEntryCount = CalleeCount.getCount(); 1616 uint64_t newEntryCount; 1617 1618 // Since CallSiteCount is an estimate, it could exceed the original callee 1619 // count and has to be set to 0 so guard against underflow. 1620 if (entryDelta < 0 && static_cast<uint64_t>(-entryDelta) > priorEntryCount) 1621 newEntryCount = 0; 1622 else 1623 newEntryCount = priorEntryCount + entryDelta; 1624 1625 // During inlining ? 1626 if (VMap) { 1627 uint64_t cloneEntryCount = priorEntryCount - newEntryCount; 1628 for (auto Entry : *VMap) 1629 if (isa<CallInst>(Entry.first)) 1630 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second)) 1631 CI->updateProfWeight(cloneEntryCount, priorEntryCount); 1632 } 1633 1634 if (entryDelta) { 1635 Callee->setEntryCount(newEntryCount); 1636 1637 for (BasicBlock &BB : *Callee) 1638 // No need to update the callsite if it is pruned during inlining. 1639 if (!VMap || VMap->count(&BB)) 1640 for (Instruction &I : BB) 1641 if (CallInst *CI = dyn_cast<CallInst>(&I)) 1642 CI->updateProfWeight(newEntryCount, priorEntryCount); 1643 } 1644 } 1645 1646 /// An operand bundle "clang.arc.attachedcall" on a call indicates the call 1647 /// result is implicitly consumed by a call to retainRV or claimRV immediately 1648 /// after the call. This function inlines the retainRV/claimRV calls. 1649 /// 1650 /// There are three cases to consider: 1651 /// 1652 /// 1. If there is a call to autoreleaseRV that takes a pointer to the returned 1653 /// object in the callee return block, the autoreleaseRV call and the 1654 /// retainRV/claimRV call in the caller cancel out. If the call in the caller 1655 /// is a claimRV call, a call to objc_release is emitted. 1656 /// 1657 /// 2. If there is a call in the callee return block that doesn't have operand 1658 /// bundle "clang.arc.attachedcall", the operand bundle on the original call 1659 /// is transferred to the call in the callee. 1660 /// 1661 /// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is 1662 /// a retainRV call. 1663 static void 1664 inlineRetainOrClaimRVCalls(CallBase &CB, 1665 const SmallVectorImpl<ReturnInst *> &Returns) { 1666 Module *Mod = CB.getModule(); 1667 bool IsRetainRV = objcarc::hasAttachedCallOpBundle(&CB, true), 1668 IsClaimRV = !IsRetainRV; 1669 1670 for (auto *RI : Returns) { 1671 Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0)); 1672 BasicBlock::reverse_iterator I = ++(RI->getIterator().getReverse()); 1673 BasicBlock::reverse_iterator EI = RI->getParent()->rend(); 1674 bool InsertRetainCall = IsRetainRV; 1675 IRBuilder<> Builder(RI->getContext()); 1676 1677 // Walk backwards through the basic block looking for either a matching 1678 // autoreleaseRV call or an unannotated call. 1679 for (; I != EI;) { 1680 auto CurI = I++; 1681 1682 // Ignore casts. 1683 if (isa<CastInst>(*CurI)) 1684 continue; 1685 1686 if (auto *II = dyn_cast<IntrinsicInst>(&*CurI)) { 1687 if (II->getIntrinsicID() == Intrinsic::objc_autoreleaseReturnValue && 1688 II->hasNUses(0) && 1689 objcarc::GetRCIdentityRoot(II->getOperand(0)) == RetOpnd) { 1690 // If we've found a matching authoreleaseRV call: 1691 // - If claimRV is attached to the call, insert a call to objc_release 1692 // and erase the autoreleaseRV call. 1693 // - If retainRV is attached to the call, just erase the autoreleaseRV 1694 // call. 1695 if (IsClaimRV) { 1696 Builder.SetInsertPoint(II); 1697 Function *IFn = 1698 Intrinsic::getDeclaration(Mod, Intrinsic::objc_release); 1699 Value *BC = 1700 Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType()); 1701 Builder.CreateCall(IFn, BC, ""); 1702 } 1703 II->eraseFromParent(); 1704 InsertRetainCall = false; 1705 } 1706 } else if (auto *CI = dyn_cast<CallInst>(&*CurI)) { 1707 if (objcarc::GetRCIdentityRoot(CI) == RetOpnd && 1708 !objcarc::hasAttachedCallOpBundle(CI)) { 1709 // If we've found an unannotated call that defines RetOpnd, add a 1710 // "clang.arc.attachedcall" operand bundle. 1711 Value *BundleArgs[] = {ConstantInt::get( 1712 Builder.getInt64Ty(), 1713 objcarc::getAttachedCallOperandBundleEnum(IsRetainRV))}; 1714 OperandBundleDef OB("clang.arc.attachedcall", BundleArgs); 1715 auto *NewCall = CallBase::addOperandBundle( 1716 CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI); 1717 NewCall->copyMetadata(*CI); 1718 CI->replaceAllUsesWith(NewCall); 1719 CI->eraseFromParent(); 1720 InsertRetainCall = false; 1721 } 1722 } 1723 1724 break; 1725 } 1726 1727 if (InsertRetainCall) { 1728 // The retainRV is attached to the call and we've failed to find a 1729 // matching autoreleaseRV or an annotated call in the callee. Emit a call 1730 // to objc_retain. 1731 Builder.SetInsertPoint(RI); 1732 Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_retain); 1733 Value *BC = Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType()); 1734 Builder.CreateCall(IFn, BC, ""); 1735 } 1736 } 1737 } 1738 1739 /// This function inlines the called function into the basic block of the 1740 /// caller. This returns false if it is not possible to inline this call. 1741 /// The program is still in a well defined state if this occurs though. 1742 /// 1743 /// Note that this only does one level of inlining. For example, if the 1744 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now 1745 /// exists in the instruction stream. Similarly this will inline a recursive 1746 /// function by one level. 1747 llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, 1748 AAResults *CalleeAAR, 1749 bool InsertLifetime, 1750 Function *ForwardVarArgsTo) { 1751 assert(CB.getParent() && CB.getFunction() && "Instruction not in function!"); 1752 1753 // FIXME: we don't inline callbr yet. 1754 if (isa<CallBrInst>(CB)) 1755 return InlineResult::failure("We don't inline callbr yet."); 1756 1757 // If IFI has any state in it, zap it before we fill it in. 1758 IFI.reset(); 1759 1760 Function *CalledFunc = CB.getCalledFunction(); 1761 if (!CalledFunc || // Can't inline external function or indirect 1762 CalledFunc->isDeclaration()) // call! 1763 return InlineResult::failure("external or indirect"); 1764 1765 // The inliner does not know how to inline through calls with operand bundles 1766 // in general ... 1767 if (CB.hasOperandBundles()) { 1768 for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) { 1769 uint32_t Tag = CB.getOperandBundleAt(i).getTagID(); 1770 // ... but it knows how to inline through "deopt" operand bundles ... 1771 if (Tag == LLVMContext::OB_deopt) 1772 continue; 1773 // ... and "funclet" operand bundles. 1774 if (Tag == LLVMContext::OB_funclet) 1775 continue; 1776 if (Tag == LLVMContext::OB_clang_arc_attachedcall) 1777 continue; 1778 1779 return InlineResult::failure("unsupported operand bundle"); 1780 } 1781 } 1782 1783 // If the call to the callee cannot throw, set the 'nounwind' flag on any 1784 // calls that we inline. 1785 bool MarkNoUnwind = CB.doesNotThrow(); 1786 1787 BasicBlock *OrigBB = CB.getParent(); 1788 Function *Caller = OrigBB->getParent(); 1789 1790 // GC poses two hazards to inlining, which only occur when the callee has GC: 1791 // 1. If the caller has no GC, then the callee's GC must be propagated to the 1792 // caller. 1793 // 2. If the caller has a differing GC, it is invalid to inline. 1794 if (CalledFunc->hasGC()) { 1795 if (!Caller->hasGC()) 1796 Caller->setGC(CalledFunc->getGC()); 1797 else if (CalledFunc->getGC() != Caller->getGC()) 1798 return InlineResult::failure("incompatible GC"); 1799 } 1800 1801 // Get the personality function from the callee if it contains a landing pad. 1802 Constant *CalledPersonality = 1803 CalledFunc->hasPersonalityFn() 1804 ? CalledFunc->getPersonalityFn()->stripPointerCasts() 1805 : nullptr; 1806 1807 // Find the personality function used by the landing pads of the caller. If it 1808 // exists, then check to see that it matches the personality function used in 1809 // the callee. 1810 Constant *CallerPersonality = 1811 Caller->hasPersonalityFn() 1812 ? Caller->getPersonalityFn()->stripPointerCasts() 1813 : nullptr; 1814 if (CalledPersonality) { 1815 if (!CallerPersonality) 1816 Caller->setPersonalityFn(CalledPersonality); 1817 // If the personality functions match, then we can perform the 1818 // inlining. Otherwise, we can't inline. 1819 // TODO: This isn't 100% true. Some personality functions are proper 1820 // supersets of others and can be used in place of the other. 1821 else if (CalledPersonality != CallerPersonality) 1822 return InlineResult::failure("incompatible personality"); 1823 } 1824 1825 // We need to figure out which funclet the callsite was in so that we may 1826 // properly nest the callee. 1827 Instruction *CallSiteEHPad = nullptr; 1828 if (CallerPersonality) { 1829 EHPersonality Personality = classifyEHPersonality(CallerPersonality); 1830 if (isScopedEHPersonality(Personality)) { 1831 Optional<OperandBundleUse> ParentFunclet = 1832 CB.getOperandBundle(LLVMContext::OB_funclet); 1833 if (ParentFunclet) 1834 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front()); 1835 1836 // OK, the inlining site is legal. What about the target function? 1837 1838 if (CallSiteEHPad) { 1839 if (Personality == EHPersonality::MSVC_CXX) { 1840 // The MSVC personality cannot tolerate catches getting inlined into 1841 // cleanup funclets. 1842 if (isa<CleanupPadInst>(CallSiteEHPad)) { 1843 // Ok, the call site is within a cleanuppad. Let's check the callee 1844 // for catchpads. 1845 for (const BasicBlock &CalledBB : *CalledFunc) { 1846 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI())) 1847 return InlineResult::failure("catch in cleanup funclet"); 1848 } 1849 } 1850 } else if (isAsynchronousEHPersonality(Personality)) { 1851 // SEH is even less tolerant, there may not be any sort of exceptional 1852 // funclet in the callee. 1853 for (const BasicBlock &CalledBB : *CalledFunc) { 1854 if (CalledBB.isEHPad()) 1855 return InlineResult::failure("SEH in cleanup funclet"); 1856 } 1857 } 1858 } 1859 } 1860 } 1861 1862 // Determine if we are dealing with a call in an EHPad which does not unwind 1863 // to caller. 1864 bool EHPadForCallUnwindsLocally = false; 1865 if (CallSiteEHPad && isa<CallInst>(CB)) { 1866 UnwindDestMemoTy FuncletUnwindMap; 1867 Value *CallSiteUnwindDestToken = 1868 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap); 1869 1870 EHPadForCallUnwindsLocally = 1871 CallSiteUnwindDestToken && 1872 !isa<ConstantTokenNone>(CallSiteUnwindDestToken); 1873 } 1874 1875 // Get an iterator to the last basic block in the function, which will have 1876 // the new function inlined after it. 1877 Function::iterator LastBlock = --Caller->end(); 1878 1879 // Make sure to capture all of the return instructions from the cloned 1880 // function. 1881 SmallVector<ReturnInst*, 8> Returns; 1882 ClonedCodeInfo InlinedFunctionInfo; 1883 Function::iterator FirstNewBlock; 1884 1885 { // Scope to destroy VMap after cloning. 1886 ValueToValueMapTy VMap; 1887 // Keep a list of pair (dst, src) to emit byval initializations. 1888 SmallVector<std::pair<Value*, Value*>, 4> ByValInit; 1889 1890 // When inlining a function that contains noalias scope metadata, 1891 // this metadata needs to be cloned so that the inlined blocks 1892 // have different "unique scopes" at every call site. 1893 // Track the metadata that must be cloned. Do this before other changes to 1894 // the function, so that we do not get in trouble when inlining caller == 1895 // callee. 1896 ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction()); 1897 1898 auto &DL = Caller->getParent()->getDataLayout(); 1899 1900 // Calculate the vector of arguments to pass into the function cloner, which 1901 // matches up the formal to the actual argument values. 1902 auto AI = CB.arg_begin(); 1903 unsigned ArgNo = 0; 1904 for (Function::arg_iterator I = CalledFunc->arg_begin(), 1905 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) { 1906 Value *ActualArg = *AI; 1907 1908 // When byval arguments actually inlined, we need to make the copy implied 1909 // by them explicit. However, we don't do this if the callee is readonly 1910 // or readnone, because the copy would be unneeded: the callee doesn't 1911 // modify the struct. 1912 if (CB.isByValArgument(ArgNo)) { 1913 ActualArg = HandleByValArgument(ActualArg, &CB, CalledFunc, IFI, 1914 CalledFunc->getParamAlignment(ArgNo)); 1915 if (ActualArg != *AI) 1916 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI)); 1917 } 1918 1919 VMap[&*I] = ActualArg; 1920 } 1921 1922 // TODO: Remove this when users have been updated to the assume bundles. 1923 // Add alignment assumptions if necessary. We do this before the inlined 1924 // instructions are actually cloned into the caller so that we can easily 1925 // check what will be known at the start of the inlined code. 1926 AddAlignmentAssumptions(CB, IFI); 1927 1928 AssumptionCache *AC = 1929 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 1930 1931 /// Preserve all attributes on of the call and its parameters. 1932 salvageKnowledge(&CB, AC); 1933 1934 // We want the inliner to prune the code as it copies. We would LOVE to 1935 // have no dead or constant instructions leftover after inlining occurs 1936 // (which can happen, e.g., because an argument was constant), but we'll be 1937 // happy with whatever the cloner can do. 1938 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, 1939 /*ModuleLevelChanges=*/false, Returns, ".i", 1940 &InlinedFunctionInfo, &CB); 1941 // Remember the first block that is newly cloned over. 1942 FirstNewBlock = LastBlock; ++FirstNewBlock; 1943 1944 // Insert retainRV/clainRV runtime calls. 1945 if (objcarc::hasAttachedCallOpBundle(&CB)) 1946 inlineRetainOrClaimRVCalls(CB, Returns); 1947 1948 // Updated caller/callee profiles only when requested. For sample loader 1949 // inlining, the context-sensitive inlinee profile doesn't need to be 1950 // subtracted from callee profile, and the inlined clone also doesn't need 1951 // to be scaled based on call site count. 1952 if (IFI.UpdateProfile) { 1953 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr) 1954 // Update the BFI of blocks cloned into the caller. 1955 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI, 1956 CalledFunc->front()); 1957 1958 updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), CB, 1959 IFI.PSI, IFI.CallerBFI); 1960 } 1961 1962 // Inject byval arguments initialization. 1963 for (std::pair<Value*, Value*> &Init : ByValInit) 1964 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(), 1965 &*FirstNewBlock, IFI); 1966 1967 Optional<OperandBundleUse> ParentDeopt = 1968 CB.getOperandBundle(LLVMContext::OB_deopt); 1969 if (ParentDeopt) { 1970 SmallVector<OperandBundleDef, 2> OpDefs; 1971 1972 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) { 1973 CallBase *ICS = dyn_cast_or_null<CallBase>(VH); 1974 if (!ICS) 1975 continue; // instruction was DCE'd or RAUW'ed to undef 1976 1977 OpDefs.clear(); 1978 1979 OpDefs.reserve(ICS->getNumOperandBundles()); 1980 1981 for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe; 1982 ++COBi) { 1983 auto ChildOB = ICS->getOperandBundleAt(COBi); 1984 if (ChildOB.getTagID() != LLVMContext::OB_deopt) { 1985 // If the inlined call has other operand bundles, let them be 1986 OpDefs.emplace_back(ChildOB); 1987 continue; 1988 } 1989 1990 // It may be useful to separate this logic (of handling operand 1991 // bundles) out to a separate "policy" component if this gets crowded. 1992 // Prepend the parent's deoptimization continuation to the newly 1993 // inlined call's deoptimization continuation. 1994 std::vector<Value *> MergedDeoptArgs; 1995 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() + 1996 ChildOB.Inputs.size()); 1997 1998 llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs); 1999 llvm::append_range(MergedDeoptArgs, ChildOB.Inputs); 2000 2001 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs)); 2002 } 2003 2004 Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS); 2005 2006 // Note: the RAUW does the appropriate fixup in VMap, so we need to do 2007 // this even if the call returns void. 2008 ICS->replaceAllUsesWith(NewI); 2009 2010 VH = nullptr; 2011 ICS->eraseFromParent(); 2012 } 2013 } 2014 2015 // Update the callgraph if requested. 2016 if (IFI.CG) 2017 UpdateCallGraphAfterInlining(CB, FirstNewBlock, VMap, IFI); 2018 2019 // For 'nodebug' functions, the associated DISubprogram is always null. 2020 // Conservatively avoid propagating the callsite debug location to 2021 // instructions inlined from a function whose DISubprogram is not null. 2022 fixupLineNumbers(Caller, FirstNewBlock, &CB, 2023 CalledFunc->getSubprogram() != nullptr); 2024 2025 // Now clone the inlined noalias scope metadata. 2026 SAMetadataCloner.clone(); 2027 SAMetadataCloner.remap(FirstNewBlock, Caller->end()); 2028 2029 // Add noalias metadata if necessary. 2030 AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR); 2031 2032 // Clone return attributes on the callsite into the calls within the inlined 2033 // function which feed into its return value. 2034 AddReturnAttributes(CB, VMap); 2035 2036 // Propagate metadata on the callsite if necessary. 2037 PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end()); 2038 2039 // Register any cloned assumptions. 2040 if (IFI.GetAssumptionCache) 2041 for (BasicBlock &NewBlock : 2042 make_range(FirstNewBlock->getIterator(), Caller->end())) 2043 for (Instruction &I : NewBlock) 2044 if (auto *II = dyn_cast<AssumeInst>(&I)) 2045 IFI.GetAssumptionCache(*Caller).registerAssumption(II); 2046 } 2047 2048 // If there are any alloca instructions in the block that used to be the entry 2049 // block for the callee, move them to the entry block of the caller. First 2050 // calculate which instruction they should be inserted before. We insert the 2051 // instructions at the end of the current alloca list. 2052 { 2053 BasicBlock::iterator InsertPoint = Caller->begin()->begin(); 2054 for (BasicBlock::iterator I = FirstNewBlock->begin(), 2055 E = FirstNewBlock->end(); I != E; ) { 2056 AllocaInst *AI = dyn_cast<AllocaInst>(I++); 2057 if (!AI) continue; 2058 2059 // If the alloca is now dead, remove it. This often occurs due to code 2060 // specialization. 2061 if (AI->use_empty()) { 2062 AI->eraseFromParent(); 2063 continue; 2064 } 2065 2066 if (!allocaWouldBeStaticInEntry(AI)) 2067 continue; 2068 2069 // Keep track of the static allocas that we inline into the caller. 2070 IFI.StaticAllocas.push_back(AI); 2071 2072 // Scan for the block of allocas that we can move over, and move them 2073 // all at once. 2074 while (isa<AllocaInst>(I) && 2075 !cast<AllocaInst>(I)->use_empty() && 2076 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) { 2077 IFI.StaticAllocas.push_back(cast<AllocaInst>(I)); 2078 ++I; 2079 } 2080 2081 // Transfer all of the allocas over in a block. Using splice means 2082 // that the instructions aren't removed from the symbol table, then 2083 // reinserted. 2084 Caller->getEntryBlock().getInstList().splice( 2085 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I); 2086 } 2087 } 2088 2089 SmallVector<Value*,4> VarArgsToForward; 2090 SmallVector<AttributeSet, 4> VarArgsAttrs; 2091 for (unsigned i = CalledFunc->getFunctionType()->getNumParams(); 2092 i < CB.getNumArgOperands(); i++) { 2093 VarArgsToForward.push_back(CB.getArgOperand(i)); 2094 VarArgsAttrs.push_back(CB.getAttributes().getParamAttributes(i)); 2095 } 2096 2097 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false; 2098 if (InlinedFunctionInfo.ContainsCalls) { 2099 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None; 2100 if (CallInst *CI = dyn_cast<CallInst>(&CB)) 2101 CallSiteTailKind = CI->getTailCallKind(); 2102 2103 // For inlining purposes, the "notail" marker is the same as no marker. 2104 if (CallSiteTailKind == CallInst::TCK_NoTail) 2105 CallSiteTailKind = CallInst::TCK_None; 2106 2107 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; 2108 ++BB) { 2109 for (auto II = BB->begin(); II != BB->end();) { 2110 Instruction &I = *II++; 2111 CallInst *CI = dyn_cast<CallInst>(&I); 2112 if (!CI) 2113 continue; 2114 2115 // Forward varargs from inlined call site to calls to the 2116 // ForwardVarArgsTo function, if requested, and to musttail calls. 2117 if (!VarArgsToForward.empty() && 2118 ((ForwardVarArgsTo && 2119 CI->getCalledFunction() == ForwardVarArgsTo) || 2120 CI->isMustTailCall())) { 2121 // Collect attributes for non-vararg parameters. 2122 AttributeList Attrs = CI->getAttributes(); 2123 SmallVector<AttributeSet, 8> ArgAttrs; 2124 if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) { 2125 for (unsigned ArgNo = 0; 2126 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo) 2127 ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo)); 2128 } 2129 2130 // Add VarArg attributes. 2131 ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end()); 2132 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(), 2133 Attrs.getRetAttributes(), ArgAttrs); 2134 // Add VarArgs to existing parameters. 2135 SmallVector<Value *, 6> Params(CI->arg_operands()); 2136 Params.append(VarArgsToForward.begin(), VarArgsToForward.end()); 2137 CallInst *NewCI = CallInst::Create( 2138 CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI); 2139 NewCI->setDebugLoc(CI->getDebugLoc()); 2140 NewCI->setAttributes(Attrs); 2141 NewCI->setCallingConv(CI->getCallingConv()); 2142 CI->replaceAllUsesWith(NewCI); 2143 CI->eraseFromParent(); 2144 CI = NewCI; 2145 } 2146 2147 if (Function *F = CI->getCalledFunction()) 2148 InlinedDeoptimizeCalls |= 2149 F->getIntrinsicID() == Intrinsic::experimental_deoptimize; 2150 2151 // We need to reduce the strength of any inlined tail calls. For 2152 // musttail, we have to avoid introducing potential unbounded stack 2153 // growth. For example, if functions 'f' and 'g' are mutually recursive 2154 // with musttail, we can inline 'g' into 'f' so long as we preserve 2155 // musttail on the cloned call to 'f'. If either the inlined call site 2156 // or the cloned call site is *not* musttail, the program already has 2157 // one frame of stack growth, so it's safe to remove musttail. Here is 2158 // a table of example transformations: 2159 // 2160 // f -> musttail g -> musttail f ==> f -> musttail f 2161 // f -> musttail g -> tail f ==> f -> tail f 2162 // f -> g -> musttail f ==> f -> f 2163 // f -> g -> tail f ==> f -> f 2164 // 2165 // Inlined notail calls should remain notail calls. 2166 CallInst::TailCallKind ChildTCK = CI->getTailCallKind(); 2167 if (ChildTCK != CallInst::TCK_NoTail) 2168 ChildTCK = std::min(CallSiteTailKind, ChildTCK); 2169 CI->setTailCallKind(ChildTCK); 2170 InlinedMustTailCalls |= CI->isMustTailCall(); 2171 2172 // Calls inlined through a 'nounwind' call site should be marked 2173 // 'nounwind'. 2174 if (MarkNoUnwind) 2175 CI->setDoesNotThrow(); 2176 } 2177 } 2178 } 2179 2180 // Leave lifetime markers for the static alloca's, scoping them to the 2181 // function we just inlined. 2182 if (InsertLifetime && !IFI.StaticAllocas.empty()) { 2183 IRBuilder<> builder(&FirstNewBlock->front()); 2184 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) { 2185 AllocaInst *AI = IFI.StaticAllocas[ai]; 2186 // Don't mark swifterror allocas. They can't have bitcast uses. 2187 if (AI->isSwiftError()) 2188 continue; 2189 2190 // If the alloca is already scoped to something smaller than the whole 2191 // function then there's no need to add redundant, less accurate markers. 2192 if (hasLifetimeMarkers(AI)) 2193 continue; 2194 2195 // Try to determine the size of the allocation. 2196 ConstantInt *AllocaSize = nullptr; 2197 if (ConstantInt *AIArraySize = 2198 dyn_cast<ConstantInt>(AI->getArraySize())) { 2199 auto &DL = Caller->getParent()->getDataLayout(); 2200 Type *AllocaType = AI->getAllocatedType(); 2201 TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType); 2202 uint64_t AllocaArraySize = AIArraySize->getLimitedValue(); 2203 2204 // Don't add markers for zero-sized allocas. 2205 if (AllocaArraySize == 0) 2206 continue; 2207 2208 // Check that array size doesn't saturate uint64_t and doesn't 2209 // overflow when it's multiplied by type size. 2210 if (!AllocaTypeSize.isScalable() && 2211 AllocaArraySize != std::numeric_limits<uint64_t>::max() && 2212 std::numeric_limits<uint64_t>::max() / AllocaArraySize >= 2213 AllocaTypeSize.getFixedSize()) { 2214 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()), 2215 AllocaArraySize * AllocaTypeSize); 2216 } 2217 } 2218 2219 builder.CreateLifetimeStart(AI, AllocaSize); 2220 for (ReturnInst *RI : Returns) { 2221 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize 2222 // call and a return. The return kills all local allocas. 2223 if (InlinedMustTailCalls && 2224 RI->getParent()->getTerminatingMustTailCall()) 2225 continue; 2226 if (InlinedDeoptimizeCalls && 2227 RI->getParent()->getTerminatingDeoptimizeCall()) 2228 continue; 2229 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize); 2230 } 2231 } 2232 } 2233 2234 // If the inlined code contained dynamic alloca instructions, wrap the inlined 2235 // code with llvm.stacksave/llvm.stackrestore intrinsics. 2236 if (InlinedFunctionInfo.ContainsDynamicAllocas) { 2237 Module *M = Caller->getParent(); 2238 // Get the two intrinsics we care about. 2239 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave); 2240 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore); 2241 2242 // Insert the llvm.stacksave. 2243 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin()) 2244 .CreateCall(StackSave, {}, "savedstack"); 2245 2246 // Insert a call to llvm.stackrestore before any return instructions in the 2247 // inlined function. 2248 for (ReturnInst *RI : Returns) { 2249 // Don't insert llvm.stackrestore calls between a musttail or deoptimize 2250 // call and a return. The return will restore the stack pointer. 2251 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall()) 2252 continue; 2253 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall()) 2254 continue; 2255 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr); 2256 } 2257 } 2258 2259 // If we are inlining for an invoke instruction, we must make sure to rewrite 2260 // any call instructions into invoke instructions. This is sensitive to which 2261 // funclet pads were top-level in the inlinee, so must be done before 2262 // rewriting the "parent pad" links. 2263 if (auto *II = dyn_cast<InvokeInst>(&CB)) { 2264 BasicBlock *UnwindDest = II->getUnwindDest(); 2265 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI(); 2266 if (isa<LandingPadInst>(FirstNonPHI)) { 2267 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo); 2268 } else { 2269 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo); 2270 } 2271 } 2272 2273 // Update the lexical scopes of the new funclets and callsites. 2274 // Anything that had 'none' as its parent is now nested inside the callsite's 2275 // EHPad. 2276 2277 if (CallSiteEHPad) { 2278 for (Function::iterator BB = FirstNewBlock->getIterator(), 2279 E = Caller->end(); 2280 BB != E; ++BB) { 2281 // Add bundle operands to any top-level call sites. 2282 SmallVector<OperandBundleDef, 1> OpBundles; 2283 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) { 2284 CallBase *I = dyn_cast<CallBase>(&*BBI++); 2285 if (!I) 2286 continue; 2287 2288 // Skip call sites which are nounwind intrinsics. 2289 auto *CalledFn = 2290 dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts()); 2291 if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow()) 2292 continue; 2293 2294 // Skip call sites which already have a "funclet" bundle. 2295 if (I->getOperandBundle(LLVMContext::OB_funclet)) 2296 continue; 2297 2298 I->getOperandBundlesAsDefs(OpBundles); 2299 OpBundles.emplace_back("funclet", CallSiteEHPad); 2300 2301 Instruction *NewInst = CallBase::Create(I, OpBundles, I); 2302 NewInst->takeName(I); 2303 I->replaceAllUsesWith(NewInst); 2304 I->eraseFromParent(); 2305 2306 OpBundles.clear(); 2307 } 2308 2309 // It is problematic if the inlinee has a cleanupret which unwinds to 2310 // caller and we inline it into a call site which doesn't unwind but into 2311 // an EH pad that does. Such an edge must be dynamically unreachable. 2312 // As such, we replace the cleanupret with unreachable. 2313 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator())) 2314 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally) 2315 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false); 2316 2317 Instruction *I = BB->getFirstNonPHI(); 2318 if (!I->isEHPad()) 2319 continue; 2320 2321 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { 2322 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad())) 2323 CatchSwitch->setParentPad(CallSiteEHPad); 2324 } else { 2325 auto *FPI = cast<FuncletPadInst>(I); 2326 if (isa<ConstantTokenNone>(FPI->getParentPad())) 2327 FPI->setParentPad(CallSiteEHPad); 2328 } 2329 } 2330 } 2331 2332 if (InlinedDeoptimizeCalls) { 2333 // We need to at least remove the deoptimizing returns from the Return set, 2334 // so that the control flow from those returns does not get merged into the 2335 // caller (but terminate it instead). If the caller's return type does not 2336 // match the callee's return type, we also need to change the return type of 2337 // the intrinsic. 2338 if (Caller->getReturnType() == CB.getType()) { 2339 llvm::erase_if(Returns, [](ReturnInst *RI) { 2340 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr; 2341 }); 2342 } else { 2343 SmallVector<ReturnInst *, 8> NormalReturns; 2344 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration( 2345 Caller->getParent(), Intrinsic::experimental_deoptimize, 2346 {Caller->getReturnType()}); 2347 2348 for (ReturnInst *RI : Returns) { 2349 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall(); 2350 if (!DeoptCall) { 2351 NormalReturns.push_back(RI); 2352 continue; 2353 } 2354 2355 // The calling convention on the deoptimize call itself may be bogus, 2356 // since the code we're inlining may have undefined behavior (and may 2357 // never actually execute at runtime); but all 2358 // @llvm.experimental.deoptimize declarations have to have the same 2359 // calling convention in a well-formed module. 2360 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv(); 2361 NewDeoptIntrinsic->setCallingConv(CallingConv); 2362 auto *CurBB = RI->getParent(); 2363 RI->eraseFromParent(); 2364 2365 SmallVector<Value *, 4> CallArgs(DeoptCall->args()); 2366 2367 SmallVector<OperandBundleDef, 1> OpBundles; 2368 DeoptCall->getOperandBundlesAsDefs(OpBundles); 2369 DeoptCall->eraseFromParent(); 2370 assert(!OpBundles.empty() && 2371 "Expected at least the deopt operand bundle"); 2372 2373 IRBuilder<> Builder(CurBB); 2374 CallInst *NewDeoptCall = 2375 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles); 2376 NewDeoptCall->setCallingConv(CallingConv); 2377 if (NewDeoptCall->getType()->isVoidTy()) 2378 Builder.CreateRetVoid(); 2379 else 2380 Builder.CreateRet(NewDeoptCall); 2381 } 2382 2383 // Leave behind the normal returns so we can merge control flow. 2384 std::swap(Returns, NormalReturns); 2385 } 2386 } 2387 2388 // Handle any inlined musttail call sites. In order for a new call site to be 2389 // musttail, the source of the clone and the inlined call site must have been 2390 // musttail. Therefore it's safe to return without merging control into the 2391 // phi below. 2392 if (InlinedMustTailCalls) { 2393 // Check if we need to bitcast the result of any musttail calls. 2394 Type *NewRetTy = Caller->getReturnType(); 2395 bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy; 2396 2397 // Handle the returns preceded by musttail calls separately. 2398 SmallVector<ReturnInst *, 8> NormalReturns; 2399 for (ReturnInst *RI : Returns) { 2400 CallInst *ReturnedMustTail = 2401 RI->getParent()->getTerminatingMustTailCall(); 2402 if (!ReturnedMustTail) { 2403 NormalReturns.push_back(RI); 2404 continue; 2405 } 2406 if (!NeedBitCast) 2407 continue; 2408 2409 // Delete the old return and any preceding bitcast. 2410 BasicBlock *CurBB = RI->getParent(); 2411 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue()); 2412 RI->eraseFromParent(); 2413 if (OldCast) 2414 OldCast->eraseFromParent(); 2415 2416 // Insert a new bitcast and return with the right type. 2417 IRBuilder<> Builder(CurBB); 2418 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy)); 2419 } 2420 2421 // Leave behind the normal returns so we can merge control flow. 2422 std::swap(Returns, NormalReturns); 2423 } 2424 2425 // Now that all of the transforms on the inlined code have taken place but 2426 // before we splice the inlined code into the CFG and lose track of which 2427 // blocks were actually inlined, collect the call sites. We only do this if 2428 // call graph updates weren't requested, as those provide value handle based 2429 // tracking of inlined call sites instead. 2430 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) { 2431 // Otherwise just collect the raw call sites that were inlined. 2432 for (BasicBlock &NewBB : 2433 make_range(FirstNewBlock->getIterator(), Caller->end())) 2434 for (Instruction &I : NewBB) 2435 if (auto *CB = dyn_cast<CallBase>(&I)) 2436 IFI.InlinedCallSites.push_back(CB); 2437 } 2438 2439 // If we cloned in _exactly one_ basic block, and if that block ends in a 2440 // return instruction, we splice the body of the inlined callee directly into 2441 // the calling basic block. 2442 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) { 2443 // Move all of the instructions right before the call. 2444 OrigBB->getInstList().splice(CB.getIterator(), FirstNewBlock->getInstList(), 2445 FirstNewBlock->begin(), FirstNewBlock->end()); 2446 // Remove the cloned basic block. 2447 Caller->getBasicBlockList().pop_back(); 2448 2449 // If the call site was an invoke instruction, add a branch to the normal 2450 // destination. 2451 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 2452 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), &CB); 2453 NewBr->setDebugLoc(Returns[0]->getDebugLoc()); 2454 } 2455 2456 // If the return instruction returned a value, replace uses of the call with 2457 // uses of the returned value. 2458 if (!CB.use_empty()) { 2459 ReturnInst *R = Returns[0]; 2460 if (&CB == R->getReturnValue()) 2461 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 2462 else 2463 CB.replaceAllUsesWith(R->getReturnValue()); 2464 } 2465 // Since we are now done with the Call/Invoke, we can delete it. 2466 CB.eraseFromParent(); 2467 2468 // Since we are now done with the return instruction, delete it also. 2469 Returns[0]->eraseFromParent(); 2470 2471 // We are now done with the inlining. 2472 return InlineResult::success(); 2473 } 2474 2475 // Otherwise, we have the normal case, of more than one block to inline or 2476 // multiple return sites. 2477 2478 // We want to clone the entire callee function into the hole between the 2479 // "starter" and "ender" blocks. How we accomplish this depends on whether 2480 // this is an invoke instruction or a call instruction. 2481 BasicBlock *AfterCallBB; 2482 BranchInst *CreatedBranchToNormalDest = nullptr; 2483 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 2484 2485 // Add an unconditional branch to make this look like the CallInst case... 2486 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), &CB); 2487 2488 // Split the basic block. This guarantees that no PHI nodes will have to be 2489 // updated due to new incoming edges, and make the invoke case more 2490 // symmetric to the call case. 2491 AfterCallBB = 2492 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(), 2493 CalledFunc->getName() + ".exit"); 2494 2495 } else { // It's a call 2496 // If this is a call instruction, we need to split the basic block that 2497 // the call lives in. 2498 // 2499 AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(), 2500 CalledFunc->getName() + ".exit"); 2501 } 2502 2503 if (IFI.CallerBFI) { 2504 // Copy original BB's block frequency to AfterCallBB 2505 IFI.CallerBFI->setBlockFreq( 2506 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency()); 2507 } 2508 2509 // Change the branch that used to go to AfterCallBB to branch to the first 2510 // basic block of the inlined function. 2511 // 2512 Instruction *Br = OrigBB->getTerminator(); 2513 assert(Br && Br->getOpcode() == Instruction::Br && 2514 "splitBasicBlock broken!"); 2515 Br->setOperand(0, &*FirstNewBlock); 2516 2517 // Now that the function is correct, make it a little bit nicer. In 2518 // particular, move the basic blocks inserted from the end of the function 2519 // into the space made by splitting the source basic block. 2520 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(), 2521 Caller->getBasicBlockList(), FirstNewBlock, 2522 Caller->end()); 2523 2524 // Handle all of the return instructions that we just cloned in, and eliminate 2525 // any users of the original call/invoke instruction. 2526 Type *RTy = CalledFunc->getReturnType(); 2527 2528 PHINode *PHI = nullptr; 2529 if (Returns.size() > 1) { 2530 // The PHI node should go at the front of the new basic block to merge all 2531 // possible incoming values. 2532 if (!CB.use_empty()) { 2533 PHI = PHINode::Create(RTy, Returns.size(), CB.getName(), 2534 &AfterCallBB->front()); 2535 // Anything that used the result of the function call should now use the 2536 // PHI node as their operand. 2537 CB.replaceAllUsesWith(PHI); 2538 } 2539 2540 // Loop over all of the return instructions adding entries to the PHI node 2541 // as appropriate. 2542 if (PHI) { 2543 for (unsigned i = 0, e = Returns.size(); i != e; ++i) { 2544 ReturnInst *RI = Returns[i]; 2545 assert(RI->getReturnValue()->getType() == PHI->getType() && 2546 "Ret value not consistent in function!"); 2547 PHI->addIncoming(RI->getReturnValue(), RI->getParent()); 2548 } 2549 } 2550 2551 // Add a branch to the merge points and remove return instructions. 2552 DebugLoc Loc; 2553 for (unsigned i = 0, e = Returns.size(); i != e; ++i) { 2554 ReturnInst *RI = Returns[i]; 2555 BranchInst* BI = BranchInst::Create(AfterCallBB, RI); 2556 Loc = RI->getDebugLoc(); 2557 BI->setDebugLoc(Loc); 2558 RI->eraseFromParent(); 2559 } 2560 // We need to set the debug location to *somewhere* inside the 2561 // inlined function. The line number may be nonsensical, but the 2562 // instruction will at least be associated with the right 2563 // function. 2564 if (CreatedBranchToNormalDest) 2565 CreatedBranchToNormalDest->setDebugLoc(Loc); 2566 } else if (!Returns.empty()) { 2567 // Otherwise, if there is exactly one return value, just replace anything 2568 // using the return value of the call with the computed value. 2569 if (!CB.use_empty()) { 2570 if (&CB == Returns[0]->getReturnValue()) 2571 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 2572 else 2573 CB.replaceAllUsesWith(Returns[0]->getReturnValue()); 2574 } 2575 2576 // Update PHI nodes that use the ReturnBB to use the AfterCallBB. 2577 BasicBlock *ReturnBB = Returns[0]->getParent(); 2578 ReturnBB->replaceAllUsesWith(AfterCallBB); 2579 2580 // Splice the code from the return block into the block that it will return 2581 // to, which contains the code that was after the call. 2582 AfterCallBB->getInstList().splice(AfterCallBB->begin(), 2583 ReturnBB->getInstList()); 2584 2585 if (CreatedBranchToNormalDest) 2586 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc()); 2587 2588 // Delete the return instruction now and empty ReturnBB now. 2589 Returns[0]->eraseFromParent(); 2590 ReturnBB->eraseFromParent(); 2591 } else if (!CB.use_empty()) { 2592 // No returns, but something is using the return value of the call. Just 2593 // nuke the result. 2594 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 2595 } 2596 2597 // Since we are now done with the Call/Invoke, we can delete it. 2598 CB.eraseFromParent(); 2599 2600 // If we inlined any musttail calls and the original return is now 2601 // unreachable, delete it. It can only contain a bitcast and ret. 2602 if (InlinedMustTailCalls && pred_empty(AfterCallBB)) 2603 AfterCallBB->eraseFromParent(); 2604 2605 // We should always be able to fold the entry block of the function into the 2606 // single predecessor of the block... 2607 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!"); 2608 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0); 2609 2610 // Splice the code entry block into calling block, right before the 2611 // unconditional branch. 2612 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes 2613 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList()); 2614 2615 // Remove the unconditional branch. 2616 OrigBB->getInstList().erase(Br); 2617 2618 // Now we can remove the CalleeEntry block, which is now empty. 2619 Caller->getBasicBlockList().erase(CalleeEntry); 2620 2621 // If we inserted a phi node, check to see if it has a single value (e.g. all 2622 // the entries are the same or undef). If so, remove the PHI so it doesn't 2623 // block other optimizations. 2624 if (PHI) { 2625 AssumptionCache *AC = 2626 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 2627 auto &DL = Caller->getParent()->getDataLayout(); 2628 if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) { 2629 PHI->replaceAllUsesWith(V); 2630 PHI->eraseFromParent(); 2631 } 2632 } 2633 2634 return InlineResult::success(); 2635 } 2636