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::SanitizeType: 939 case Attribute::SanitizeHWAddress: 940 case Attribute::SanitizeMemTag: 941 case Attribute::SanitizeRealtime: 942 case Attribute::SanitizeRealtimeBlocking: 943 case Attribute::SpeculativeLoadHardening: 944 case Attribute::StackProtect: 945 case Attribute::StackProtectReq: 946 case Attribute::StackProtectStrong: 947 case Attribute::StrictFP: 948 case Attribute::UWTable: 949 case Attribute::VScaleRange: 950 case Attribute::NoCfCheck: 951 case Attribute::MustProgress: 952 case Attribute::NoProfile: 953 case Attribute::SkipProfile: 954 break; 955 // These attributes cannot be applied to functions. 956 case Attribute::Alignment: 957 case Attribute::AllocatedPointer: 958 case Attribute::AllocAlign: 959 case Attribute::ByVal: 960 case Attribute::Dereferenceable: 961 case Attribute::DereferenceableOrNull: 962 case Attribute::ElementType: 963 case Attribute::InAlloca: 964 case Attribute::InReg: 965 case Attribute::Nest: 966 case Attribute::NoAlias: 967 case Attribute::NoCapture: 968 case Attribute::NoUndef: 969 case Attribute::NonNull: 970 case Attribute::Preallocated: 971 case Attribute::ReadNone: 972 case Attribute::ReadOnly: 973 case Attribute::Returned: 974 case Attribute::SExt: 975 case Attribute::StructRet: 976 case Attribute::SwiftError: 977 case Attribute::SwiftSelf: 978 case Attribute::SwiftAsync: 979 case Attribute::ZExt: 980 case Attribute::ImmArg: 981 case Attribute::ByRef: 982 case Attribute::WriteOnly: 983 case Attribute::Writable: 984 case Attribute::DeadOnUnwind: 985 case Attribute::Range: 986 case Attribute::Initializes: 987 case Attribute::NoExt: 988 // These are not really attributes. 989 case Attribute::None: 990 case Attribute::EndAttrKinds: 991 case Attribute::EmptyKey: 992 case Attribute::TombstoneKey: 993 llvm_unreachable("Not a function attribute"); 994 } 995 996 newFunction->addFnAttr(Attr); 997 } 998 999 // Create scalar and aggregate iterators to name all of the arguments we 1000 // inserted. 1001 Function::arg_iterator ScalarAI = newFunction->arg_begin(); 1002 1003 // Set names and attributes for input and output arguments. 1004 ScalarAI = newFunction->arg_begin(); 1005 for (Value *input : inputs) { 1006 if (StructValues.contains(input)) 1007 continue; 1008 1009 ScalarAI->setName(input->getName()); 1010 if (input->isSwiftError()) 1011 newFunction->addParamAttr(ScalarAI - newFunction->arg_begin(), 1012 Attribute::SwiftError); 1013 ++ScalarAI; 1014 } 1015 for (Value *output : outputs) { 1016 if (StructValues.contains(output)) 1017 continue; 1018 1019 ScalarAI->setName(output->getName() + ".out"); 1020 ++ScalarAI; 1021 } 1022 1023 // Update the entry count of the function. 1024 if (BFI) { 1025 auto Count = BFI->getProfileCountFromFreq(EntryFreq); 1026 if (Count.has_value()) 1027 newFunction->setEntryCount( 1028 ProfileCount(*Count, Function::PCT_Real)); // FIXME 1029 } 1030 1031 return newFunction; 1032 } 1033 1034 /// If the original function has debug info, we have to add a debug location 1035 /// to the new branch instruction from the artificial entry block. 1036 /// We use the debug location of the first instruction in the extracted 1037 /// blocks, as there is no other equivalent line in the source code. 1038 static void applyFirstDebugLoc(Function *oldFunction, 1039 ArrayRef<BasicBlock *> Blocks, 1040 Instruction *BranchI) { 1041 if (oldFunction->getSubprogram()) { 1042 any_of(Blocks, [&BranchI](const BasicBlock *BB) { 1043 return any_of(*BB, [&BranchI](const Instruction &I) { 1044 if (!I.getDebugLoc()) 1045 return false; 1046 // Don't use source locations attached to debug-intrinsics: they could 1047 // be from completely unrelated scopes. 1048 if (isa<DbgInfoIntrinsic>(I)) 1049 return false; 1050 BranchI->setDebugLoc(I.getDebugLoc()); 1051 return true; 1052 }); 1053 }); 1054 } 1055 } 1056 1057 /// Erase lifetime.start markers which reference inputs to the extraction 1058 /// region, and insert the referenced memory into \p LifetimesStart. 1059 /// 1060 /// The extraction region is defined by a set of blocks (\p Blocks), and a set 1061 /// of allocas which will be moved from the caller function into the extracted 1062 /// function (\p SunkAllocas). 1063 static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks, 1064 const SetVector<Value *> &SunkAllocas, 1065 SetVector<Value *> &LifetimesStart) { 1066 for (BasicBlock *BB : Blocks) { 1067 for (Instruction &I : llvm::make_early_inc_range(*BB)) { 1068 auto *II = dyn_cast<IntrinsicInst>(&I); 1069 if (!II || !II->isLifetimeStartOrEnd()) 1070 continue; 1071 1072 // Get the memory operand of the lifetime marker. If the underlying 1073 // object is a sunk alloca, or is otherwise defined in the extraction 1074 // region, the lifetime marker must not be erased. 1075 Value *Mem = II->getOperand(1)->stripInBoundsOffsets(); 1076 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem)) 1077 continue; 1078 1079 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 1080 LifetimesStart.insert(Mem); 1081 II->eraseFromParent(); 1082 } 1083 } 1084 } 1085 1086 /// Insert lifetime start/end markers surrounding the call to the new function 1087 /// for objects defined in the caller. 1088 static void insertLifetimeMarkersSurroundingCall( 1089 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd, 1090 CallInst *TheCall) { 1091 LLVMContext &Ctx = M->getContext(); 1092 auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1); 1093 Instruction *Term = TheCall->getParent()->getTerminator(); 1094 1095 // Emit lifetime markers for the pointers given in \p Objects. Insert the 1096 // markers before the call if \p InsertBefore, and after the call otherwise. 1097 auto insertMarkers = [&](Intrinsic::ID MarkerFunc, ArrayRef<Value *> Objects, 1098 bool InsertBefore) { 1099 for (Value *Mem : Objects) { 1100 assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() == 1101 TheCall->getFunction()) && 1102 "Input memory not defined in original function"); 1103 1104 Function *Func = 1105 Intrinsic::getOrInsertDeclaration(M, MarkerFunc, Mem->getType()); 1106 auto Marker = CallInst::Create(Func, {NegativeOne, Mem}); 1107 if (InsertBefore) 1108 Marker->insertBefore(TheCall); 1109 else 1110 Marker->insertBefore(Term); 1111 } 1112 }; 1113 1114 if (!LifetimesStart.empty()) { 1115 insertMarkers(Intrinsic::lifetime_start, LifetimesStart, 1116 /*InsertBefore=*/true); 1117 } 1118 1119 if (!LifetimesEnd.empty()) { 1120 insertMarkers(Intrinsic::lifetime_end, LifetimesEnd, 1121 /*InsertBefore=*/false); 1122 } 1123 } 1124 1125 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 1126 auto newFuncIt = newFunction->begin(); 1127 for (BasicBlock *Block : Blocks) { 1128 // Delete the basic block from the old function, and the list of blocks 1129 Block->removeFromParent(); 1130 1131 // Insert this basic block into the new function 1132 // Insert the original blocks after the entry block created 1133 // for the new function. The entry block may be followed 1134 // by a set of exit blocks at this point, but these exit 1135 // blocks better be placed at the end of the new function. 1136 newFuncIt = newFunction->insert(std::next(newFuncIt), Block); 1137 } 1138 } 1139 1140 void CodeExtractor::calculateNewCallTerminatorWeights( 1141 BasicBlock *CodeReplacer, 1142 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, 1143 BranchProbabilityInfo *BPI) { 1144 using Distribution = BlockFrequencyInfoImplBase::Distribution; 1145 using BlockNode = BlockFrequencyInfoImplBase::BlockNode; 1146 1147 // Update the branch weights for the exit block. 1148 Instruction *TI = CodeReplacer->getTerminator(); 1149 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); 1150 1151 // Block Frequency distribution with dummy node. 1152 Distribution BranchDist; 1153 1154 SmallVector<BranchProbability, 4> EdgeProbabilities( 1155 TI->getNumSuccessors(), BranchProbability::getUnknown()); 1156 1157 // Add each of the frequencies of the successors. 1158 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { 1159 BlockNode ExitNode(i); 1160 uint64_t ExitFreq = ExitWeights.lookup(TI->getSuccessor(i)).getFrequency(); 1161 if (ExitFreq != 0) 1162 BranchDist.addExit(ExitNode, ExitFreq); 1163 else 1164 EdgeProbabilities[i] = BranchProbability::getZero(); 1165 } 1166 1167 // Check for no total weight. 1168 if (BranchDist.Total == 0) { 1169 BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities); 1170 return; 1171 } 1172 1173 // Normalize the distribution so that they can fit in unsigned. 1174 BranchDist.normalize(); 1175 1176 // Create normalized branch weights and set the metadata. 1177 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { 1178 const auto &Weight = BranchDist.Weights[I]; 1179 1180 // Get the weight and update the current BFI. 1181 BranchWeights[Weight.TargetNode.Index] = Weight.Amount; 1182 BranchProbability BP(Weight.Amount, BranchDist.Total); 1183 EdgeProbabilities[Weight.TargetNode.Index] = BP; 1184 } 1185 BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities); 1186 TI->setMetadata( 1187 LLVMContext::MD_prof, 1188 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); 1189 } 1190 1191 /// Erase debug info intrinsics which refer to values in \p F but aren't in 1192 /// \p F. 1193 static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) { 1194 for (Instruction &I : instructions(F)) { 1195 SmallVector<DbgVariableIntrinsic *, 4> DbgUsers; 1196 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords; 1197 findDbgUsers(DbgUsers, &I, &DbgVariableRecords); 1198 for (DbgVariableIntrinsic *DVI : DbgUsers) 1199 if (DVI->getFunction() != &F) 1200 DVI->eraseFromParent(); 1201 for (DbgVariableRecord *DVR : DbgVariableRecords) 1202 if (DVR->getFunction() != &F) 1203 DVR->eraseFromParent(); 1204 } 1205 } 1206 1207 /// Fix up the debug info in the old and new functions by pointing line 1208 /// locations and debug intrinsics to the new subprogram scope, and by deleting 1209 /// intrinsics which point to values outside of the new function. 1210 static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc, 1211 CallInst &TheCall) { 1212 DISubprogram *OldSP = OldFunc.getSubprogram(); 1213 LLVMContext &Ctx = OldFunc.getContext(); 1214 1215 if (!OldSP) { 1216 // Erase any debug info the new function contains. 1217 stripDebugInfo(NewFunc); 1218 // Make sure the old function doesn't contain any non-local metadata refs. 1219 eraseDebugIntrinsicsWithNonLocalRefs(NewFunc); 1220 return; 1221 } 1222 1223 // Create a subprogram for the new function. Leave out a description of the 1224 // function arguments, as the parameters don't correspond to anything at the 1225 // source level. 1226 assert(OldSP->getUnit() && "Missing compile unit for subprogram"); 1227 DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false, 1228 OldSP->getUnit()); 1229 auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray({})); 1230 DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition | 1231 DISubprogram::SPFlagOptimized | 1232 DISubprogram::SPFlagLocalToUnit; 1233 auto NewSP = DIB.createFunction( 1234 OldSP->getUnit(), NewFunc.getName(), NewFunc.getName(), OldSP->getFile(), 1235 /*LineNo=*/0, SPType, /*ScopeLine=*/0, DINode::FlagZero, SPFlags); 1236 NewFunc.setSubprogram(NewSP); 1237 1238 auto IsInvalidLocation = [&NewFunc](Value *Location) { 1239 // Location is invalid if it isn't a constant or an instruction, or is an 1240 // instruction but isn't in the new function. 1241 if (!Location || 1242 (!isa<Constant>(Location) && !isa<Instruction>(Location))) 1243 return true; 1244 Instruction *LocationInst = dyn_cast<Instruction>(Location); 1245 return LocationInst && LocationInst->getFunction() != &NewFunc; 1246 }; 1247 1248 // Debug intrinsics in the new function need to be updated in one of two 1249 // ways: 1250 // 1) They need to be deleted, because they describe a value in the old 1251 // function. 1252 // 2) They need to point to fresh metadata, e.g. because they currently 1253 // point to a variable in the wrong scope. 1254 SmallDenseMap<DINode *, DINode *> RemappedMetadata; 1255 SmallVector<Instruction *, 4> DebugIntrinsicsToDelete; 1256 SmallVector<DbgVariableRecord *, 4> DVRsToDelete; 1257 DenseMap<const MDNode *, MDNode *> Cache; 1258 1259 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar) { 1260 DINode *&NewVar = RemappedMetadata[OldVar]; 1261 if (!NewVar) { 1262 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram( 1263 *OldVar->getScope(), *NewSP, Ctx, Cache); 1264 NewVar = DIB.createAutoVariable( 1265 NewScope, OldVar->getName(), OldVar->getFile(), OldVar->getLine(), 1266 OldVar->getType(), /*AlwaysPreserve=*/false, DINode::FlagZero, 1267 OldVar->getAlignInBits()); 1268 } 1269 return cast<DILocalVariable>(NewVar); 1270 }; 1271 1272 auto UpdateDbgLabel = [&](auto *LabelRecord) { 1273 // Point the label record to a fresh label within the new function if 1274 // the record was not inlined from some other function. 1275 if (LabelRecord->getDebugLoc().getInlinedAt()) 1276 return; 1277 DILabel *OldLabel = LabelRecord->getLabel(); 1278 DINode *&NewLabel = RemappedMetadata[OldLabel]; 1279 if (!NewLabel) { 1280 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram( 1281 *OldLabel->getScope(), *NewSP, Ctx, Cache); 1282 NewLabel = DILabel::get(Ctx, NewScope, OldLabel->getName(), 1283 OldLabel->getFile(), OldLabel->getLine()); 1284 } 1285 LabelRecord->setLabel(cast<DILabel>(NewLabel)); 1286 }; 1287 1288 auto UpdateDbgRecordsOnInst = [&](Instruction &I) -> void { 1289 for (DbgRecord &DR : I.getDbgRecordRange()) { 1290 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1291 UpdateDbgLabel(DLR); 1292 continue; 1293 } 1294 1295 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1296 // Apply the two updates that dbg.values get: invalid operands, and 1297 // variable metadata fixup. 1298 if (any_of(DVR.location_ops(), IsInvalidLocation)) { 1299 DVRsToDelete.push_back(&DVR); 1300 continue; 1301 } 1302 if (DVR.isDbgAssign() && IsInvalidLocation(DVR.getAddress())) { 1303 DVRsToDelete.push_back(&DVR); 1304 continue; 1305 } 1306 if (!DVR.getDebugLoc().getInlinedAt()) 1307 DVR.setVariable(GetUpdatedDIVariable(DVR.getVariable())); 1308 } 1309 }; 1310 1311 for (Instruction &I : instructions(NewFunc)) { 1312 UpdateDbgRecordsOnInst(I); 1313 1314 auto *DII = dyn_cast<DbgInfoIntrinsic>(&I); 1315 if (!DII) 1316 continue; 1317 1318 // Point the intrinsic to a fresh label within the new function if the 1319 // intrinsic was not inlined from some other function. 1320 if (auto *DLI = dyn_cast<DbgLabelInst>(&I)) { 1321 UpdateDbgLabel(DLI); 1322 continue; 1323 } 1324 1325 auto *DVI = cast<DbgVariableIntrinsic>(DII); 1326 // If any of the used locations are invalid, delete the intrinsic. 1327 if (any_of(DVI->location_ops(), IsInvalidLocation)) { 1328 DebugIntrinsicsToDelete.push_back(DVI); 1329 continue; 1330 } 1331 // DbgAssign intrinsics have an extra Value argument: 1332 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI); 1333 DAI && IsInvalidLocation(DAI->getAddress())) { 1334 DebugIntrinsicsToDelete.push_back(DVI); 1335 continue; 1336 } 1337 // If the variable was in the scope of the old function, i.e. it was not 1338 // inlined, point the intrinsic to a fresh variable within the new function. 1339 if (!DVI->getDebugLoc().getInlinedAt()) 1340 DVI->setVariable(GetUpdatedDIVariable(DVI->getVariable())); 1341 } 1342 1343 for (auto *DII : DebugIntrinsicsToDelete) 1344 DII->eraseFromParent(); 1345 for (auto *DVR : DVRsToDelete) 1346 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR); 1347 DIB.finalizeSubprogram(NewSP); 1348 1349 // Fix up the scope information attached to the line locations and the 1350 // debug assignment metadata in the new function. 1351 DenseMap<DIAssignID *, DIAssignID *> AssignmentIDMap; 1352 for (Instruction &I : instructions(NewFunc)) { 1353 if (const DebugLoc &DL = I.getDebugLoc()) 1354 I.setDebugLoc( 1355 DebugLoc::replaceInlinedAtSubprogram(DL, *NewSP, Ctx, Cache)); 1356 for (DbgRecord &DR : I.getDbgRecordRange()) 1357 DR.setDebugLoc(DebugLoc::replaceInlinedAtSubprogram(DR.getDebugLoc(), 1358 *NewSP, Ctx, Cache)); 1359 1360 // Loop info metadata may contain line locations. Fix them up. 1361 auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * { 1362 if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 1363 return DebugLoc::replaceInlinedAtSubprogram(Loc, *NewSP, Ctx, Cache); 1364 return MD; 1365 }; 1366 updateLoopMetadataDebugLocations(I, updateLoopInfoLoc); 1367 at::remapAssignID(AssignmentIDMap, I); 1368 } 1369 if (!TheCall.getDebugLoc()) 1370 TheCall.setDebugLoc(DILocation::get(Ctx, 0, 0, OldSP)); 1371 1372 eraseDebugIntrinsicsWithNonLocalRefs(NewFunc); 1373 } 1374 1375 Function * 1376 CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) { 1377 ValueSet Inputs, Outputs; 1378 return extractCodeRegion(CEAC, Inputs, Outputs); 1379 } 1380 1381 Function * 1382 CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC, 1383 ValueSet &inputs, ValueSet &outputs) { 1384 if (!isEligible()) 1385 return nullptr; 1386 1387 // Assumption: this is a single-entry code region, and the header is the first 1388 // block in the region. 1389 BasicBlock *header = *Blocks.begin(); 1390 Function *oldFunction = header->getParent(); 1391 1392 normalizeCFGForExtraction(header); 1393 1394 // Remove @llvm.assume calls that will be moved to the new function from the 1395 // old function's assumption cache. 1396 for (BasicBlock *Block : Blocks) { 1397 for (Instruction &I : llvm::make_early_inc_range(*Block)) { 1398 if (auto *AI = dyn_cast<AssumeInst>(&I)) { 1399 if (AC) 1400 AC->unregisterAssumption(AI); 1401 AI->eraseFromParent(); 1402 } 1403 } 1404 } 1405 1406 ValueSet SinkingCands, HoistingCands; 1407 BasicBlock *CommonExit = nullptr; 1408 findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit); 1409 assert(HoistingCands.empty() || CommonExit); 1410 1411 // Find inputs to, outputs from the code region. 1412 findInputsOutputs(inputs, outputs, SinkingCands); 1413 1414 // Collect objects which are inputs to the extraction region and also 1415 // referenced by lifetime start markers within it. The effects of these 1416 // markers must be replicated in the calling function to prevent the stack 1417 // coloring pass from merging slots which store input objects. 1418 ValueSet LifetimesStart; 1419 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart); 1420 1421 if (!HoistingCands.empty()) { 1422 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit); 1423 Instruction *TI = HoistToBlock->getTerminator(); 1424 for (auto *II : HoistingCands) 1425 cast<Instruction>(II)->moveBefore(TI); 1426 computeExtractedFuncRetVals(); 1427 } 1428 1429 // CFG/ExitBlocks must not change hereafter 1430 1431 // Calculate the entry frequency of the new function before we change the root 1432 // block. 1433 BlockFrequency EntryFreq; 1434 DenseMap<BasicBlock *, BlockFrequency> ExitWeights; 1435 if (BFI) { 1436 assert(BPI && "Both BPI and BFI are required to preserve profile info"); 1437 for (BasicBlock *Pred : predecessors(header)) { 1438 if (Blocks.count(Pred)) 1439 continue; 1440 EntryFreq += 1441 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); 1442 } 1443 1444 for (BasicBlock *Succ : ExtractedFuncRetVals) { 1445 for (BasicBlock *Block : predecessors(Succ)) { 1446 if (!Blocks.count(Block)) 1447 continue; 1448 1449 // Update the branch weight for this successor. 1450 BlockFrequency &BF = ExitWeights[Succ]; 1451 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, Succ); 1452 } 1453 } 1454 } 1455 1456 // Determine position for the replacement code. Do so before header is moved 1457 // to the new function. 1458 BasicBlock *ReplIP = header; 1459 while (ReplIP && Blocks.count(ReplIP)) 1460 ReplIP = ReplIP->getNextNode(); 1461 1462 // Construct new function based on inputs/outputs & add allocas for all defs. 1463 std::string SuffixToUse = 1464 Suffix.empty() 1465 ? (header->getName().empty() ? "extracted" : header->getName().str()) 1466 : Suffix; 1467 1468 ValueSet StructValues; 1469 StructType *StructTy = nullptr; 1470 Function *newFunction = constructFunctionDeclaration( 1471 inputs, outputs, EntryFreq, oldFunction->getName() + "." + SuffixToUse, 1472 StructValues, StructTy); 1473 newFunction->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1474 1475 emitFunctionBody(inputs, outputs, StructValues, newFunction, StructTy, header, 1476 SinkingCands); 1477 1478 std::vector<Value *> Reloads; 1479 CallInst *TheCall = emitReplacerCall( 1480 inputs, outputs, StructValues, newFunction, StructTy, oldFunction, ReplIP, 1481 EntryFreq, LifetimesStart.getArrayRef(), Reloads); 1482 1483 insertReplacerCall(oldFunction, header, TheCall->getParent(), outputs, 1484 Reloads, ExitWeights); 1485 1486 fixupDebugInfoPostExtraction(*oldFunction, *newFunction, *TheCall); 1487 1488 LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) { 1489 newFunction->dump(); 1490 report_fatal_error("verification of newFunction failed!"); 1491 }); 1492 LLVM_DEBUG(if (verifyFunction(*oldFunction)) 1493 report_fatal_error("verification of oldFunction failed!")); 1494 LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC)) 1495 report_fatal_error("Stale Asumption cache for old Function!")); 1496 return newFunction; 1497 } 1498 1499 void CodeExtractor::normalizeCFGForExtraction(BasicBlock *&header) { 1500 // If we have any return instructions in the region, split those blocks so 1501 // that the return is not in the region. 1502 splitReturnBlocks(); 1503 1504 // If we have to split PHI nodes of the entry or exit blocks, do so now. 1505 severSplitPHINodesOfEntry(header); 1506 1507 // If a PHI in an exit block has multiple incoming values from the outlined 1508 // region, create a new PHI for those values within the region such that only 1509 // PHI itself becomes an output value, not each of its incoming values 1510 // individually. 1511 computeExtractedFuncRetVals(); 1512 severSplitPHINodesOfExits(); 1513 } 1514 1515 void CodeExtractor::computeExtractedFuncRetVals() { 1516 ExtractedFuncRetVals.clear(); 1517 1518 SmallPtrSet<BasicBlock *, 2> ExitBlocks; 1519 for (BasicBlock *Block : Blocks) { 1520 for (BasicBlock *Succ : successors(Block)) { 1521 if (Blocks.count(Succ)) 1522 continue; 1523 1524 bool IsNew = ExitBlocks.insert(Succ).second; 1525 if (IsNew) 1526 ExtractedFuncRetVals.push_back(Succ); 1527 } 1528 } 1529 } 1530 1531 Type *CodeExtractor::getSwitchType() { 1532 LLVMContext &Context = Blocks.front()->getContext(); 1533 1534 assert(ExtractedFuncRetVals.size() < 0xffff && 1535 "too many exit blocks for switch"); 1536 switch (ExtractedFuncRetVals.size()) { 1537 case 0: 1538 case 1: 1539 return Type::getVoidTy(Context); 1540 case 2: 1541 // Conditional branch, return a bool 1542 return Type::getInt1Ty(Context); 1543 default: 1544 return Type::getInt16Ty(Context); 1545 } 1546 } 1547 1548 void CodeExtractor::emitFunctionBody( 1549 const ValueSet &inputs, const ValueSet &outputs, 1550 const ValueSet &StructValues, Function *newFunction, 1551 StructType *StructArgTy, BasicBlock *header, const ValueSet &SinkingCands) { 1552 Function *oldFunction = header->getParent(); 1553 LLVMContext &Context = oldFunction->getContext(); 1554 1555 // The new function needs a root node because other nodes can branch to the 1556 // head of the region, but the entry node of a function cannot have preds. 1557 BasicBlock *newFuncRoot = 1558 BasicBlock::Create(Context, "newFuncRoot", newFunction); 1559 newFuncRoot->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1560 1561 // Now sink all instructions which only have non-phi uses inside the region. 1562 // Group the allocas at the start of the block, so that any bitcast uses of 1563 // the allocas are well-defined. 1564 for (auto *II : SinkingCands) { 1565 if (!isa<AllocaInst>(II)) { 1566 cast<Instruction>(II)->moveBefore(*newFuncRoot, 1567 newFuncRoot->getFirstInsertionPt()); 1568 } 1569 } 1570 for (auto *II : SinkingCands) { 1571 if (auto *AI = dyn_cast<AllocaInst>(II)) { 1572 AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt()); 1573 } 1574 } 1575 1576 Function::arg_iterator ScalarAI = newFunction->arg_begin(); 1577 Argument *AggArg = StructValues.empty() 1578 ? nullptr 1579 : newFunction->getArg(newFunction->arg_size() - 1); 1580 1581 // Rewrite all users of the inputs in the extracted region to use the 1582 // arguments (or appropriate addressing into struct) instead. 1583 SmallVector<Value *> NewValues; 1584 for (unsigned i = 0, e = inputs.size(), aggIdx = 0; i != e; ++i) { 1585 Value *RewriteVal; 1586 if (StructValues.contains(inputs[i])) { 1587 Value *Idx[2]; 1588 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 1589 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), aggIdx); 1590 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1591 StructArgTy, AggArg, Idx, "gep_" + inputs[i]->getName(), newFuncRoot); 1592 RewriteVal = new LoadInst(StructArgTy->getElementType(aggIdx), GEP, 1593 "loadgep_" + inputs[i]->getName(), newFuncRoot); 1594 ++aggIdx; 1595 } else 1596 RewriteVal = &*ScalarAI++; 1597 1598 NewValues.push_back(RewriteVal); 1599 } 1600 1601 moveCodeToFunction(newFunction); 1602 1603 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 1604 Value *RewriteVal = NewValues[i]; 1605 1606 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 1607 for (User *use : Users) 1608 if (Instruction *inst = dyn_cast<Instruction>(use)) 1609 if (Blocks.count(inst->getParent())) 1610 inst->replaceUsesOfWith(inputs[i], RewriteVal); 1611 } 1612 1613 // Since there may be multiple exits from the original region, make the new 1614 // function return an unsigned, switch on that number. This loop iterates 1615 // over all of the blocks in the extracted region, updating any terminator 1616 // instructions in the to-be-extracted region that branch to blocks that are 1617 // not in the region to be extracted. 1618 std::map<BasicBlock *, BasicBlock *> ExitBlockMap; 1619 1620 // Iterate over the previously collected targets, and create new blocks inside 1621 // the function to branch to. 1622 for (auto P : enumerate(ExtractedFuncRetVals)) { 1623 BasicBlock *OldTarget = P.value(); 1624 size_t SuccNum = P.index(); 1625 1626 BasicBlock *NewTarget = BasicBlock::Create( 1627 Context, OldTarget->getName() + ".exitStub", newFunction); 1628 ExitBlockMap[OldTarget] = NewTarget; 1629 1630 Value *brVal = nullptr; 1631 Type *RetTy = getSwitchType(); 1632 assert(ExtractedFuncRetVals.size() < 0xffff && 1633 "too many exit blocks for switch"); 1634 switch (ExtractedFuncRetVals.size()) { 1635 case 0: 1636 case 1: 1637 // No value needed. 1638 break; 1639 case 2: // Conditional branch, return a bool 1640 brVal = ConstantInt::get(RetTy, !SuccNum); 1641 break; 1642 default: 1643 brVal = ConstantInt::get(RetTy, SuccNum); 1644 break; 1645 } 1646 1647 ReturnInst::Create(Context, brVal, NewTarget); 1648 } 1649 1650 for (BasicBlock *Block : Blocks) { 1651 Instruction *TI = Block->getTerminator(); 1652 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 1653 if (Blocks.count(TI->getSuccessor(i))) 1654 continue; 1655 BasicBlock *OldTarget = TI->getSuccessor(i); 1656 // add a new basic block which returns the appropriate value 1657 BasicBlock *NewTarget = ExitBlockMap[OldTarget]; 1658 assert(NewTarget && "Unknown target block!"); 1659 1660 // rewrite the original branch instruction with this new target 1661 TI->setSuccessor(i, NewTarget); 1662 } 1663 } 1664 1665 // Loop over all of the PHI nodes in the header and exit blocks, and change 1666 // any references to the old incoming edge to be the new incoming edge. 1667 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 1668 PHINode *PN = cast<PHINode>(I); 1669 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1670 if (!Blocks.count(PN->getIncomingBlock(i))) 1671 PN->setIncomingBlock(i, newFuncRoot); 1672 } 1673 1674 // Connect newFunction entry block to new header. 1675 BranchInst *BranchI = BranchInst::Create(header, newFuncRoot); 1676 applyFirstDebugLoc(oldFunction, Blocks.getArrayRef(), BranchI); 1677 1678 // Store the arguments right after the definition of output value. 1679 // This should be proceeded after creating exit stubs to be ensure that invoke 1680 // result restore will be placed in the outlined function. 1681 ScalarAI = newFunction->arg_begin(); 1682 unsigned AggIdx = 0; 1683 1684 for (Value *Input : inputs) { 1685 if (StructValues.contains(Input)) 1686 ++AggIdx; 1687 else 1688 ++ScalarAI; 1689 } 1690 1691 for (Value *Output : outputs) { 1692 // Find proper insertion point. 1693 // In case Output is an invoke, we insert the store at the beginning in the 1694 // 'normal destination' BB. Otherwise we insert the store right after 1695 // Output. 1696 BasicBlock::iterator InsertPt; 1697 if (auto *InvokeI = dyn_cast<InvokeInst>(Output)) 1698 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt(); 1699 else if (auto *Phi = dyn_cast<PHINode>(Output)) 1700 InsertPt = Phi->getParent()->getFirstInsertionPt(); 1701 else if (auto *OutI = dyn_cast<Instruction>(Output)) 1702 InsertPt = std::next(OutI->getIterator()); 1703 else { 1704 // Globals don't need to be updated, just advance to the next argument. 1705 if (StructValues.contains(Output)) 1706 ++AggIdx; 1707 else 1708 ++ScalarAI; 1709 continue; 1710 } 1711 1712 assert((InsertPt->getFunction() == newFunction || 1713 Blocks.count(InsertPt->getParent())) && 1714 "InsertPt should be in new function"); 1715 1716 if (StructValues.contains(Output)) { 1717 assert(AggArg && "Number of aggregate output arguments should match " 1718 "the number of defined values"); 1719 Value *Idx[2]; 1720 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1721 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx); 1722 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1723 StructArgTy, AggArg, Idx, "gep_" + Output->getName(), InsertPt); 1724 new StoreInst(Output, GEP, InsertPt); 1725 ++AggIdx; 1726 } else { 1727 assert(ScalarAI != newFunction->arg_end() && 1728 "Number of scalar output arguments should match " 1729 "the number of defined values"); 1730 new StoreInst(Output, &*ScalarAI, InsertPt); 1731 ++ScalarAI; 1732 } 1733 } 1734 1735 if (ExtractedFuncRetVals.empty()) { 1736 // Mark the new function `noreturn` if applicable. Terminators which resume 1737 // exception propagation are treated as returning instructions. This is to 1738 // avoid inserting traps after calls to outlined functions which unwind. 1739 if (none_of(Blocks, [](const BasicBlock *BB) { 1740 const Instruction *Term = BB->getTerminator(); 1741 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term); 1742 })) 1743 newFunction->setDoesNotReturn(); 1744 } 1745 } 1746 1747 CallInst *CodeExtractor::emitReplacerCall( 1748 const ValueSet &inputs, const ValueSet &outputs, 1749 const ValueSet &StructValues, Function *newFunction, 1750 StructType *StructArgTy, Function *oldFunction, BasicBlock *ReplIP, 1751 BlockFrequency EntryFreq, ArrayRef<Value *> LifetimesStart, 1752 std::vector<Value *> &Reloads) { 1753 LLVMContext &Context = oldFunction->getContext(); 1754 Module *M = oldFunction->getParent(); 1755 const DataLayout &DL = M->getDataLayout(); 1756 1757 // This takes place of the original loop 1758 BasicBlock *codeReplacer = 1759 BasicBlock::Create(Context, "codeRepl", oldFunction, ReplIP); 1760 codeReplacer->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1761 BasicBlock *AllocaBlock = 1762 AllocationBlock ? AllocationBlock : &oldFunction->getEntryBlock(); 1763 AllocaBlock->IsNewDbgInfoFormat = oldFunction->IsNewDbgInfoFormat; 1764 1765 // Update the entry count of the function. 1766 if (BFI) 1767 BFI->setBlockFreq(codeReplacer, EntryFreq); 1768 1769 std::vector<Value *> params; 1770 1771 // Add inputs as params, or to be filled into the struct 1772 for (Value *input : inputs) { 1773 if (StructValues.contains(input)) 1774 continue; 1775 1776 params.push_back(input); 1777 } 1778 1779 // Create allocas for the outputs 1780 std::vector<Value *> ReloadOutputs; 1781 for (Value *output : outputs) { 1782 if (StructValues.contains(output)) 1783 continue; 1784 1785 AllocaInst *alloca = new AllocaInst( 1786 output->getType(), DL.getAllocaAddrSpace(), nullptr, 1787 output->getName() + ".loc", AllocaBlock->getFirstInsertionPt()); 1788 params.push_back(alloca); 1789 ReloadOutputs.push_back(alloca); 1790 } 1791 1792 AllocaInst *Struct = nullptr; 1793 if (!StructValues.empty()) { 1794 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, 1795 "structArg", AllocaBlock->getFirstInsertionPt()); 1796 if (ArgsInZeroAddressSpace && DL.getAllocaAddrSpace() != 0) { 1797 auto *StructSpaceCast = new AddrSpaceCastInst( 1798 Struct, PointerType ::get(Context, 0), "structArg.ascast"); 1799 StructSpaceCast->insertAfter(Struct); 1800 params.push_back(StructSpaceCast); 1801 } else { 1802 params.push_back(Struct); 1803 } 1804 1805 unsigned AggIdx = 0; 1806 for (Value *input : inputs) { 1807 if (!StructValues.contains(input)) 1808 continue; 1809 1810 Value *Idx[2]; 1811 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1812 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx); 1813 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1814 StructArgTy, Struct, Idx, "gep_" + input->getName()); 1815 GEP->insertInto(codeReplacer, codeReplacer->end()); 1816 new StoreInst(input, GEP, codeReplacer); 1817 1818 ++AggIdx; 1819 } 1820 } 1821 1822 // Emit the call to the function 1823 CallInst *call = CallInst::Create( 1824 newFunction, params, ExtractedFuncRetVals.size() > 1 ? "targetBlock" : "", 1825 codeReplacer); 1826 1827 // Set swifterror parameter attributes. 1828 unsigned ParamIdx = 0; 1829 unsigned AggIdx = 0; 1830 for (auto input : inputs) { 1831 if (StructValues.contains(input)) { 1832 ++AggIdx; 1833 } else { 1834 if (input->isSwiftError()) 1835 call->addParamAttr(ParamIdx, Attribute::SwiftError); 1836 ++ParamIdx; 1837 } 1838 } 1839 1840 // Add debug location to the new call, if the original function has debug 1841 // info. In that case, the terminator of the entry block of the extracted 1842 // function contains the first debug location of the extracted function, 1843 // set in extractCodeRegion. 1844 if (codeReplacer->getParent()->getSubprogram()) { 1845 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc()) 1846 call->setDebugLoc(DL); 1847 } 1848 1849 // Reload the outputs passed in by reference, use the struct if output is in 1850 // the aggregate or reload from the scalar argument. 1851 for (unsigned i = 0, e = outputs.size(), scalarIdx = 0; i != e; ++i) { 1852 Value *Output = nullptr; 1853 if (StructValues.contains(outputs[i])) { 1854 Value *Idx[2]; 1855 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1856 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx); 1857 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1858 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); 1859 GEP->insertInto(codeReplacer, codeReplacer->end()); 1860 Output = GEP; 1861 ++AggIdx; 1862 } else { 1863 Output = ReloadOutputs[scalarIdx]; 1864 ++scalarIdx; 1865 } 1866 LoadInst *load = 1867 new LoadInst(outputs[i]->getType(), Output, 1868 outputs[i]->getName() + ".reload", codeReplacer); 1869 Reloads.push_back(load); 1870 } 1871 1872 // Now we can emit a switch statement using the call as a value. 1873 SwitchInst *TheSwitch = 1874 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 1875 codeReplacer, 0, codeReplacer); 1876 for (auto P : enumerate(ExtractedFuncRetVals)) { 1877 BasicBlock *OldTarget = P.value(); 1878 size_t SuccNum = P.index(); 1879 1880 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), SuccNum), 1881 OldTarget); 1882 } 1883 1884 // Now that we've done the deed, simplify the switch instruction. 1885 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 1886 switch (ExtractedFuncRetVals.size()) { 1887 case 0: 1888 // There are no successors (the block containing the switch itself), which 1889 // means that previously this was the last part of the function, and hence 1890 // this should be rewritten as a `ret` or `unreachable`. 1891 if (newFunction->doesNotReturn()) { 1892 // If fn is no return, end with an unreachable terminator. 1893 (void)new UnreachableInst(Context, TheSwitch->getIterator()); 1894 } else if (OldFnRetTy->isVoidTy()) { 1895 // We have no return value. 1896 ReturnInst::Create(Context, nullptr, 1897 TheSwitch->getIterator()); // Return void 1898 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 1899 // return what we have 1900 ReturnInst::Create(Context, TheSwitch->getCondition(), 1901 TheSwitch->getIterator()); 1902 } else { 1903 // Otherwise we must have code extracted an unwind or something, just 1904 // return whatever we want. 1905 ReturnInst::Create(Context, Constant::getNullValue(OldFnRetTy), 1906 TheSwitch->getIterator()); 1907 } 1908 1909 TheSwitch->eraseFromParent(); 1910 break; 1911 case 1: 1912 // Only a single destination, change the switch into an unconditional 1913 // branch. 1914 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getIterator()); 1915 TheSwitch->eraseFromParent(); 1916 break; 1917 case 2: 1918 // Only two destinations, convert to a condition branch. 1919 // Remark: This also swaps the target branches: 1920 // 0 -> false -> getSuccessor(2); 1 -> true -> getSuccessor(1) 1921 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 1922 call, TheSwitch->getIterator()); 1923 TheSwitch->eraseFromParent(); 1924 break; 1925 default: 1926 // Otherwise, make the default destination of the switch instruction be one 1927 // of the other successors. 1928 TheSwitch->setCondition(call); 1929 TheSwitch->setDefaultDest( 1930 TheSwitch->getSuccessor(ExtractedFuncRetVals.size())); 1931 // Remove redundant case 1932 TheSwitch->removeCase( 1933 SwitchInst::CaseIt(TheSwitch, ExtractedFuncRetVals.size() - 1)); 1934 break; 1935 } 1936 1937 // Insert lifetime markers around the reloads of any output values. The 1938 // allocas output values are stored in are only in-use in the codeRepl block. 1939 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call); 1940 1941 // Replicate the effects of any lifetime start/end markers which referenced 1942 // input objects in the extraction region by placing markers around the call. 1943 insertLifetimeMarkersSurroundingCall(oldFunction->getParent(), LifetimesStart, 1944 {}, call); 1945 1946 return call; 1947 } 1948 1949 void CodeExtractor::insertReplacerCall( 1950 Function *oldFunction, BasicBlock *header, BasicBlock *codeReplacer, 1951 const ValueSet &outputs, ArrayRef<Value *> Reloads, 1952 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights) { 1953 1954 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 1955 // within the new function. This must be done before we lose track of which 1956 // blocks were originally in the code region. 1957 std::vector<User *> Users(header->user_begin(), header->user_end()); 1958 for (auto &U : Users) 1959 // The BasicBlock which contains the branch is not in the region 1960 // modify the branch target to a new block 1961 if (Instruction *I = dyn_cast<Instruction>(U)) 1962 if (I->isTerminator() && I->getFunction() == oldFunction && 1963 !Blocks.count(I->getParent())) 1964 I->replaceUsesOfWith(header, codeReplacer); 1965 1966 // When moving the code region it is sufficient to replace all uses to the 1967 // extracted function values. Since the original definition's block 1968 // dominated its use, it will also be dominated by codeReplacer's switch 1969 // which joined multiple exit blocks. 1970 for (BasicBlock *ExitBB : ExtractedFuncRetVals) 1971 for (PHINode &PN : ExitBB->phis()) { 1972 Value *IncomingCodeReplacerVal = nullptr; 1973 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1974 // Ignore incoming values from outside of the extracted region. 1975 if (!Blocks.count(PN.getIncomingBlock(i))) 1976 continue; 1977 1978 // Ensure that there is only one incoming value from codeReplacer. 1979 if (!IncomingCodeReplacerVal) { 1980 PN.setIncomingBlock(i, codeReplacer); 1981 IncomingCodeReplacerVal = PN.getIncomingValue(i); 1982 } else 1983 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) && 1984 "PHI has two incompatbile incoming values from codeRepl"); 1985 } 1986 } 1987 1988 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 1989 Value *load = Reloads[i]; 1990 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 1991 for (User *U : Users) { 1992 Instruction *inst = cast<Instruction>(U); 1993 if (inst->getParent()->getParent() == oldFunction) 1994 inst->replaceUsesOfWith(outputs[i], load); 1995 } 1996 } 1997 1998 // Update the branch weights for the exit block. 1999 if (BFI && ExtractedFuncRetVals.size() > 1) 2000 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); 2001 } 2002 2003 bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc, 2004 const Function &NewFunc, 2005 AssumptionCache *AC) { 2006 for (auto AssumeVH : AC->assumptions()) { 2007 auto *I = dyn_cast_or_null<CallInst>(AssumeVH); 2008 if (!I) 2009 continue; 2010 2011 // There shouldn't be any llvm.assume intrinsics in the new function. 2012 if (I->getFunction() != &OldFunc) 2013 return true; 2014 2015 // There shouldn't be any stale affected values in the assumption cache 2016 // that were previously in the old function, but that have now been moved 2017 // to the new function. 2018 for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) { 2019 auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH); 2020 if (!AffectedCI) 2021 continue; 2022 if (AffectedCI->getFunction() != &OldFunc) 2023 return true; 2024 auto *AssumedInst = cast<Instruction>(AffectedCI->getOperand(0)); 2025 if (AssumedInst->getFunction() != &OldFunc) 2026 return true; 2027 } 2028 } 2029 return false; 2030 } 2031 2032 void CodeExtractor::excludeArgFromAggregate(Value *Arg) { 2033 ExcludeArgsFromAggregate.insert(Arg); 2034 } 2035