1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 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 the interface to tear out a code region, such as an 10 // individual loop or a parallel section, into a new function, replacing it with 11 // a call to the new function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/CodeExtractor.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 25 #include "llvm/Analysis/BranchProbabilityInfo.h" 26 #include "llvm/IR/Argument.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/Constant.h" 31 #include "llvm/IR/Constants.h" 32 #include "llvm/IR/DIBuilder.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/DebugInfo.h" 35 #include "llvm/IR/DebugInfoMetadata.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/GlobalValue.h" 40 #include "llvm/IR/InstIterator.h" 41 #include "llvm/IR/InstrTypes.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/LLVMContext.h" 47 #include "llvm/IR/MDBuilder.h" 48 #include "llvm/IR/Module.h" 49 #include "llvm/IR/PatternMatch.h" 50 #include "llvm/IR/Type.h" 51 #include "llvm/IR/User.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/IR/Verifier.h" 54 #include "llvm/Support/BlockFrequency.h" 55 #include "llvm/Support/BranchProbability.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CommandLine.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 62 #include <cassert> 63 #include <cstdint> 64 #include <iterator> 65 #include <map> 66 #include <utility> 67 #include <vector> 68 69 using namespace llvm; 70 using namespace llvm::PatternMatch; 71 using ProfileCount = Function::ProfileCount; 72 73 #define DEBUG_TYPE "code-extractor" 74 75 // Provide a command-line option to aggregate function arguments into a struct 76 // for functions produced by the code extractor. This is useful when converting 77 // extracted functions to pthread-based code, as only one argument (void*) can 78 // be passed in to pthread_create(). 79 static cl::opt<bool> 80 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 81 cl::desc("Aggregate arguments to code-extracted functions")); 82 83 /// Test whether a block is valid for extraction. 84 static bool isBlockValidForExtraction(const BasicBlock &BB, 85 const SetVector<BasicBlock *> &Result, 86 bool AllowVarArgs, bool AllowAlloca) { 87 // taking the address of a basic block moved to another function is illegal 88 if (BB.hasAddressTaken()) 89 return false; 90 91 // don't hoist code that uses another basicblock address, as it's likely to 92 // lead to unexpected behavior, like cross-function jumps 93 SmallPtrSet<User const *, 16> Visited; 94 SmallVector<User const *, 16> ToVisit; 95 96 for (Instruction const &Inst : BB) 97 ToVisit.push_back(&Inst); 98 99 while (!ToVisit.empty()) { 100 User const *Curr = ToVisit.pop_back_val(); 101 if (!Visited.insert(Curr).second) 102 continue; 103 if (isa<BlockAddress const>(Curr)) 104 return false; // even a reference to self is likely to be not compatible 105 106 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB) 107 continue; 108 109 for (auto const &U : Curr->operands()) { 110 if (auto *UU = dyn_cast<User>(U)) 111 ToVisit.push_back(UU); 112 } 113 } 114 115 // If explicitly requested, allow vastart and alloca. For invoke instructions 116 // verify that extraction is valid. 117 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 118 if (isa<AllocaInst>(I)) { 119 if (!AllowAlloca) 120 return false; 121 continue; 122 } 123 124 if (const auto *II = dyn_cast<InvokeInst>(I)) { 125 // Unwind destination (either a landingpad, catchswitch, or cleanuppad) 126 // must be a part of the subgraph which is being extracted. 127 if (auto *UBB = II->getUnwindDest()) 128 if (!Result.count(UBB)) 129 return false; 130 continue; 131 } 132 133 // All catch handlers of a catchswitch instruction as well as the unwind 134 // destination must be in the subgraph. 135 if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) { 136 if (auto *UBB = CSI->getUnwindDest()) 137 if (!Result.count(UBB)) 138 return false; 139 for (const auto *HBB : CSI->handlers()) 140 if (!Result.count(const_cast<BasicBlock*>(HBB))) 141 return false; 142 continue; 143 } 144 145 // Make sure that entire catch handler is within subgraph. It is sufficient 146 // to check that catch return's block is in the list. 147 if (const auto *CPI = dyn_cast<CatchPadInst>(I)) { 148 for (const auto *U : CPI->users()) 149 if (const auto *CRI = dyn_cast<CatchReturnInst>(U)) 150 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) 151 return false; 152 continue; 153 } 154 155 // And do similar checks for cleanup handler - the entire handler must be 156 // in subgraph which is going to be extracted. For cleanup return should 157 // additionally check that the unwind destination is also in the subgraph. 158 if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) { 159 for (const auto *U : CPI->users()) 160 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U)) 161 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) 162 return false; 163 continue; 164 } 165 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) { 166 if (auto *UBB = CRI->getUnwindDest()) 167 if (!Result.count(UBB)) 168 return false; 169 continue; 170 } 171 172 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 173 if (const Function *F = CI->getCalledFunction()) { 174 auto IID = F->getIntrinsicID(); 175 if (IID == Intrinsic::vastart) { 176 if (AllowVarArgs) 177 continue; 178 else 179 return false; 180 } 181 182 // Currently, we miscompile outlined copies of eh_typid_for. There are 183 // proposals for fixing this in llvm.org/PR39545. 184 if (IID == Intrinsic::eh_typeid_for) 185 return false; 186 } 187 } 188 } 189 190 return true; 191 } 192 193 /// Build a set of blocks to extract if the input blocks are viable. 194 static SetVector<BasicBlock *> 195 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 196 bool AllowVarArgs, bool AllowAlloca) { 197 assert(!BBs.empty() && "The set of blocks to extract must be non-empty"); 198 SetVector<BasicBlock *> Result; 199 200 // Loop over the blocks, adding them to our set-vector, and aborting with an 201 // empty set if we encounter invalid blocks. 202 for (BasicBlock *BB : BBs) { 203 // If this block is dead, don't process it. 204 if (DT && !DT->isReachableFromEntry(BB)) 205 continue; 206 207 if (!Result.insert(BB)) 208 llvm_unreachable("Repeated basic blocks in extraction input"); 209 } 210 211 LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName() 212 << '\n'); 213 214 for (auto *BB : Result) { 215 if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca)) 216 return {}; 217 218 // Make sure that the first block is not a landing pad. 219 if (BB == Result.front()) { 220 if (BB->isEHPad()) { 221 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n"); 222 return {}; 223 } 224 continue; 225 } 226 227 // All blocks other than the first must not have predecessors outside of 228 // the subgraph which is being extracted. 229 for (auto *PBB : predecessors(BB)) 230 if (!Result.count(PBB)) { 231 LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from " 232 "outside the region except for the first block!\n" 233 << "Problematic source BB: " << BB->getName() << "\n" 234 << "Problematic destination BB: " << PBB->getName() 235 << "\n"); 236 return {}; 237 } 238 } 239 240 return Result; 241 } 242 243 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 244 bool AggregateArgs, BlockFrequencyInfo *BFI, 245 BranchProbabilityInfo *BPI, AssumptionCache *AC, 246 bool AllowVarArgs, bool AllowAlloca, 247 BasicBlock *AllocationBlock, std::string Suffix, 248 bool ArgsInZeroAddressSpace) 249 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 250 BPI(BPI), AC(AC), AllocationBlock(AllocationBlock), 251 AllowVarArgs(AllowVarArgs), 252 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)), 253 Suffix(Suffix), ArgsInZeroAddressSpace(ArgsInZeroAddressSpace) {} 254 255 /// definedInRegion - Return true if the specified value is defined in the 256 /// extracted region. 257 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 258 if (Instruction *I = dyn_cast<Instruction>(V)) 259 if (Blocks.count(I->getParent())) 260 return true; 261 return false; 262 } 263 264 /// definedInCaller - Return true if the specified value is defined in the 265 /// function being code extracted, but not in the region being extracted. 266 /// These values must be passed in as live-ins to the function. 267 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 268 if (isa<Argument>(V)) return true; 269 if (Instruction *I = dyn_cast<Instruction>(V)) 270 if (!Blocks.count(I->getParent())) 271 return true; 272 return false; 273 } 274 275 static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) { 276 BasicBlock *CommonExitBlock = nullptr; 277 auto hasNonCommonExitSucc = [&](BasicBlock *Block) { 278 for (auto *Succ : successors(Block)) { 279 // Internal edges, ok. 280 if (Blocks.count(Succ)) 281 continue; 282 if (!CommonExitBlock) { 283 CommonExitBlock = Succ; 284 continue; 285 } 286 if (CommonExitBlock != Succ) 287 return true; 288 } 289 return false; 290 }; 291 292 if (any_of(Blocks, hasNonCommonExitSucc)) 293 return nullptr; 294 295 return CommonExitBlock; 296 } 297 298 CodeExtractorAnalysisCache::CodeExtractorAnalysisCache(Function &F) { 299 for (BasicBlock &BB : F) { 300 for (Instruction &II : BB.instructionsWithoutDebug()) 301 if (auto *AI = dyn_cast<AllocaInst>(&II)) 302 Allocas.push_back(AI); 303 304 findSideEffectInfoForBlock(BB); 305 } 306 } 307 308 void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) { 309 for (Instruction &II : BB.instructionsWithoutDebug()) { 310 unsigned Opcode = II.getOpcode(); 311 Value *MemAddr = nullptr; 312 switch (Opcode) { 313 case Instruction::Store: 314 case Instruction::Load: { 315 if (Opcode == Instruction::Store) { 316 StoreInst *SI = cast<StoreInst>(&II); 317 MemAddr = SI->getPointerOperand(); 318 } else { 319 LoadInst *LI = cast<LoadInst>(&II); 320 MemAddr = LI->getPointerOperand(); 321 } 322 // Global variable can not be aliased with locals. 323 if (isa<Constant>(MemAddr)) 324 break; 325 Value *Base = MemAddr->stripInBoundsConstantOffsets(); 326 if (!isa<AllocaInst>(Base)) { 327 SideEffectingBlocks.insert(&BB); 328 return; 329 } 330 BaseMemAddrs[&BB].insert(Base); 331 break; 332 } 333 default: { 334 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II); 335 if (IntrInst) { 336 if (IntrInst->isLifetimeStartOrEnd()) 337 break; 338 SideEffectingBlocks.insert(&BB); 339 return; 340 } 341 // Treat all the other cases conservatively if it has side effects. 342 if (II.mayHaveSideEffects()) { 343 SideEffectingBlocks.insert(&BB); 344 return; 345 } 346 } 347 } 348 } 349 } 350 351 bool CodeExtractorAnalysisCache::doesBlockContainClobberOfAddr( 352 BasicBlock &BB, AllocaInst *Addr) const { 353 if (SideEffectingBlocks.count(&BB)) 354 return true; 355 auto It = BaseMemAddrs.find(&BB); 356 if (It != BaseMemAddrs.end()) 357 return It->second.count(Addr); 358 return false; 359 } 360 361 bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( 362 const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const { 363 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets()); 364 Function *Func = (*Blocks.begin())->getParent(); 365 for (BasicBlock &BB : *Func) { 366 if (Blocks.count(&BB)) 367 continue; 368 if (CEAC.doesBlockContainClobberOfAddr(BB, AI)) 369 return false; 370 } 371 return true; 372 } 373 374 BasicBlock * 375 CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) { 376 BasicBlock *SinglePredFromOutlineRegion = nullptr; 377 assert(!Blocks.count(CommonExitBlock) && 378 "Expect a block outside the region!"); 379 for (auto *Pred : predecessors(CommonExitBlock)) { 380 if (!Blocks.count(Pred)) 381 continue; 382 if (!SinglePredFromOutlineRegion) { 383 SinglePredFromOutlineRegion = Pred; 384 } else if (SinglePredFromOutlineRegion != Pred) { 385 SinglePredFromOutlineRegion = nullptr; 386 break; 387 } 388 } 389 390 if (SinglePredFromOutlineRegion) 391 return SinglePredFromOutlineRegion; 392 393 #ifndef NDEBUG 394 auto getFirstPHI = [](BasicBlock *BB) { 395 BasicBlock::iterator I = BB->begin(); 396 PHINode *FirstPhi = nullptr; 397 while (I != BB->end()) { 398 PHINode *Phi = dyn_cast<PHINode>(I); 399 if (!Phi) 400 break; 401 if (!FirstPhi) { 402 FirstPhi = Phi; 403 break; 404 } 405 } 406 return FirstPhi; 407 }; 408 // If there are any phi nodes, the single pred either exists or has already 409 // be created before code extraction. 410 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected"); 411 #endif 412 413 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock( 414 CommonExitBlock->getFirstNonPHI()->getIterator()); 415 416 for (BasicBlock *Pred : 417 llvm::make_early_inc_range(predecessors(CommonExitBlock))) { 418 if (Blocks.count(Pred)) 419 continue; 420 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock); 421 } 422 // Now add the old exit block to the outline region. 423 Blocks.insert(CommonExitBlock); 424 return CommonExitBlock; 425 } 426 427 // Find the pair of life time markers for address 'Addr' that are either 428 // defined inside the outline region or can legally be shrinkwrapped into the 429 // outline region. If there are not other untracked uses of the address, return 430 // the pair of markers if found; otherwise return a pair of nullptr. 431 CodeExtractor::LifetimeMarkerInfo 432 CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC, 433 Instruction *Addr, 434 BasicBlock *ExitBlock) const { 435 LifetimeMarkerInfo Info; 436 437 for (User *U : Addr->users()) { 438 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); 439 if (IntrInst) { 440 // We don't model addresses with multiple start/end markers, but the 441 // markers do not need to be in the region. 442 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) { 443 if (Info.LifeStart) 444 return {}; 445 Info.LifeStart = IntrInst; 446 continue; 447 } 448 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) { 449 if (Info.LifeEnd) 450 return {}; 451 Info.LifeEnd = IntrInst; 452 continue; 453 } 454 // At this point, permit debug uses outside of the region. 455 // This is fixed in a later call to fixupDebugInfoPostExtraction(). 456 if (isa<DbgInfoIntrinsic>(IntrInst)) 457 continue; 458 } 459 // Find untracked uses of the address, bail. 460 if (!definedInRegion(Blocks, U)) 461 return {}; 462 } 463 464 if (!Info.LifeStart || !Info.LifeEnd) 465 return {}; 466 467 Info.SinkLifeStart = !definedInRegion(Blocks, Info.LifeStart); 468 Info.HoistLifeEnd = !definedInRegion(Blocks, Info.LifeEnd); 469 // Do legality check. 470 if ((Info.SinkLifeStart || Info.HoistLifeEnd) && 471 !isLegalToShrinkwrapLifetimeMarkers(CEAC, Addr)) 472 return {}; 473 474 // Check to see if we have a place to do hoisting, if not, bail. 475 if (Info.HoistLifeEnd && !ExitBlock) 476 return {}; 477 478 return Info; 479 } 480 481 void CodeExtractor::findAllocas(const CodeExtractorAnalysisCache &CEAC, 482 ValueSet &SinkCands, ValueSet &HoistCands, 483 BasicBlock *&ExitBlock) const { 484 Function *Func = (*Blocks.begin())->getParent(); 485 ExitBlock = getCommonExitBlock(Blocks); 486 487 auto moveOrIgnoreLifetimeMarkers = 488 [&](const LifetimeMarkerInfo &LMI) -> bool { 489 if (!LMI.LifeStart) 490 return false; 491 if (LMI.SinkLifeStart) { 492 LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart 493 << "\n"); 494 SinkCands.insert(LMI.LifeStart); 495 } 496 if (LMI.HoistLifeEnd) { 497 LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n"); 498 HoistCands.insert(LMI.LifeEnd); 499 } 500 return true; 501 }; 502 503 // Look up allocas in the original function in CodeExtractorAnalysisCache, as 504 // this is much faster than walking all the instructions. 505 for (AllocaInst *AI : CEAC.getAllocas()) { 506 BasicBlock *BB = AI->getParent(); 507 if (Blocks.count(BB)) 508 continue; 509 510 // As a prior call to extractCodeRegion() may have shrinkwrapped the alloca, 511 // check whether it is actually still in the original function. 512 Function *AIFunc = BB->getParent(); 513 if (AIFunc != Func) 514 continue; 515 516 LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, AI, ExitBlock); 517 bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo); 518 if (Moved) { 519 LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n"); 520 SinkCands.insert(AI); 521 continue; 522 } 523 524 // Find bitcasts in the outlined region that have lifetime marker users 525 // outside that region. Replace the lifetime marker use with an 526 // outside region bitcast to avoid unnecessary alloca/reload instructions 527 // and extra lifetime markers. 528 SmallVector<Instruction *, 2> LifetimeBitcastUsers; 529 for (User *U : AI->users()) { 530 if (!definedInRegion(Blocks, U)) 531 continue; 532 533 if (U->stripInBoundsConstantOffsets() != AI) 534 continue; 535 536 Instruction *Bitcast = cast<Instruction>(U); 537 for (User *BU : Bitcast->users()) { 538 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(BU); 539 if (!IntrInst) 540 continue; 541 542 if (!IntrInst->isLifetimeStartOrEnd()) 543 continue; 544 545 if (definedInRegion(Blocks, IntrInst)) 546 continue; 547 548 LLVM_DEBUG(dbgs() << "Replace use of extracted region bitcast" 549 << *Bitcast << " in out-of-region lifetime marker " 550 << *IntrInst << "\n"); 551 LifetimeBitcastUsers.push_back(IntrInst); 552 } 553 } 554 555 for (Instruction *I : LifetimeBitcastUsers) { 556 Module *M = AIFunc->getParent(); 557 LLVMContext &Ctx = M->getContext(); 558 auto *Int8PtrTy = PointerType::getUnqual(Ctx); 559 CastInst *CastI = 560 CastInst::CreatePointerCast(AI, Int8PtrTy, "lt.cast", I->getIterator()); 561 I->replaceUsesOfWith(I->getOperand(1), CastI); 562 } 563 564 // Follow any bitcasts. 565 SmallVector<Instruction *, 2> Bitcasts; 566 SmallVector<LifetimeMarkerInfo, 2> BitcastLifetimeInfo; 567 for (User *U : AI->users()) { 568 if (U->stripInBoundsConstantOffsets() == AI) { 569 Instruction *Bitcast = cast<Instruction>(U); 570 LifetimeMarkerInfo LMI = getLifetimeMarkers(CEAC, Bitcast, ExitBlock); 571 if (LMI.LifeStart) { 572 Bitcasts.push_back(Bitcast); 573 BitcastLifetimeInfo.push_back(LMI); 574 continue; 575 } 576 } 577 578 // Found unknown use of AI. 579 if (!definedInRegion(Blocks, U)) { 580 Bitcasts.clear(); 581 break; 582 } 583 } 584 585 // Either no bitcasts reference the alloca or there are unknown uses. 586 if (Bitcasts.empty()) 587 continue; 588 589 LLVM_DEBUG(dbgs() << "Sinking alloca (via bitcast): " << *AI << "\n"); 590 SinkCands.insert(AI); 591 for (unsigned I = 0, E = Bitcasts.size(); I != E; ++I) { 592 Instruction *BitcastAddr = Bitcasts[I]; 593 const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[I]; 594 assert(LMI.LifeStart && 595 "Unsafe to sink bitcast without lifetime markers"); 596 moveOrIgnoreLifetimeMarkers(LMI); 597 if (!definedInRegion(Blocks, BitcastAddr)) { 598 LLVM_DEBUG(dbgs() << "Sinking bitcast-of-alloca: " << *BitcastAddr 599 << "\n"); 600 SinkCands.insert(BitcastAddr); 601 } 602 } 603 } 604 } 605 606 bool CodeExtractor::isEligible() const { 607 if (Blocks.empty()) 608 return false; 609 BasicBlock *Header = *Blocks.begin(); 610 Function *F = Header->getParent(); 611 612 // For functions with varargs, check that varargs handling is only done in the 613 // outlined function, i.e vastart and vaend are only used in outlined blocks. 614 if (AllowVarArgs && F->getFunctionType()->isVarArg()) { 615 auto containsVarArgIntrinsic = [](const Instruction &I) { 616 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 617 if (const Function *Callee = CI->getCalledFunction()) 618 return Callee->getIntrinsicID() == Intrinsic::vastart || 619 Callee->getIntrinsicID() == Intrinsic::vaend; 620 return false; 621 }; 622 623 for (auto &BB : *F) { 624 if (Blocks.count(&BB)) 625 continue; 626 if (llvm::any_of(BB, containsVarArgIntrinsic)) 627 return false; 628 } 629 } 630 return true; 631 } 632 633 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, 634 const ValueSet &SinkCands, 635 bool CollectGlobalInputs) const { 636 for (BasicBlock *BB : Blocks) { 637 // If a used value is defined outside the region, it's an input. If an 638 // instruction is used outside the region, it's an output. 639 for (Instruction &II : *BB) { 640 for (auto &OI : II.operands()) { 641 Value *V = OI; 642 if (!SinkCands.count(V) && 643 (definedInCaller(Blocks, V) || 644 (CollectGlobalInputs && llvm::isa<llvm::GlobalVariable>(V)))) 645 Inputs.insert(V); 646 } 647 648 for (User *U : II.users()) 649 if (!definedInRegion(Blocks, U)) { 650 Outputs.insert(&II); 651 break; 652 } 653 } 654 } 655 } 656 657 /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside 658 /// of the region, we need to split the entry block of the region so that the 659 /// PHI node is easier to deal with. 660 void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) { 661 unsigned NumPredsFromRegion = 0; 662 unsigned NumPredsOutsideRegion = 0; 663 664 if (Header != &Header->getParent()->getEntryBlock()) { 665 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 666 if (!PN) return; // No PHI nodes. 667 668 // If the header node contains any PHI nodes, check to see if there is more 669 // than one entry from outside the region. If so, we need to sever the 670 // header block into two. 671 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 672 if (Blocks.count(PN->getIncomingBlock(i))) 673 ++NumPredsFromRegion; 674 else 675 ++NumPredsOutsideRegion; 676 677 // If there is one (or fewer) predecessor from outside the region, we don't 678 // need to do anything special. 679 if (NumPredsOutsideRegion <= 1) return; 680 } 681 682 // Otherwise, we need to split the header block into two pieces: one 683 // containing PHI nodes merging values from outside of the region, and a 684 // second that contains all of the code for the block and merges back any 685 // incoming values from inside of the region. 686 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); 687 688 // We only want to code extract the second block now, and it becomes the new 689 // header of the region. 690 BasicBlock *OldPred = Header; 691 Blocks.remove(OldPred); 692 Blocks.insert(NewBB); 693 Header = NewBB; 694 695 // Okay, now we need to adjust the PHI nodes and any branches from within the 696 // region to go to the new header block instead of the old header block. 697 if (NumPredsFromRegion) { 698 PHINode *PN = cast<PHINode>(OldPred->begin()); 699 // Loop over all of the predecessors of OldPred that are in the region, 700 // changing them to branch to NewBB instead. 701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 702 if (Blocks.count(PN->getIncomingBlock(i))) { 703 Instruction *TI = PN->getIncomingBlock(i)->getTerminator(); 704 TI->replaceUsesOfWith(OldPred, NewBB); 705 } 706 707 // Okay, everything within the region is now branching to the right block, we 708 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 709 BasicBlock::iterator AfterPHIs; 710 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 711 PHINode *PN = cast<PHINode>(AfterPHIs); 712 // Create a new PHI node in the new region, which has an incoming value 713 // from OldPred of PN. 714 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 715 PN->getName() + ".ce"); 716 NewPN->insertBefore(NewBB->begin()); 717 PN->replaceAllUsesWith(NewPN); 718 NewPN->addIncoming(PN, OldPred); 719 720 // Loop over all of the incoming value in PN, moving them to NewPN if they 721 // are from the extracted region. 722 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 723 if (Blocks.count(PN->getIncomingBlock(i))) { 724 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 725 PN->removeIncomingValue(i); 726 --i; 727 } 728 } 729 } 730 } 731 } 732 733 /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from 734 /// outlined region, we split these PHIs on two: one with inputs from region 735 /// and other with remaining incoming blocks; then first PHIs are placed in 736 /// outlined region. 737 void CodeExtractor::severSplitPHINodesOfExits() { 738 for (BasicBlock *ExitBB : ExtractedFuncRetVals) { 739 BasicBlock *NewBB = nullptr; 740 741 for (PHINode &PN : ExitBB->phis()) { 742 // Find all incoming values from the outlining region. 743 SmallVector<unsigned, 2> IncomingVals; 744 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i) 745 if (Blocks.count(PN.getIncomingBlock(i))) 746 IncomingVals.push_back(i); 747 748 // Do not process PHI if there is one (or fewer) predecessor from region. 749 // If PHI has exactly one predecessor from region, only this one incoming 750 // will be replaced on codeRepl block, so it should be safe to skip PHI. 751 if (IncomingVals.size() <= 1) 752 continue; 753 754 // Create block for new PHIs and add it to the list of outlined if it 755 // wasn't done before. 756 if (!NewBB) { 757 NewBB = BasicBlock::Create(ExitBB->getContext(), 758 ExitBB->getName() + ".split", 759 ExitBB->getParent(), ExitBB); 760 NewBB->IsNewDbgInfoFormat = ExitBB->IsNewDbgInfoFormat; 761 SmallVector<BasicBlock *, 4> Preds(predecessors(ExitBB)); 762 for (BasicBlock *PredBB : Preds) 763 if (Blocks.count(PredBB)) 764 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB); 765 BranchInst::Create(ExitBB, NewBB); 766 Blocks.insert(NewBB); 767 } 768 769 // Split this PHI. 770 PHINode *NewPN = PHINode::Create(PN.getType(), IncomingVals.size(), 771 PN.getName() + ".ce"); 772 NewPN->insertBefore(NewBB->getFirstNonPHIIt()); 773 for (unsigned i : IncomingVals) 774 NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i)); 775 for (unsigned i : reverse(IncomingVals)) 776 PN.removeIncomingValue(i, false); 777 PN.addIncoming(NewPN, NewBB); 778 } 779 } 780 } 781 782 void CodeExtractor::splitReturnBlocks() { 783 for (BasicBlock *Block : Blocks) 784 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { 785 BasicBlock *New = 786 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); 787 if (DT) { 788 // Old dominates New. New node dominates all other nodes dominated 789 // by Old. 790 DomTreeNode *OldNode = DT->getNode(Block); 791 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), 792 OldNode->end()); 793 794 DomTreeNode *NewNode = DT->addNewBlock(New, Block); 795 796 for (DomTreeNode *I : Children) 797 DT->changeImmediateDominator(I, NewNode); 798 } 799 } 800 } 801 802 Function *CodeExtractor::constructFunctionDeclaration( 803 const ValueSet &inputs, const ValueSet &outputs, BlockFrequency EntryFreq, 804 const Twine &Name, ValueSet &StructValues, StructType *&StructTy) { 805 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 806 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 807 808 Function *oldFunction = Blocks.front()->getParent(); 809 Module *M = Blocks.front()->getModule(); 810 811 // Assemble the function's parameter lists. 812 std::vector<Type *> ParamTy; 813 std::vector<Type *> AggParamTy; 814 const DataLayout &DL = M->getDataLayout(); 815 816 // Add the types of the input values to the function's argument list 817 for (Value *value : inputs) { 818 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n"); 819 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(value)) { 820 AggParamTy.push_back(value->getType()); 821 StructValues.insert(value); 822 } else 823 ParamTy.push_back(value->getType()); 824 } 825 826 // Add the types of the output values to the function's argument list. 827 for (Value *output : outputs) { 828 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n"); 829 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(output)) { 830 AggParamTy.push_back(output->getType()); 831 StructValues.insert(output); 832 } else 833 ParamTy.push_back( 834 PointerType::get(output->getType(), DL.getAllocaAddrSpace())); 835 } 836 837 assert( 838 (ParamTy.size() + AggParamTy.size()) == 839 (inputs.size() + outputs.size()) && 840 "Number of scalar and aggregate params does not match inputs, outputs"); 841 assert((StructValues.empty() || AggregateArgs) && 842 "Expeced StructValues only with AggregateArgs set"); 843 844 // Concatenate scalar and aggregate params in ParamTy. 845 if (!AggParamTy.empty()) { 846 StructTy = StructType::get(M->getContext(), AggParamTy); 847 ParamTy.push_back(PointerType::get( 848 StructTy, ArgsInZeroAddressSpace ? 0 : DL.getAllocaAddrSpace())); 849 } 850 851 Type *RetTy = getSwitchType(); 852 LLVM_DEBUG({ 853 dbgs() << "Function type: " << *RetTy << " f("; 854 for (Type *i : ParamTy) 855 dbgs() << *i << ", "; 856 dbgs() << ")\n"; 857 }); 858 859 FunctionType *funcType = FunctionType::get( 860 RetTy, ParamTy, AllowVarArgs && oldFunction->isVarArg()); 861 862 // Create the new function 863 Function *newFunction = 864 Function::Create(funcType, GlobalValue::InternalLinkage, 865 oldFunction->getAddressSpace(), Name, M); 866 867 // Propagate personality info to the new function if there is one. 868 if (oldFunction->hasPersonalityFn()) 869 newFunction->setPersonalityFn(oldFunction->getPersonalityFn()); 870 871 // Inherit all of the target dependent attributes and white-listed 872 // target independent attributes. 873 // (e.g. If the extracted region contains a call to an x86.sse 874 // instruction we need to make sure that the extracted region has the 875 // "target-features" attribute allowing it to be lowered. 876 // FIXME: This should be changed to check to see if a specific 877 // attribute can not be inherited. 878 for (const auto &Attr : oldFunction->getAttributes().getFnAttrs()) { 879 if (Attr.isStringAttribute()) { 880 if (Attr.getKindAsString() == "thunk") 881 continue; 882 } else 883 switch (Attr.getKindAsEnum()) { 884 // Those attributes cannot be propagated safely. Explicitly list them 885 // here so we get a warning if new attributes are added. 886 case Attribute::AllocSize: 887 case Attribute::Builtin: 888 case Attribute::Convergent: 889 case Attribute::JumpTable: 890 case Attribute::Naked: 891 case Attribute::NoBuiltin: 892 case Attribute::NoMerge: 893 case Attribute::NoReturn: 894 case Attribute::NoSync: 895 case Attribute::ReturnsTwice: 896 case Attribute::Speculatable: 897 case Attribute::StackAlignment: 898 case Attribute::WillReturn: 899 case Attribute::AllocKind: 900 case Attribute::PresplitCoroutine: 901 case Attribute::Memory: 902 case Attribute::NoFPClass: 903 case Attribute::CoroDestroyOnlyWhenComplete: 904 case Attribute::CoroElideSafe: 905 case Attribute::NoDivergenceSource: 906 continue; 907 // Those attributes should be safe to propagate to the extracted function. 908 case Attribute::AlwaysInline: 909 case Attribute::Cold: 910 case Attribute::DisableSanitizerInstrumentation: 911 case Attribute::FnRetThunkExtern: 912 case Attribute::Hot: 913 case Attribute::HybridPatchable: 914 case Attribute::NoRecurse: 915 case Attribute::InlineHint: 916 case Attribute::MinSize: 917 case Attribute::NoCallback: 918 case Attribute::NoDuplicate: 919 case Attribute::NoFree: 920 case Attribute::NoImplicitFloat: 921 case Attribute::NoInline: 922 case Attribute::NonLazyBind: 923 case Attribute::NoRedZone: 924 case Attribute::NoUnwind: 925 case Attribute::NoSanitizeBounds: 926 case Attribute::NoSanitizeCoverage: 927 case Attribute::NullPointerIsValid: 928 case Attribute::OptimizeForDebugging: 929 case Attribute::OptForFuzzing: 930 case Attribute::OptimizeNone: 931 case Attribute::OptimizeForSize: 932 case Attribute::SafeStack: 933 case Attribute::ShadowCallStack: 934 case Attribute::SanitizeAddress: 935 case Attribute::SanitizeMemory: 936 case Attribute::SanitizeNumericalStability: 937 case Attribute::SanitizeThread: 938 case Attribute::SanitizeHWAddress: 939 case Attribute::SanitizeMemTag: 940 case Attribute::SanitizeRealtime: 941 case Attribute::SanitizeRealtimeBlocking: 942 case Attribute::SpeculativeLoadHardening: 943 case Attribute::StackProtect: 944 case Attribute::StackProtectReq: 945 case Attribute::StackProtectStrong: 946 case Attribute::StrictFP: 947 case Attribute::UWTable: 948 case Attribute::VScaleRange: 949 case Attribute::NoCfCheck: 950 case Attribute::MustProgress: 951 case Attribute::NoProfile: 952 case Attribute::SkipProfile: 953 break; 954 // These attributes cannot be applied to functions. 955 case Attribute::Alignment: 956 case Attribute::AllocatedPointer: 957 case Attribute::AllocAlign: 958 case Attribute::ByVal: 959 case Attribute::Dereferenceable: 960 case Attribute::DereferenceableOrNull: 961 case Attribute::ElementType: 962 case Attribute::InAlloca: 963 case Attribute::InReg: 964 case Attribute::Nest: 965 case Attribute::NoAlias: 966 case Attribute::NoCapture: 967 case Attribute::NoUndef: 968 case Attribute::NonNull: 969 case Attribute::Preallocated: 970 case Attribute::ReadNone: 971 case Attribute::ReadOnly: 972 case Attribute::Returned: 973 case Attribute::SExt: 974 case Attribute::StructRet: 975 case Attribute::SwiftError: 976 case Attribute::SwiftSelf: 977 case Attribute::SwiftAsync: 978 case Attribute::ZExt: 979 case Attribute::ImmArg: 980 case Attribute::ByRef: 981 case Attribute::WriteOnly: 982 case Attribute::Writable: 983 case Attribute::DeadOnUnwind: 984 case Attribute::Range: 985 case Attribute::Initializes: 986 case Attribute::NoExt: 987 // These are not really attributes. 988 case Attribute::None: 989 case Attribute::EndAttrKinds: 990 case Attribute::EmptyKey: 991 case Attribute::TombstoneKey: 992 llvm_unreachable("Not a function attribute"); 993 } 994 995 newFunction->addFnAttr(Attr); 996 } 997 998 // Create scalar and aggregate iterators to name all of the arguments we 999 // inserted. 1000 Function::arg_iterator ScalarAI = newFunction->arg_begin(); 1001 1002 // Set names and attributes for input and output arguments. 1003 ScalarAI = newFunction->arg_begin(); 1004 for (Value *input : inputs) { 1005 if (StructValues.contains(input)) 1006 continue; 1007 1008 ScalarAI->setName(input->getName()); 1009 if (input->isSwiftError()) 1010 newFunction->addParamAttr(ScalarAI - newFunction->arg_begin(), 1011 Attribute::SwiftError); 1012 ++ScalarAI; 1013 } 1014 for (Value *output : outputs) { 1015 if (StructValues.contains(output)) 1016 continue; 1017 1018 ScalarAI->setName(output->getName() + ".out"); 1019 ++ScalarAI; 1020 } 1021 1022 // Update the entry count of the function. 1023 if (BFI) { 1024 auto Count = BFI->getProfileCountFromFreq(EntryFreq); 1025 if (Count.has_value()) 1026 newFunction->setEntryCount( 1027 ProfileCount(*Count, Function::PCT_Real)); // FIXME 1028 } 1029 1030 return newFunction; 1031 } 1032 1033 /// If the original function has debug info, we have to add a debug location 1034 /// to the new branch instruction from the artificial entry block. 1035 /// We use the debug location of the first instruction in the extracted 1036 /// blocks, as there is no other equivalent line in the source code. 1037 static void applyFirstDebugLoc(Function *oldFunction, 1038 ArrayRef<BasicBlock *> Blocks, 1039 Instruction *BranchI) { 1040 if (oldFunction->getSubprogram()) { 1041 any_of(Blocks, [&BranchI](const BasicBlock *BB) { 1042 return any_of(*BB, [&BranchI](const Instruction &I) { 1043 if (!I.getDebugLoc()) 1044 return false; 1045 // Don't use source locations attached to debug-intrinsics: they could 1046 // be from completely unrelated scopes. 1047 if (isa<DbgInfoIntrinsic>(I)) 1048 return false; 1049 BranchI->setDebugLoc(I.getDebugLoc()); 1050 return true; 1051 }); 1052 }); 1053 } 1054 } 1055 1056 /// Erase lifetime.start markers which reference inputs to the extraction 1057 /// region, and insert the referenced memory into \p LifetimesStart. 1058 /// 1059 /// The extraction region is defined by a set of blocks (\p Blocks), and a set 1060 /// of allocas which will be moved from the caller function into the extracted 1061 /// function (\p SunkAllocas). 1062 static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks, 1063 const SetVector<Value *> &SunkAllocas, 1064 SetVector<Value *> &LifetimesStart) { 1065 for (BasicBlock *BB : Blocks) { 1066 for (Instruction &I : llvm::make_early_inc_range(*BB)) { 1067 auto *II = dyn_cast<IntrinsicInst>(&I); 1068 if (!II || !II->isLifetimeStartOrEnd()) 1069 continue; 1070 1071 // Get the memory operand of the lifetime marker. If the underlying 1072 // object is a sunk alloca, or is otherwise defined in the extraction 1073 // region, the lifetime marker must not be erased. 1074 Value *Mem = II->getOperand(1)->stripInBoundsOffsets(); 1075 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem)) 1076 continue; 1077 1078 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 1079 LifetimesStart.insert(Mem); 1080 II->eraseFromParent(); 1081 } 1082 } 1083 } 1084 1085 /// Insert lifetime start/end markers surrounding the call to the new function 1086 /// for objects defined in the caller. 1087 static void insertLifetimeMarkersSurroundingCall( 1088 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd, 1089 CallInst *TheCall) { 1090 LLVMContext &Ctx = M->getContext(); 1091 auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1); 1092 Instruction *Term = TheCall->getParent()->getTerminator(); 1093 1094 // Emit lifetime markers for the pointers given in \p Objects. Insert the 1095 // markers before the call if \p InsertBefore, and after the call otherwise. 1096 auto insertMarkers = [&](Intrinsic::ID MarkerFunc, ArrayRef<Value *> Objects, 1097 bool InsertBefore) { 1098 for (Value *Mem : Objects) { 1099 assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() == 1100 TheCall->getFunction()) && 1101 "Input memory not defined in original function"); 1102 1103 Function *Func = 1104 Intrinsic::getOrInsertDeclaration(M, MarkerFunc, Mem->getType()); 1105 auto Marker = CallInst::Create(Func, {NegativeOne, Mem}); 1106 if (InsertBefore) 1107 Marker->insertBefore(TheCall); 1108 else 1109 Marker->insertBefore(Term); 1110 } 1111 }; 1112 1113 if (!LifetimesStart.empty()) { 1114 insertMarkers(Intrinsic::lifetime_start, LifetimesStart, 1115 /*InsertBefore=*/true); 1116 } 1117 1118 if (!LifetimesEnd.empty()) { 1119 insertMarkers(Intrinsic::lifetime_end, LifetimesEnd, 1120 /*InsertBefore=*/false); 1121 } 1122 } 1123 1124 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 1125 auto newFuncIt = newFunction->begin(); 1126 for (BasicBlock *Block : Blocks) { 1127 // Delete the basic block from the old function, and the list of blocks 1128 Block->removeFromParent(); 1129 1130 // Insert this basic block into the new function 1131 // Insert the original blocks after the entry block created 1132 // for the new function. The entry block may be followed 1133 // by a set of exit blocks at this point, but these exit 1134 // blocks better be placed at the end of the new function. 1135 newFuncIt = newFunction->insert(std::next(newFuncIt), Block); 1136 } 1137 } 1138 1139 void CodeExtractor::calculateNewCallTerminatorWeights( 1140 BasicBlock *CodeReplacer, 1141 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, 1142 BranchProbabilityInfo *BPI) { 1143 using Distribution = BlockFrequencyInfoImplBase::Distribution; 1144 using BlockNode = BlockFrequencyInfoImplBase::BlockNode; 1145 1146 // Update the branch weights for the exit block. 1147 Instruction *TI = CodeReplacer->getTerminator(); 1148 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); 1149 1150 // Block Frequency distribution with dummy node. 1151 Distribution BranchDist; 1152 1153 SmallVector<BranchProbability, 4> EdgeProbabilities( 1154 TI->getNumSuccessors(), BranchProbability::getUnknown()); 1155 1156 // Add each of the frequencies of the successors. 1157 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { 1158 BlockNode ExitNode(i); 1159 uint64_t ExitFreq = ExitWeights.lookup(TI->getSuccessor(i)).getFrequency(); 1160 if (ExitFreq != 0) 1161 BranchDist.addExit(ExitNode, ExitFreq); 1162 else 1163 EdgeProbabilities[i] = BranchProbability::getZero(); 1164 } 1165 1166 // Check for no total weight. 1167 if (BranchDist.Total == 0) { 1168 BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities); 1169 return; 1170 } 1171 1172 // Normalize the distribution so that they can fit in unsigned. 1173 BranchDist.normalize(); 1174 1175 // Create normalized branch weights and set the metadata. 1176 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { 1177 const auto &Weight = BranchDist.Weights[I]; 1178 1179 // Get the weight and update the current BFI. 1180 BranchWeights[Weight.TargetNode.Index] = Weight.Amount; 1181 BranchProbability BP(Weight.Amount, BranchDist.Total); 1182 EdgeProbabilities[Weight.TargetNode.Index] = BP; 1183 } 1184 BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities); 1185 TI->setMetadata( 1186 LLVMContext::MD_prof, 1187 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); 1188 } 1189 1190 /// Erase debug info intrinsics which refer to values in \p F but aren't in 1191 /// \p F. 1192 static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) { 1193 for (Instruction &I : instructions(F)) { 1194 SmallVector<DbgVariableIntrinsic *, 4> DbgUsers; 1195 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords; 1196 findDbgUsers(DbgUsers, &I, &DbgVariableRecords); 1197 for (DbgVariableIntrinsic *DVI : DbgUsers) 1198 if (DVI->getFunction() != &F) 1199 DVI->eraseFromParent(); 1200 for (DbgVariableRecord *DVR : DbgVariableRecords) 1201 if (DVR->getFunction() != &F) 1202 DVR->eraseFromParent(); 1203 } 1204 } 1205 1206 /// Fix up the debug info in the old and new functions by pointing line 1207 /// locations and debug intrinsics to the new subprogram scope, and by deleting 1208 /// intrinsics which point to values outside of the new function. 1209 static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc, 1210 CallInst &TheCall) { 1211 DISubprogram *OldSP = OldFunc.getSubprogram(); 1212 LLVMContext &Ctx = OldFunc.getContext(); 1213 1214 if (!OldSP) { 1215 // Erase any debug info the new function contains. 1216 stripDebugInfo(NewFunc); 1217 // Make sure the old function doesn't contain any non-local metadata refs. 1218 eraseDebugIntrinsicsWithNonLocalRefs(NewFunc); 1219 return; 1220 } 1221 1222 // Create a subprogram for the new function. Leave out a description of the 1223 // function arguments, as the parameters don't correspond to anything at the 1224 // source level. 1225 assert(OldSP->getUnit() && "Missing compile unit for subprogram"); 1226 DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false, 1227 OldSP->getUnit()); 1228 auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray({})); 1229 DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition | 1230 DISubprogram::SPFlagOptimized | 1231 DISubprogram::SPFlagLocalToUnit; 1232 auto NewSP = DIB.createFunction( 1233 OldSP->getUnit(), NewFunc.getName(), NewFunc.getName(), OldSP->getFile(), 1234 /*LineNo=*/0, SPType, /*ScopeLine=*/0, DINode::FlagZero, SPFlags); 1235 NewFunc.setSubprogram(NewSP); 1236 1237 auto IsInvalidLocation = [&NewFunc](Value *Location) { 1238 // Location is invalid if it isn't a constant or an instruction, or is an 1239 // instruction but isn't in the new function. 1240 if (!Location || 1241 (!isa<Constant>(Location) && !isa<Instruction>(Location))) 1242 return true; 1243 Instruction *LocationInst = dyn_cast<Instruction>(Location); 1244 return LocationInst && LocationInst->getFunction() != &NewFunc; 1245 }; 1246 1247 // Debug intrinsics in the new function need to be updated in one of two 1248 // ways: 1249 // 1) They need to be deleted, because they describe a value in the old 1250 // function. 1251 // 2) They need to point to fresh metadata, e.g. because they currently 1252 // point to a variable in the wrong scope. 1253 SmallDenseMap<DINode *, DINode *> RemappedMetadata; 1254 SmallVector<Instruction *, 4> DebugIntrinsicsToDelete; 1255 SmallVector<DbgVariableRecord *, 4> DVRsToDelete; 1256 DenseMap<const MDNode *, MDNode *> Cache; 1257 1258 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar) { 1259 DINode *&NewVar = RemappedMetadata[OldVar]; 1260 if (!NewVar) { 1261 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram( 1262 *OldVar->getScope(), *NewSP, Ctx, Cache); 1263 NewVar = DIB.createAutoVariable( 1264 NewScope, OldVar->getName(), OldVar->getFile(), OldVar->getLine(), 1265 OldVar->getType(), /*AlwaysPreserve=*/false, DINode::FlagZero, 1266 OldVar->getAlignInBits()); 1267 } 1268 return cast<DILocalVariable>(NewVar); 1269 }; 1270 1271 auto UpdateDbgLabel = [&](auto *LabelRecord) { 1272 // Point the label record to a fresh label within the new function if 1273 // the record was not inlined from some other function. 1274 if (LabelRecord->getDebugLoc().getInlinedAt()) 1275 return; 1276 DILabel *OldLabel = LabelRecord->getLabel(); 1277 DINode *&NewLabel = RemappedMetadata[OldLabel]; 1278 if (!NewLabel) { 1279 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram( 1280 *OldLabel->getScope(), *NewSP, Ctx, Cache); 1281 NewLabel = DILabel::get(Ctx, NewScope, OldLabel->getName(), 1282 OldLabel->getFile(), OldLabel->getLine()); 1283 } 1284 LabelRecord->setLabel(cast<DILabel>(NewLabel)); 1285 }; 1286 1287 auto UpdateDbgRecordsOnInst = [&](Instruction &I) -> void { 1288 for (DbgRecord &DR : I.getDbgRecordRange()) { 1289 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1290 UpdateDbgLabel(DLR); 1291 continue; 1292 } 1293 1294 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1295 // Apply the two updates that dbg.values get: invalid operands, and 1296 // variable metadata fixup. 1297 if (any_of(DVR.location_ops(), IsInvalidLocation)) { 1298 DVRsToDelete.push_back(&DVR); 1299 continue; 1300 } 1301 if (DVR.isDbgAssign() && IsInvalidLocation(DVR.getAddress())) { 1302 DVRsToDelete.push_back(&DVR); 1303 continue; 1304 } 1305 if (!DVR.getDebugLoc().getInlinedAt()) 1306 DVR.setVariable(GetUpdatedDIVariable(DVR.getVariable())); 1307 } 1308 }; 1309 1310 for (Instruction &I : instructions(NewFunc)) { 1311 UpdateDbgRecordsOnInst(I); 1312 1313 auto *DII = dyn_cast<DbgInfoIntrinsic>(&I); 1314 if (!DII) 1315 continue; 1316 1317 // Point the intrinsic to a fresh label within the new function if the 1318 // intrinsic was not inlined from some other function. 1319 if (auto *DLI = dyn_cast<DbgLabelInst>(&I)) { 1320 UpdateDbgLabel(DLI); 1321 continue; 1322 } 1323 1324 auto *DVI = cast<DbgVariableIntrinsic>(DII); 1325 // If any of the used locations are invalid, delete the intrinsic. 1326 if (any_of(DVI->location_ops(), IsInvalidLocation)) { 1327 DebugIntrinsicsToDelete.push_back(DVI); 1328 continue; 1329 } 1330 // DbgAssign intrinsics have an extra Value argument: 1331 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI); 1332 DAI && IsInvalidLocation(DAI->getAddress())) { 1333 DebugIntrinsicsToDelete.push_back(DVI); 1334 continue; 1335 } 1336 // If the variable was in the scope of the old function, i.e. it was not 1337 // inlined, point the intrinsic to a fresh variable within the new function. 1338 if (!DVI->getDebugLoc().getInlinedAt()) 1339 DVI->setVariable(GetUpdatedDIVariable(DVI->getVariable())); 1340 } 1341 1342 for (auto *DII : DebugIntrinsicsToDelete) 1343 DII->eraseFromParent(); 1344 for (auto *DVR : DVRsToDelete) 1345 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR); 1346 DIB.finalizeSubprogram(NewSP); 1347 1348 // Fix up the scope information attached to the line locations and the 1349 // debug assignment metadata in the new function. 1350 DenseMap<DIAssignID *, DIAssignID *> AssignmentIDMap; 1351 for (Instruction &I : instructions(NewFunc)) { 1352 if (const DebugLoc &DL = I.getDebugLoc()) 1353 I.setDebugLoc( 1354 DebugLoc::replaceInlinedAtSubprogram(DL, *NewSP, Ctx, Cache)); 1355 for (DbgRecord &DR : I.getDbgRecordRange()) 1356 DR.setDebugLoc(DebugLoc::replaceInlinedAtSubprogram(DR.getDebugLoc(), 1357 *NewSP, Ctx, Cache)); 1358 1359 // Loop info metadata may contain line locations. Fix them up. 1360 auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * { 1361 if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 1362 return DebugLoc::replaceInlinedAtSubprogram(Loc, *NewSP, Ctx, Cache); 1363 return MD; 1364 }; 1365 updateLoopMetadataDebugLocations(I, updateLoopInfoLoc); 1366 at::remapAssignID(AssignmentIDMap, I); 1367 } 1368 if (!TheCall.getDebugLoc()) 1369 TheCall.setDebugLoc(DILocation::get(Ctx, 0, 0, OldSP)); 1370 1371 eraseDebugIntrinsicsWithNonLocalRefs(NewFunc); 1372 } 1373 1374 Function * 1375 CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) { 1376 ValueSet Inputs, Outputs; 1377 return extractCodeRegion(CEAC, Inputs, Outputs); 1378 } 1379 1380 Function * 1381 CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC, 1382 ValueSet &inputs, ValueSet &outputs) { 1383 if (!isEligible()) 1384 return nullptr; 1385 1386 // Assumption: this is a single-entry code region, and the header is the first 1387 // block in the region. 1388 BasicBlock *header = *Blocks.begin(); 1389 Function *oldFunction = header->getParent(); 1390 1391 normalizeCFGForExtraction(header); 1392 1393 // Remove @llvm.assume calls that will be moved to the new function from the 1394 // old function's assumption cache. 1395 for (BasicBlock *Block : Blocks) { 1396 for (Instruction &I : llvm::make_early_inc_range(*Block)) { 1397 if (auto *AI = dyn_cast<AssumeInst>(&I)) { 1398 if (AC) 1399 AC->unregisterAssumption(AI); 1400 AI->eraseFromParent(); 1401 } 1402 } 1403 } 1404 1405 ValueSet SinkingCands, HoistingCands; 1406 BasicBlock *CommonExit = nullptr; 1407 findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit); 1408 assert(HoistingCands.empty() || CommonExit); 1409 1410 // Find inputs to, outputs from the code region. 1411 findInputsOutputs(inputs, outputs, SinkingCands); 1412 1413 // Collect objects which are inputs to the extraction region and also 1414 // referenced by lifetime start markers within it. The effects of these 1415 // markers must be replicated in the calling function to prevent the stack 1416 // coloring pass from merging slots which store input objects. 1417 ValueSet LifetimesStart; 1418 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart); 1419 1420 if (!HoistingCands.empty()) { 1421 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit); 1422 Instruction *TI = HoistToBlock->getTerminator(); 1423 for (auto *II : HoistingCands) 1424 cast<Instruction>(II)->moveBefore(TI); 1425 computeExtractedFuncRetVals(); 1426 } 1427 1428 // CFG/ExitBlocks must not change hereafter 1429 1430 // Calculate the entry frequency of the new function before we change the root 1431 // block. 1432 BlockFrequency EntryFreq; 1433 DenseMap<BasicBlock *, BlockFrequency> ExitWeights; 1434 if (BFI) { 1435 assert(BPI && "Both BPI and BFI are required to preserve profile info"); 1436 for (BasicBlock *Pred : predecessors(header)) { 1437 if (Blocks.count(Pred)) 1438 continue; 1439 EntryFreq += 1440 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); 1441 } 1442 1443 for (BasicBlock *Succ : ExtractedFuncRetVals) { 1444 for (BasicBlock *Block : predecessors(Succ)) { 1445 if (!Blocks.count(Block)) 1446 continue; 1447 1448 // Update the branch weight for this successor. 1449 BlockFrequency &BF = ExitWeights[Succ]; 1450 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, Succ); 1451 } 1452 } 1453 } 1454 1455 // Determine position for the replacement code. Do so before header is moved 1456 // to the new function. 1457 BasicBlock *ReplIP = header; 1458 while (ReplIP && Blocks.count(ReplIP)) 1459 ReplIP = ReplIP->getNextNode(); 1460 1461 // Construct new function based on inputs/outputs & add allocas for all defs. 1462 std::string SuffixToUse = 1463 Suffix.empty() 1464 ? (header->getName().empty() ? "extracted" : header->getName().str()) 1465 : Suffix; 1466 1467 ValueSet StructValues; 1468 StructType *StructTy; 1469 Function *newFunction = constructFunctionDeclaration( 1470 inputs, outputs, EntryFreq, oldFunction->getName() + "." + SuffixToUse, 1471 StructValues, StructTy); 1472 newFunction->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1473 1474 emitFunctionBody(inputs, outputs, StructValues, newFunction, StructTy, header, 1475 SinkingCands); 1476 1477 std::vector<Value *> Reloads; 1478 CallInst *TheCall = emitReplacerCall( 1479 inputs, outputs, StructValues, newFunction, StructTy, oldFunction, ReplIP, 1480 EntryFreq, LifetimesStart.getArrayRef(), Reloads); 1481 1482 insertReplacerCall(oldFunction, header, TheCall->getParent(), outputs, 1483 Reloads, ExitWeights); 1484 1485 fixupDebugInfoPostExtraction(*oldFunction, *newFunction, *TheCall); 1486 1487 LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) { 1488 newFunction->dump(); 1489 report_fatal_error("verification of newFunction failed!"); 1490 }); 1491 LLVM_DEBUG(if (verifyFunction(*oldFunction)) 1492 report_fatal_error("verification of oldFunction failed!")); 1493 LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC)) 1494 report_fatal_error("Stale Asumption cache for old Function!")); 1495 return newFunction; 1496 } 1497 1498 void CodeExtractor::normalizeCFGForExtraction(BasicBlock *&header) { 1499 // If we have any return instructions in the region, split those blocks so 1500 // that the return is not in the region. 1501 splitReturnBlocks(); 1502 1503 // If we have to split PHI nodes of the entry or exit blocks, do so now. 1504 severSplitPHINodesOfEntry(header); 1505 1506 // If a PHI in an exit block has multiple incoming values from the outlined 1507 // region, create a new PHI for those values within the region such that only 1508 // PHI itself becomes an output value, not each of its incoming values 1509 // individually. 1510 computeExtractedFuncRetVals(); 1511 severSplitPHINodesOfExits(); 1512 } 1513 1514 void CodeExtractor::computeExtractedFuncRetVals() { 1515 ExtractedFuncRetVals.clear(); 1516 1517 SmallPtrSet<BasicBlock *, 2> ExitBlocks; 1518 for (BasicBlock *Block : Blocks) { 1519 for (BasicBlock *Succ : successors(Block)) { 1520 if (Blocks.count(Succ)) 1521 continue; 1522 1523 bool IsNew = ExitBlocks.insert(Succ).second; 1524 if (IsNew) 1525 ExtractedFuncRetVals.push_back(Succ); 1526 } 1527 } 1528 } 1529 1530 Type *CodeExtractor::getSwitchType() { 1531 LLVMContext &Context = Blocks.front()->getContext(); 1532 1533 assert(ExtractedFuncRetVals.size() < 0xffff && 1534 "too many exit blocks for switch"); 1535 switch (ExtractedFuncRetVals.size()) { 1536 case 0: 1537 case 1: 1538 return Type::getVoidTy(Context); 1539 case 2: 1540 // Conditional branch, return a bool 1541 return Type::getInt1Ty(Context); 1542 default: 1543 return Type::getInt16Ty(Context); 1544 } 1545 } 1546 1547 void CodeExtractor::emitFunctionBody( 1548 const ValueSet &inputs, const ValueSet &outputs, 1549 const ValueSet &StructValues, Function *newFunction, 1550 StructType *StructArgTy, BasicBlock *header, const ValueSet &SinkingCands) { 1551 Function *oldFunction = header->getParent(); 1552 LLVMContext &Context = oldFunction->getContext(); 1553 1554 // The new function needs a root node because other nodes can branch to the 1555 // head of the region, but the entry node of a function cannot have preds. 1556 BasicBlock *newFuncRoot = 1557 BasicBlock::Create(Context, "newFuncRoot", newFunction); 1558 newFuncRoot->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1559 1560 // Now sink all instructions which only have non-phi uses inside the region. 1561 // Group the allocas at the start of the block, so that any bitcast uses of 1562 // the allocas are well-defined. 1563 for (auto *II : SinkingCands) { 1564 if (!isa<AllocaInst>(II)) { 1565 cast<Instruction>(II)->moveBefore(*newFuncRoot, 1566 newFuncRoot->getFirstInsertionPt()); 1567 } 1568 } 1569 for (auto *II : SinkingCands) { 1570 if (auto *AI = dyn_cast<AllocaInst>(II)) { 1571 AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt()); 1572 } 1573 } 1574 1575 Function::arg_iterator ScalarAI = newFunction->arg_begin(); 1576 Argument *AggArg = StructValues.empty() 1577 ? nullptr 1578 : newFunction->getArg(newFunction->arg_size() - 1); 1579 1580 // Rewrite all users of the inputs in the extracted region to use the 1581 // arguments (or appropriate addressing into struct) instead. 1582 SmallVector<Value *> NewValues; 1583 for (unsigned i = 0, e = inputs.size(), aggIdx = 0; i != e; ++i) { 1584 Value *RewriteVal; 1585 if (StructValues.contains(inputs[i])) { 1586 Value *Idx[2]; 1587 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 1588 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), aggIdx); 1589 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1590 StructArgTy, AggArg, Idx, "gep_" + inputs[i]->getName(), newFuncRoot); 1591 RewriteVal = new LoadInst(StructArgTy->getElementType(aggIdx), GEP, 1592 "loadgep_" + inputs[i]->getName(), newFuncRoot); 1593 ++aggIdx; 1594 } else 1595 RewriteVal = &*ScalarAI++; 1596 1597 NewValues.push_back(RewriteVal); 1598 } 1599 1600 moveCodeToFunction(newFunction); 1601 1602 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 1603 Value *RewriteVal = NewValues[i]; 1604 1605 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 1606 for (User *use : Users) 1607 if (Instruction *inst = dyn_cast<Instruction>(use)) 1608 if (Blocks.count(inst->getParent())) 1609 inst->replaceUsesOfWith(inputs[i], RewriteVal); 1610 } 1611 1612 // Since there may be multiple exits from the original region, make the new 1613 // function return an unsigned, switch on that number. This loop iterates 1614 // over all of the blocks in the extracted region, updating any terminator 1615 // instructions in the to-be-extracted region that branch to blocks that are 1616 // not in the region to be extracted. 1617 std::map<BasicBlock *, BasicBlock *> ExitBlockMap; 1618 1619 // Iterate over the previously collected targets, and create new blocks inside 1620 // the function to branch to. 1621 for (auto P : enumerate(ExtractedFuncRetVals)) { 1622 BasicBlock *OldTarget = P.value(); 1623 size_t SuccNum = P.index(); 1624 1625 BasicBlock *NewTarget = BasicBlock::Create( 1626 Context, OldTarget->getName() + ".exitStub", newFunction); 1627 ExitBlockMap[OldTarget] = NewTarget; 1628 1629 Value *brVal = nullptr; 1630 Type *RetTy = getSwitchType(); 1631 assert(ExtractedFuncRetVals.size() < 0xffff && 1632 "too many exit blocks for switch"); 1633 switch (ExtractedFuncRetVals.size()) { 1634 case 0: 1635 case 1: 1636 // No value needed. 1637 break; 1638 case 2: // Conditional branch, return a bool 1639 brVal = ConstantInt::get(RetTy, !SuccNum); 1640 break; 1641 default: 1642 brVal = ConstantInt::get(RetTy, SuccNum); 1643 break; 1644 } 1645 1646 ReturnInst::Create(Context, brVal, NewTarget); 1647 } 1648 1649 for (BasicBlock *Block : Blocks) { 1650 Instruction *TI = Block->getTerminator(); 1651 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 1652 if (Blocks.count(TI->getSuccessor(i))) 1653 continue; 1654 BasicBlock *OldTarget = TI->getSuccessor(i); 1655 // add a new basic block which returns the appropriate value 1656 BasicBlock *NewTarget = ExitBlockMap[OldTarget]; 1657 assert(NewTarget && "Unknown target block!"); 1658 1659 // rewrite the original branch instruction with this new target 1660 TI->setSuccessor(i, NewTarget); 1661 } 1662 } 1663 1664 // Loop over all of the PHI nodes in the header and exit blocks, and change 1665 // any references to the old incoming edge to be the new incoming edge. 1666 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 1667 PHINode *PN = cast<PHINode>(I); 1668 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1669 if (!Blocks.count(PN->getIncomingBlock(i))) 1670 PN->setIncomingBlock(i, newFuncRoot); 1671 } 1672 1673 // Connect newFunction entry block to new header. 1674 BranchInst *BranchI = BranchInst::Create(header, newFuncRoot); 1675 applyFirstDebugLoc(oldFunction, Blocks.getArrayRef(), BranchI); 1676 1677 // Store the arguments right after the definition of output value. 1678 // This should be proceeded after creating exit stubs to be ensure that invoke 1679 // result restore will be placed in the outlined function. 1680 ScalarAI = newFunction->arg_begin(); 1681 unsigned AggIdx = 0; 1682 1683 for (Value *Input : inputs) { 1684 if (StructValues.contains(Input)) 1685 ++AggIdx; 1686 else 1687 ++ScalarAI; 1688 } 1689 1690 for (Value *Output : outputs) { 1691 // Find proper insertion point. 1692 // In case Output is an invoke, we insert the store at the beginning in the 1693 // 'normal destination' BB. Otherwise we insert the store right after 1694 // Output. 1695 BasicBlock::iterator InsertPt; 1696 if (auto *InvokeI = dyn_cast<InvokeInst>(Output)) 1697 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt(); 1698 else if (auto *Phi = dyn_cast<PHINode>(Output)) 1699 InsertPt = Phi->getParent()->getFirstInsertionPt(); 1700 else if (auto *OutI = dyn_cast<Instruction>(Output)) 1701 InsertPt = std::next(OutI->getIterator()); 1702 else { 1703 // Globals don't need to be updated, just advance to the next argument. 1704 if (StructValues.contains(Output)) 1705 ++AggIdx; 1706 else 1707 ++ScalarAI; 1708 continue; 1709 } 1710 1711 assert((InsertPt->getFunction() == newFunction || 1712 Blocks.count(InsertPt->getParent())) && 1713 "InsertPt should be in new function"); 1714 1715 if (StructValues.contains(Output)) { 1716 assert(AggArg && "Number of aggregate output arguments should match " 1717 "the number of defined values"); 1718 Value *Idx[2]; 1719 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1720 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx); 1721 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1722 StructArgTy, AggArg, Idx, "gep_" + Output->getName(), InsertPt); 1723 new StoreInst(Output, GEP, InsertPt); 1724 ++AggIdx; 1725 } else { 1726 assert(ScalarAI != newFunction->arg_end() && 1727 "Number of scalar output arguments should match " 1728 "the number of defined values"); 1729 new StoreInst(Output, &*ScalarAI, InsertPt); 1730 ++ScalarAI; 1731 } 1732 } 1733 1734 if (ExtractedFuncRetVals.empty()) { 1735 // Mark the new function `noreturn` if applicable. Terminators which resume 1736 // exception propagation are treated as returning instructions. This is to 1737 // avoid inserting traps after calls to outlined functions which unwind. 1738 if (none_of(Blocks, [](const BasicBlock *BB) { 1739 const Instruction *Term = BB->getTerminator(); 1740 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term); 1741 })) 1742 newFunction->setDoesNotReturn(); 1743 } 1744 } 1745 1746 CallInst *CodeExtractor::emitReplacerCall( 1747 const ValueSet &inputs, const ValueSet &outputs, 1748 const ValueSet &StructValues, Function *newFunction, 1749 StructType *StructArgTy, Function *oldFunction, BasicBlock *ReplIP, 1750 BlockFrequency EntryFreq, ArrayRef<Value *> LifetimesStart, 1751 std::vector<Value *> &Reloads) { 1752 LLVMContext &Context = oldFunction->getContext(); 1753 Module *M = oldFunction->getParent(); 1754 const DataLayout &DL = M->getDataLayout(); 1755 1756 // This takes place of the original loop 1757 BasicBlock *codeReplacer = 1758 BasicBlock::Create(Context, "codeRepl", oldFunction, ReplIP); 1759 codeReplacer->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1760 BasicBlock *AllocaBlock = 1761 AllocationBlock ? AllocationBlock : &oldFunction->getEntryBlock(); 1762 AllocaBlock->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1763 1764 // Update the entry count of the function. 1765 if (BFI) 1766 BFI->setBlockFreq(codeReplacer, EntryFreq); 1767 1768 std::vector<Value *> params; 1769 1770 // Add inputs as params, or to be filled into the struct 1771 for (Value *input : inputs) { 1772 if (StructValues.contains(input)) 1773 continue; 1774 1775 params.push_back(input); 1776 } 1777 1778 // Create allocas for the outputs 1779 std::vector<Value *> ReloadOutputs; 1780 for (Value *output : outputs) { 1781 if (StructValues.contains(output)) 1782 continue; 1783 1784 AllocaInst *alloca = new AllocaInst( 1785 output->getType(), DL.getAllocaAddrSpace(), nullptr, 1786 output->getName() + ".loc", AllocaBlock->getFirstInsertionPt()); 1787 params.push_back(alloca); 1788 ReloadOutputs.push_back(alloca); 1789 } 1790 1791 AllocaInst *Struct = nullptr; 1792 if (!StructValues.empty()) { 1793 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, 1794 "structArg", AllocaBlock->getFirstInsertionPt()); 1795 if (ArgsInZeroAddressSpace && DL.getAllocaAddrSpace() != 0) { 1796 auto *StructSpaceCast = new AddrSpaceCastInst( 1797 Struct, PointerType ::get(Context, 0), "structArg.ascast"); 1798 StructSpaceCast->insertAfter(Struct); 1799 params.push_back(StructSpaceCast); 1800 } else { 1801 params.push_back(Struct); 1802 } 1803 1804 unsigned AggIdx = 0; 1805 for (Value *input : inputs) { 1806 if (!StructValues.contains(input)) 1807 continue; 1808 1809 Value *Idx[2]; 1810 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1811 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx); 1812 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1813 StructArgTy, Struct, Idx, "gep_" + input->getName()); 1814 GEP->insertInto(codeReplacer, codeReplacer->end()); 1815 new StoreInst(input, GEP, codeReplacer); 1816 1817 ++AggIdx; 1818 } 1819 } 1820 1821 // Emit the call to the function 1822 CallInst *call = CallInst::Create( 1823 newFunction, params, ExtractedFuncRetVals.size() > 1 ? "targetBlock" : "", 1824 codeReplacer); 1825 1826 // Set swifterror parameter attributes. 1827 unsigned ParamIdx = 0; 1828 unsigned AggIdx = 0; 1829 for (auto input : inputs) { 1830 if (StructValues.contains(input)) { 1831 ++AggIdx; 1832 } else { 1833 if (input->isSwiftError()) 1834 call->addParamAttr(ParamIdx, Attribute::SwiftError); 1835 ++ParamIdx; 1836 } 1837 } 1838 1839 // Add debug location to the new call, if the original function has debug 1840 // info. In that case, the terminator of the entry block of the extracted 1841 // function contains the first debug location of the extracted function, 1842 // set in extractCodeRegion. 1843 if (codeReplacer->getParent()->getSubprogram()) { 1844 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc()) 1845 call->setDebugLoc(DL); 1846 } 1847 1848 // Reload the outputs passed in by reference, use the struct if output is in 1849 // the aggregate or reload from the scalar argument. 1850 for (unsigned i = 0, e = outputs.size(), scalarIdx = 0; i != e; ++i) { 1851 Value *Output = nullptr; 1852 if (StructValues.contains(outputs[i])) { 1853 Value *Idx[2]; 1854 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1855 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx); 1856 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1857 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); 1858 GEP->insertInto(codeReplacer, codeReplacer->end()); 1859 Output = GEP; 1860 ++AggIdx; 1861 } else { 1862 Output = ReloadOutputs[scalarIdx]; 1863 ++scalarIdx; 1864 } 1865 LoadInst *load = 1866 new LoadInst(outputs[i]->getType(), Output, 1867 outputs[i]->getName() + ".reload", codeReplacer); 1868 Reloads.push_back(load); 1869 } 1870 1871 // Now we can emit a switch statement using the call as a value. 1872 SwitchInst *TheSwitch = 1873 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 1874 codeReplacer, 0, codeReplacer); 1875 for (auto P : enumerate(ExtractedFuncRetVals)) { 1876 BasicBlock *OldTarget = P.value(); 1877 size_t SuccNum = P.index(); 1878 1879 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), SuccNum), 1880 OldTarget); 1881 } 1882 1883 // Now that we've done the deed, simplify the switch instruction. 1884 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 1885 switch (ExtractedFuncRetVals.size()) { 1886 case 0: 1887 // There are no successors (the block containing the switch itself), which 1888 // means that previously this was the last part of the function, and hence 1889 // this should be rewritten as a `ret` or `unreachable`. 1890 if (newFunction->doesNotReturn()) { 1891 // If fn is no return, end with an unreachable terminator. 1892 (void)new UnreachableInst(Context, TheSwitch->getIterator()); 1893 } else if (OldFnRetTy->isVoidTy()) { 1894 // We have no return value. 1895 ReturnInst::Create(Context, nullptr, 1896 TheSwitch->getIterator()); // Return void 1897 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 1898 // return what we have 1899 ReturnInst::Create(Context, TheSwitch->getCondition(), 1900 TheSwitch->getIterator()); 1901 } else { 1902 // Otherwise we must have code extracted an unwind or something, just 1903 // return whatever we want. 1904 ReturnInst::Create(Context, Constant::getNullValue(OldFnRetTy), 1905 TheSwitch->getIterator()); 1906 } 1907 1908 TheSwitch->eraseFromParent(); 1909 break; 1910 case 1: 1911 // Only a single destination, change the switch into an unconditional 1912 // branch. 1913 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getIterator()); 1914 TheSwitch->eraseFromParent(); 1915 break; 1916 case 2: 1917 // Only two destinations, convert to a condition branch. 1918 // Remark: This also swaps the target branches: 1919 // 0 -> false -> getSuccessor(2); 1 -> true -> getSuccessor(1) 1920 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 1921 call, TheSwitch->getIterator()); 1922 TheSwitch->eraseFromParent(); 1923 break; 1924 default: 1925 // Otherwise, make the default destination of the switch instruction be one 1926 // of the other successors. 1927 TheSwitch->setCondition(call); 1928 TheSwitch->setDefaultDest( 1929 TheSwitch->getSuccessor(ExtractedFuncRetVals.size())); 1930 // Remove redundant case 1931 TheSwitch->removeCase( 1932 SwitchInst::CaseIt(TheSwitch, ExtractedFuncRetVals.size() - 1)); 1933 break; 1934 } 1935 1936 // Insert lifetime markers around the reloads of any output values. The 1937 // allocas output values are stored in are only in-use in the codeRepl block. 1938 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call); 1939 1940 // Replicate the effects of any lifetime start/end markers which referenced 1941 // input objects in the extraction region by placing markers around the call. 1942 insertLifetimeMarkersSurroundingCall(oldFunction->getParent(), LifetimesStart, 1943 {}, call); 1944 1945 return call; 1946 } 1947 1948 void CodeExtractor::insertReplacerCall( 1949 Function *oldFunction, BasicBlock *header, BasicBlock *codeReplacer, 1950 const ValueSet &outputs, ArrayRef<Value *> Reloads, 1951 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights) { 1952 1953 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 1954 // within the new function. This must be done before we lose track of which 1955 // blocks were originally in the code region. 1956 std::vector<User *> Users(header->user_begin(), header->user_end()); 1957 for (auto &U : Users) 1958 // The BasicBlock which contains the branch is not in the region 1959 // modify the branch target to a new block 1960 if (Instruction *I = dyn_cast<Instruction>(U)) 1961 if (I->isTerminator() && I->getFunction() == oldFunction && 1962 !Blocks.count(I->getParent())) 1963 I->replaceUsesOfWith(header, codeReplacer); 1964 1965 // When moving the code region it is sufficient to replace all uses to the 1966 // extracted function values. Since the original definition's block 1967 // dominated its use, it will also be dominated by codeReplacer's switch 1968 // which joined multiple exit blocks. 1969 for (BasicBlock *ExitBB : ExtractedFuncRetVals) 1970 for (PHINode &PN : ExitBB->phis()) { 1971 Value *IncomingCodeReplacerVal = nullptr; 1972 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1973 // Ignore incoming values from outside of the extracted region. 1974 if (!Blocks.count(PN.getIncomingBlock(i))) 1975 continue; 1976 1977 // Ensure that there is only one incoming value from codeReplacer. 1978 if (!IncomingCodeReplacerVal) { 1979 PN.setIncomingBlock(i, codeReplacer); 1980 IncomingCodeReplacerVal = PN.getIncomingValue(i); 1981 } else 1982 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) && 1983 "PHI has two incompatbile incoming values from codeRepl"); 1984 } 1985 } 1986 1987 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 1988 Value *load = Reloads[i]; 1989 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 1990 for (User *U : Users) { 1991 Instruction *inst = cast<Instruction>(U); 1992 if (inst->getParent()->getParent() == oldFunction) 1993 inst->replaceUsesOfWith(outputs[i], load); 1994 } 1995 } 1996 1997 // Update the branch weights for the exit block. 1998 if (BFI && ExtractedFuncRetVals.size() > 1) 1999 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); 2000 } 2001 2002 bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc, 2003 const Function &NewFunc, 2004 AssumptionCache *AC) { 2005 for (auto AssumeVH : AC->assumptions()) { 2006 auto *I = dyn_cast_or_null<CallInst>(AssumeVH); 2007 if (!I) 2008 continue; 2009 2010 // There shouldn't be any llvm.assume intrinsics in the new function. 2011 if (I->getFunction() != &OldFunc) 2012 return true; 2013 2014 // There shouldn't be any stale affected values in the assumption cache 2015 // that were previously in the old function, but that have now been moved 2016 // to the new function. 2017 for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) { 2018 auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH); 2019 if (!AffectedCI) 2020 continue; 2021 if (AffectedCI->getFunction() != &OldFunc) 2022 return true; 2023 auto *AssumedInst = cast<Instruction>(AffectedCI->getOperand(0)); 2024 if (AssumedInst->getFunction() != &OldFunc) 2025 return true; 2026 } 2027 } 2028 return false; 2029 } 2030 2031 void CodeExtractor::excludeArgFromAggregate(Value *Arg) { 2032 ExcludeArgsFromAggregate.insert(Arg); 2033 } 2034