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/Optional.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/Analysis/AssumptionCache.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 26 #include "llvm/Analysis/BranchProbabilityInfo.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/IR/Argument.h" 29 #include "llvm/IR/Attributes.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/CFG.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/GlobalValue.h" 39 #include "llvm/IR/InstrTypes.h" 40 #include "llvm/IR/Instruction.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/IntrinsicInst.h" 43 #include "llvm/IR/Intrinsics.h" 44 #include "llvm/IR/LLVMContext.h" 45 #include "llvm/IR/MDBuilder.h" 46 #include "llvm/IR/Module.h" 47 #include "llvm/IR/PatternMatch.h" 48 #include "llvm/IR/Type.h" 49 #include "llvm/IR/User.h" 50 #include "llvm/IR/Value.h" 51 #include "llvm/IR/Verifier.h" 52 #include "llvm/Pass.h" 53 #include "llvm/Support/BlockFrequency.h" 54 #include "llvm/Support/BranchProbability.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/ErrorHandling.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 61 #include "llvm/Transforms/Utils/Local.h" 62 #include <cassert> 63 #include <cstdint> 64 #include <iterator> 65 #include <map> 66 #include <set> 67 #include <utility> 68 #include <vector> 69 70 using namespace llvm; 71 using namespace llvm::PatternMatch; 72 using ProfileCount = Function::ProfileCount; 73 74 #define DEBUG_TYPE "code-extractor" 75 76 // Provide a command-line option to aggregate function arguments into a struct 77 // for functions produced by the code extractor. This is useful when converting 78 // extracted functions to pthread-based code, as only one argument (void*) can 79 // be passed in to pthread_create(). 80 static cl::opt<bool> 81 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 82 cl::desc("Aggregate arguments to code-extracted functions")); 83 84 /// Test whether a block is valid for extraction. 85 static bool isBlockValidForExtraction(const BasicBlock &BB, 86 const SetVector<BasicBlock *> &Result, 87 bool AllowVarArgs, bool AllowAlloca) { 88 // taking the address of a basic block moved to another function is illegal 89 if (BB.hasAddressTaken()) 90 return false; 91 92 // don't hoist code that uses another basicblock address, as it's likely to 93 // lead to unexpected behavior, like cross-function jumps 94 SmallPtrSet<User const *, 16> Visited; 95 SmallVector<User const *, 16> ToVisit; 96 97 for (Instruction const &Inst : BB) 98 ToVisit.push_back(&Inst); 99 100 while (!ToVisit.empty()) { 101 User const *Curr = ToVisit.pop_back_val(); 102 if (!Visited.insert(Curr).second) 103 continue; 104 if (isa<BlockAddress const>(Curr)) 105 return false; // even a reference to self is likely to be not compatible 106 107 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB) 108 continue; 109 110 for (auto const &U : Curr->operands()) { 111 if (auto *UU = dyn_cast<User>(U)) 112 ToVisit.push_back(UU); 113 } 114 } 115 116 // If explicitly requested, allow vastart and alloca. For invoke instructions 117 // verify that extraction is valid. 118 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 119 if (isa<AllocaInst>(I)) { 120 if (!AllowAlloca) 121 return false; 122 continue; 123 } 124 125 if (const auto *II = dyn_cast<InvokeInst>(I)) { 126 // Unwind destination (either a landingpad, catchswitch, or cleanuppad) 127 // must be a part of the subgraph which is being extracted. 128 if (auto *UBB = II->getUnwindDest()) 129 if (!Result.count(UBB)) 130 return false; 131 continue; 132 } 133 134 // All catch handlers of a catchswitch instruction as well as the unwind 135 // destination must be in the subgraph. 136 if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) { 137 if (auto *UBB = CSI->getUnwindDest()) 138 if (!Result.count(UBB)) 139 return false; 140 for (auto *HBB : CSI->handlers()) 141 if (!Result.count(const_cast<BasicBlock*>(HBB))) 142 return false; 143 continue; 144 } 145 146 // Make sure that entire catch handler is within subgraph. It is sufficient 147 // to check that catch return's block is in the list. 148 if (const auto *CPI = dyn_cast<CatchPadInst>(I)) { 149 for (const auto *U : CPI->users()) 150 if (const auto *CRI = dyn_cast<CatchReturnInst>(U)) 151 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) 152 return false; 153 continue; 154 } 155 156 // And do similar checks for cleanup handler - the entire handler must be 157 // in subgraph which is going to be extracted. For cleanup return should 158 // additionally check that the unwind destination is also in the subgraph. 159 if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) { 160 for (const auto *U : CPI->users()) 161 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U)) 162 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) 163 return false; 164 continue; 165 } 166 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) { 167 if (auto *UBB = CRI->getUnwindDest()) 168 if (!Result.count(UBB)) 169 return false; 170 continue; 171 } 172 173 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 174 if (const Function *F = CI->getCalledFunction()) { 175 auto IID = F->getIntrinsicID(); 176 if (IID == Intrinsic::vastart) { 177 if (AllowVarArgs) 178 continue; 179 else 180 return false; 181 } 182 183 // Currently, we miscompile outlined copies of eh_typid_for. There are 184 // proposals for fixing this in llvm.org/PR39545. 185 if (IID == Intrinsic::eh_typeid_for) 186 return false; 187 } 188 } 189 } 190 191 return true; 192 } 193 194 /// Build a set of blocks to extract if the input blocks are viable. 195 static SetVector<BasicBlock *> 196 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 197 bool AllowVarArgs, bool AllowAlloca) { 198 assert(!BBs.empty() && "The set of blocks to extract must be non-empty"); 199 SetVector<BasicBlock *> Result; 200 201 // Loop over the blocks, adding them to our set-vector, and aborting with an 202 // empty set if we encounter invalid blocks. 203 for (BasicBlock *BB : BBs) { 204 // If this block is dead, don't process it. 205 if (DT && !DT->isReachableFromEntry(BB)) 206 continue; 207 208 if (!Result.insert(BB)) 209 llvm_unreachable("Repeated basic blocks in extraction input"); 210 } 211 212 for (auto *BB : Result) { 213 if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca)) 214 return {}; 215 216 // Make sure that the first block is not a landing pad. 217 if (BB == Result.front()) { 218 if (BB->isEHPad()) { 219 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n"); 220 return {}; 221 } 222 continue; 223 } 224 225 // All blocks other than the first must not have predecessors outside of 226 // the subgraph which is being extracted. 227 for (auto *PBB : predecessors(BB)) 228 if (!Result.count(PBB)) { 229 LLVM_DEBUG( 230 dbgs() << "No blocks in this region may have entries from " 231 "outside the region except for the first block!\n"); 232 return {}; 233 } 234 } 235 236 return Result; 237 } 238 239 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 240 bool AggregateArgs, BlockFrequencyInfo *BFI, 241 BranchProbabilityInfo *BPI, AssumptionCache *AC, 242 bool AllowVarArgs, bool AllowAlloca, 243 std::string Suffix) 244 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 245 BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs), 246 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)), 247 Suffix(Suffix) {} 248 249 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, 250 BlockFrequencyInfo *BFI, 251 BranchProbabilityInfo *BPI, AssumptionCache *AC, 252 std::string Suffix) 253 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 254 BPI(BPI), AC(AC), AllowVarArgs(false), 255 Blocks(buildExtractionBlockSet(L.getBlocks(), &DT, 256 /* AllowVarArgs */ false, 257 /* AllowAlloca */ false)), 258 Suffix(Suffix) {} 259 260 /// definedInRegion - Return true if the specified value is defined in the 261 /// extracted region. 262 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 263 if (Instruction *I = dyn_cast<Instruction>(V)) 264 if (Blocks.count(I->getParent())) 265 return true; 266 return false; 267 } 268 269 /// definedInCaller - Return true if the specified value is defined in the 270 /// function being code extracted, but not in the region being extracted. 271 /// These values must be passed in as live-ins to the function. 272 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 273 if (isa<Argument>(V)) return true; 274 if (Instruction *I = dyn_cast<Instruction>(V)) 275 if (!Blocks.count(I->getParent())) 276 return true; 277 return false; 278 } 279 280 static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) { 281 BasicBlock *CommonExitBlock = nullptr; 282 auto hasNonCommonExitSucc = [&](BasicBlock *Block) { 283 for (auto *Succ : successors(Block)) { 284 // Internal edges, ok. 285 if (Blocks.count(Succ)) 286 continue; 287 if (!CommonExitBlock) { 288 CommonExitBlock = Succ; 289 continue; 290 } 291 if (CommonExitBlock == Succ) 292 continue; 293 294 return true; 295 } 296 return false; 297 }; 298 299 if (any_of(Blocks, hasNonCommonExitSucc)) 300 return nullptr; 301 302 return CommonExitBlock; 303 } 304 305 bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( 306 Instruction *Addr) const { 307 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets()); 308 Function *Func = (*Blocks.begin())->getParent(); 309 for (BasicBlock &BB : *Func) { 310 if (Blocks.count(&BB)) 311 continue; 312 for (Instruction &II : BB) { 313 if (isa<DbgInfoIntrinsic>(II)) 314 continue; 315 316 unsigned Opcode = II.getOpcode(); 317 Value *MemAddr = nullptr; 318 switch (Opcode) { 319 case Instruction::Store: 320 case Instruction::Load: { 321 if (Opcode == Instruction::Store) { 322 StoreInst *SI = cast<StoreInst>(&II); 323 MemAddr = SI->getPointerOperand(); 324 } else { 325 LoadInst *LI = cast<LoadInst>(&II); 326 MemAddr = LI->getPointerOperand(); 327 } 328 // Global variable can not be aliased with locals. 329 if (dyn_cast<Constant>(MemAddr)) 330 break; 331 Value *Base = MemAddr->stripInBoundsConstantOffsets(); 332 if (!dyn_cast<AllocaInst>(Base) || Base == AI) 333 return false; 334 break; 335 } 336 default: { 337 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II); 338 if (IntrInst) { 339 if (IntrInst->isLifetimeStartOrEnd()) 340 break; 341 return false; 342 } 343 // Treat all the other cases conservatively if it has side effects. 344 if (II.mayHaveSideEffects()) 345 return false; 346 } 347 } 348 } 349 } 350 351 return true; 352 } 353 354 BasicBlock * 355 CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) { 356 BasicBlock *SinglePredFromOutlineRegion = nullptr; 357 assert(!Blocks.count(CommonExitBlock) && 358 "Expect a block outside the region!"); 359 for (auto *Pred : predecessors(CommonExitBlock)) { 360 if (!Blocks.count(Pred)) 361 continue; 362 if (!SinglePredFromOutlineRegion) { 363 SinglePredFromOutlineRegion = Pred; 364 } else if (SinglePredFromOutlineRegion != Pred) { 365 SinglePredFromOutlineRegion = nullptr; 366 break; 367 } 368 } 369 370 if (SinglePredFromOutlineRegion) 371 return SinglePredFromOutlineRegion; 372 373 #ifndef NDEBUG 374 auto getFirstPHI = [](BasicBlock *BB) { 375 BasicBlock::iterator I = BB->begin(); 376 PHINode *FirstPhi = nullptr; 377 while (I != BB->end()) { 378 PHINode *Phi = dyn_cast<PHINode>(I); 379 if (!Phi) 380 break; 381 if (!FirstPhi) { 382 FirstPhi = Phi; 383 break; 384 } 385 } 386 return FirstPhi; 387 }; 388 // If there are any phi nodes, the single pred either exists or has already 389 // be created before code extraction. 390 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected"); 391 #endif 392 393 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock( 394 CommonExitBlock->getFirstNonPHI()->getIterator()); 395 396 for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock); 397 PI != PE;) { 398 BasicBlock *Pred = *PI++; 399 if (Blocks.count(Pred)) 400 continue; 401 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock); 402 } 403 // Now add the old exit block to the outline region. 404 Blocks.insert(CommonExitBlock); 405 return CommonExitBlock; 406 } 407 408 void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands, 409 BasicBlock *&ExitBlock) const { 410 Function *Func = (*Blocks.begin())->getParent(); 411 ExitBlock = getCommonExitBlock(Blocks); 412 413 for (BasicBlock &BB : *Func) { 414 if (Blocks.count(&BB)) 415 continue; 416 for (Instruction &II : BB) { 417 auto *AI = dyn_cast<AllocaInst>(&II); 418 if (!AI) 419 continue; 420 421 // Find the pair of life time markers for address 'Addr' that are either 422 // defined inside the outline region or can legally be shrinkwrapped into 423 // the outline region. If there are not other untracked uses of the 424 // address, return the pair of markers if found; otherwise return a pair 425 // of nullptr. 426 auto GetLifeTimeMarkers = 427 [&](Instruction *Addr, bool &SinkLifeStart, 428 bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> { 429 Instruction *LifeStart = nullptr, *LifeEnd = nullptr; 430 431 for (User *U : Addr->users()) { 432 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); 433 if (IntrInst) { 434 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) { 435 // Do not handle the case where AI has multiple start markers. 436 if (LifeStart) 437 return std::make_pair<Instruction *>(nullptr, nullptr); 438 LifeStart = IntrInst; 439 } 440 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) { 441 if (LifeEnd) 442 return std::make_pair<Instruction *>(nullptr, nullptr); 443 LifeEnd = IntrInst; 444 } 445 continue; 446 } 447 // Find untracked uses of the address, bail. 448 if (!definedInRegion(Blocks, U)) 449 return std::make_pair<Instruction *>(nullptr, nullptr); 450 } 451 452 if (!LifeStart || !LifeEnd) 453 return std::make_pair<Instruction *>(nullptr, nullptr); 454 455 SinkLifeStart = !definedInRegion(Blocks, LifeStart); 456 HoistLifeEnd = !definedInRegion(Blocks, LifeEnd); 457 // Do legality Check. 458 if ((SinkLifeStart || HoistLifeEnd) && 459 !isLegalToShrinkwrapLifetimeMarkers(Addr)) 460 return std::make_pair<Instruction *>(nullptr, nullptr); 461 462 // Check to see if we have a place to do hoisting, if not, bail. 463 if (HoistLifeEnd && !ExitBlock) 464 return std::make_pair<Instruction *>(nullptr, nullptr); 465 466 return std::make_pair(LifeStart, LifeEnd); 467 }; 468 469 bool SinkLifeStart = false, HoistLifeEnd = false; 470 auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd); 471 472 if (Markers.first) { 473 if (SinkLifeStart) 474 SinkCands.insert(Markers.first); 475 SinkCands.insert(AI); 476 if (HoistLifeEnd) 477 HoistCands.insert(Markers.second); 478 continue; 479 } 480 481 // Follow the bitcast. 482 Instruction *MarkerAddr = nullptr; 483 for (User *U : AI->users()) { 484 if (U->stripInBoundsConstantOffsets() == AI) { 485 SinkLifeStart = false; 486 HoistLifeEnd = false; 487 Instruction *Bitcast = cast<Instruction>(U); 488 Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd); 489 if (Markers.first) { 490 MarkerAddr = Bitcast; 491 continue; 492 } 493 } 494 495 // Found unknown use of AI. 496 if (!definedInRegion(Blocks, U)) { 497 MarkerAddr = nullptr; 498 break; 499 } 500 } 501 502 if (MarkerAddr) { 503 if (SinkLifeStart) 504 SinkCands.insert(Markers.first); 505 if (!definedInRegion(Blocks, MarkerAddr)) 506 SinkCands.insert(MarkerAddr); 507 SinkCands.insert(AI); 508 if (HoistLifeEnd) 509 HoistCands.insert(Markers.second); 510 } 511 } 512 } 513 } 514 515 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, 516 const ValueSet &SinkCands) const { 517 for (BasicBlock *BB : Blocks) { 518 // If a used value is defined outside the region, it's an input. If an 519 // instruction is used outside the region, it's an output. 520 for (Instruction &II : *BB) { 521 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE; 522 ++OI) { 523 Value *V = *OI; 524 if (!SinkCands.count(V) && definedInCaller(Blocks, V)) 525 Inputs.insert(V); 526 } 527 528 for (User *U : II.users()) 529 if (!definedInRegion(Blocks, U)) { 530 Outputs.insert(&II); 531 break; 532 } 533 } 534 } 535 } 536 537 /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside 538 /// of the region, we need to split the entry block of the region so that the 539 /// PHI node is easier to deal with. 540 void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) { 541 unsigned NumPredsFromRegion = 0; 542 unsigned NumPredsOutsideRegion = 0; 543 544 if (Header != &Header->getParent()->getEntryBlock()) { 545 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 546 if (!PN) return; // No PHI nodes. 547 548 // If the header node contains any PHI nodes, check to see if there is more 549 // than one entry from outside the region. If so, we need to sever the 550 // header block into two. 551 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 552 if (Blocks.count(PN->getIncomingBlock(i))) 553 ++NumPredsFromRegion; 554 else 555 ++NumPredsOutsideRegion; 556 557 // If there is one (or fewer) predecessor from outside the region, we don't 558 // need to do anything special. 559 if (NumPredsOutsideRegion <= 1) return; 560 } 561 562 // Otherwise, we need to split the header block into two pieces: one 563 // containing PHI nodes merging values from outside of the region, and a 564 // second that contains all of the code for the block and merges back any 565 // incoming values from inside of the region. 566 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); 567 568 // We only want to code extract the second block now, and it becomes the new 569 // header of the region. 570 BasicBlock *OldPred = Header; 571 Blocks.remove(OldPred); 572 Blocks.insert(NewBB); 573 Header = NewBB; 574 575 // Okay, now we need to adjust the PHI nodes and any branches from within the 576 // region to go to the new header block instead of the old header block. 577 if (NumPredsFromRegion) { 578 PHINode *PN = cast<PHINode>(OldPred->begin()); 579 // Loop over all of the predecessors of OldPred that are in the region, 580 // changing them to branch to NewBB instead. 581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 582 if (Blocks.count(PN->getIncomingBlock(i))) { 583 Instruction *TI = PN->getIncomingBlock(i)->getTerminator(); 584 TI->replaceUsesOfWith(OldPred, NewBB); 585 } 586 587 // Okay, everything within the region is now branching to the right block, we 588 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 589 BasicBlock::iterator AfterPHIs; 590 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 591 PHINode *PN = cast<PHINode>(AfterPHIs); 592 // Create a new PHI node in the new region, which has an incoming value 593 // from OldPred of PN. 594 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 595 PN->getName() + ".ce", &NewBB->front()); 596 PN->replaceAllUsesWith(NewPN); 597 NewPN->addIncoming(PN, OldPred); 598 599 // Loop over all of the incoming value in PN, moving them to NewPN if they 600 // are from the extracted region. 601 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 602 if (Blocks.count(PN->getIncomingBlock(i))) { 603 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 604 PN->removeIncomingValue(i); 605 --i; 606 } 607 } 608 } 609 } 610 } 611 612 /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from 613 /// outlined region, we split these PHIs on two: one with inputs from region 614 /// and other with remaining incoming blocks; then first PHIs are placed in 615 /// outlined region. 616 void CodeExtractor::severSplitPHINodesOfExits( 617 const SmallPtrSetImpl<BasicBlock *> &Exits) { 618 for (BasicBlock *ExitBB : Exits) { 619 BasicBlock *NewBB = nullptr; 620 621 for (PHINode &PN : ExitBB->phis()) { 622 // Find all incoming values from the outlining region. 623 SmallVector<unsigned, 2> IncomingVals; 624 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i) 625 if (Blocks.count(PN.getIncomingBlock(i))) 626 IncomingVals.push_back(i); 627 628 // Do not process PHI if there is one (or fewer) predecessor from region. 629 // If PHI has exactly one predecessor from region, only this one incoming 630 // will be replaced on codeRepl block, so it should be safe to skip PHI. 631 if (IncomingVals.size() <= 1) 632 continue; 633 634 // Create block for new PHIs and add it to the list of outlined if it 635 // wasn't done before. 636 if (!NewBB) { 637 NewBB = BasicBlock::Create(ExitBB->getContext(), 638 ExitBB->getName() + ".split", 639 ExitBB->getParent(), ExitBB); 640 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB), 641 pred_end(ExitBB)); 642 for (BasicBlock *PredBB : Preds) 643 if (Blocks.count(PredBB)) 644 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB); 645 BranchInst::Create(ExitBB, NewBB); 646 Blocks.insert(NewBB); 647 } 648 649 // Split this PHI. 650 PHINode *NewPN = 651 PHINode::Create(PN.getType(), IncomingVals.size(), 652 PN.getName() + ".ce", NewBB->getFirstNonPHI()); 653 for (unsigned i : IncomingVals) 654 NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i)); 655 for (unsigned i : reverse(IncomingVals)) 656 PN.removeIncomingValue(i, false); 657 PN.addIncoming(NewPN, NewBB); 658 } 659 } 660 } 661 662 void CodeExtractor::splitReturnBlocks() { 663 for (BasicBlock *Block : Blocks) 664 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { 665 BasicBlock *New = 666 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); 667 if (DT) { 668 // Old dominates New. New node dominates all other nodes dominated 669 // by Old. 670 DomTreeNode *OldNode = DT->getNode(Block); 671 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), 672 OldNode->end()); 673 674 DomTreeNode *NewNode = DT->addNewBlock(New, Block); 675 676 for (DomTreeNode *I : Children) 677 DT->changeImmediateDominator(I, NewNode); 678 } 679 } 680 } 681 682 /// constructFunction - make a function based on inputs and outputs, as follows: 683 /// f(in0, ..., inN, out0, ..., outN) 684 Function *CodeExtractor::constructFunction(const ValueSet &inputs, 685 const ValueSet &outputs, 686 BasicBlock *header, 687 BasicBlock *newRootNode, 688 BasicBlock *newHeader, 689 Function *oldFunction, 690 Module *M) { 691 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 692 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 693 694 // This function returns unsigned, outputs will go back by reference. 695 switch (NumExitBlocks) { 696 case 0: 697 case 1: RetTy = Type::getVoidTy(header->getContext()); break; 698 case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 699 default: RetTy = Type::getInt16Ty(header->getContext()); break; 700 } 701 702 std::vector<Type *> paramTy; 703 704 // Add the types of the input values to the function's argument list 705 for (Value *value : inputs) { 706 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n"); 707 paramTy.push_back(value->getType()); 708 } 709 710 // Add the types of the output values to the function's argument list. 711 for (Value *output : outputs) { 712 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n"); 713 if (AggregateArgs) 714 paramTy.push_back(output->getType()); 715 else 716 paramTy.push_back(PointerType::getUnqual(output->getType())); 717 } 718 719 LLVM_DEBUG({ 720 dbgs() << "Function type: " << *RetTy << " f("; 721 for (Type *i : paramTy) 722 dbgs() << *i << ", "; 723 dbgs() << ")\n"; 724 }); 725 726 StructType *StructTy; 727 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 728 StructTy = StructType::get(M->getContext(), paramTy); 729 paramTy.clear(); 730 paramTy.push_back(PointerType::getUnqual(StructTy)); 731 } 732 FunctionType *funcType = 733 FunctionType::get(RetTy, paramTy, 734 AllowVarArgs && oldFunction->isVarArg()); 735 736 std::string SuffixToUse = 737 Suffix.empty() 738 ? (header->getName().empty() ? "extracted" : header->getName().str()) 739 : Suffix; 740 // Create the new function 741 Function *newFunction = Function::Create( 742 funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(), 743 oldFunction->getName() + "." + SuffixToUse, M); 744 // If the old function is no-throw, so is the new one. 745 if (oldFunction->doesNotThrow()) 746 newFunction->setDoesNotThrow(); 747 748 // Inherit the uwtable attribute if we need to. 749 if (oldFunction->hasUWTable()) 750 newFunction->setHasUWTable(); 751 752 // Inherit all of the target dependent attributes and white-listed 753 // target independent attributes. 754 // (e.g. If the extracted region contains a call to an x86.sse 755 // instruction we need to make sure that the extracted region has the 756 // "target-features" attribute allowing it to be lowered. 757 // FIXME: This should be changed to check to see if a specific 758 // attribute can not be inherited. 759 for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) { 760 if (Attr.isStringAttribute()) { 761 if (Attr.getKindAsString() == "thunk") 762 continue; 763 } else 764 switch (Attr.getKindAsEnum()) { 765 // Those attributes cannot be propagated safely. Explicitly list them 766 // here so we get a warning if new attributes are added. This list also 767 // includes non-function attributes. 768 case Attribute::Alignment: 769 case Attribute::AllocSize: 770 case Attribute::ArgMemOnly: 771 case Attribute::Builtin: 772 case Attribute::ByVal: 773 case Attribute::Convergent: 774 case Attribute::Dereferenceable: 775 case Attribute::DereferenceableOrNull: 776 case Attribute::InAlloca: 777 case Attribute::InReg: 778 case Attribute::InaccessibleMemOnly: 779 case Attribute::InaccessibleMemOrArgMemOnly: 780 case Attribute::JumpTable: 781 case Attribute::Naked: 782 case Attribute::Nest: 783 case Attribute::NoAlias: 784 case Attribute::NoBuiltin: 785 case Attribute::NoCapture: 786 case Attribute::NoReturn: 787 case Attribute::None: 788 case Attribute::NonNull: 789 case Attribute::ReadNone: 790 case Attribute::ReadOnly: 791 case Attribute::Returned: 792 case Attribute::ReturnsTwice: 793 case Attribute::SExt: 794 case Attribute::Speculatable: 795 case Attribute::StackAlignment: 796 case Attribute::StructRet: 797 case Attribute::SwiftError: 798 case Attribute::SwiftSelf: 799 case Attribute::WriteOnly: 800 case Attribute::ZExt: 801 case Attribute::EndAttrKinds: 802 continue; 803 // Those attributes should be safe to propagate to the extracted function. 804 case Attribute::AlwaysInline: 805 case Attribute::Cold: 806 case Attribute::NoRecurse: 807 case Attribute::InlineHint: 808 case Attribute::MinSize: 809 case Attribute::NoDuplicate: 810 case Attribute::NoImplicitFloat: 811 case Attribute::NoInline: 812 case Attribute::NonLazyBind: 813 case Attribute::NoRedZone: 814 case Attribute::NoUnwind: 815 case Attribute::OptForFuzzing: 816 case Attribute::OptimizeNone: 817 case Attribute::OptimizeForSize: 818 case Attribute::SafeStack: 819 case Attribute::ShadowCallStack: 820 case Attribute::SanitizeAddress: 821 case Attribute::SanitizeMemory: 822 case Attribute::SanitizeThread: 823 case Attribute::SanitizeHWAddress: 824 case Attribute::SpeculativeLoadHardening: 825 case Attribute::StackProtect: 826 case Attribute::StackProtectReq: 827 case Attribute::StackProtectStrong: 828 case Attribute::StrictFP: 829 case Attribute::UWTable: 830 case Attribute::NoCfCheck: 831 break; 832 } 833 834 newFunction->addFnAttr(Attr); 835 } 836 newFunction->getBasicBlockList().push_back(newRootNode); 837 838 // Create an iterator to name all of the arguments we inserted. 839 Function::arg_iterator AI = newFunction->arg_begin(); 840 841 // Rewrite all users of the inputs in the extracted region to use the 842 // arguments (or appropriate addressing into struct) instead. 843 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 844 Value *RewriteVal; 845 if (AggregateArgs) { 846 Value *Idx[2]; 847 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 848 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 849 Instruction *TI = newFunction->begin()->getTerminator(); 850 GetElementPtrInst *GEP = GetElementPtrInst::Create( 851 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); 852 RewriteVal = new LoadInst(StructTy->getElementType(i), GEP, 853 "loadgep_" + inputs[i]->getName(), TI); 854 } else 855 RewriteVal = &*AI++; 856 857 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 858 for (User *use : Users) 859 if (Instruction *inst = dyn_cast<Instruction>(use)) 860 if (Blocks.count(inst->getParent())) 861 inst->replaceUsesOfWith(inputs[i], RewriteVal); 862 } 863 864 // Set names for input and output arguments. 865 if (!AggregateArgs) { 866 AI = newFunction->arg_begin(); 867 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 868 AI->setName(inputs[i]->getName()); 869 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 870 AI->setName(outputs[i]->getName()+".out"); 871 } 872 873 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 874 // within the new function. This must be done before we lose track of which 875 // blocks were originally in the code region. 876 std::vector<User *> Users(header->user_begin(), header->user_end()); 877 for (unsigned i = 0, e = Users.size(); i != e; ++i) 878 // The BasicBlock which contains the branch is not in the region 879 // modify the branch target to a new block 880 if (Instruction *I = dyn_cast<Instruction>(Users[i])) 881 if (I->isTerminator() && !Blocks.count(I->getParent()) && 882 I->getParent()->getParent() == oldFunction) 883 I->replaceUsesOfWith(header, newHeader); 884 885 return newFunction; 886 } 887 888 /// Scan the extraction region for lifetime markers which reference inputs. 889 /// Erase these markers. Return the inputs which were referenced. 890 /// 891 /// The extraction region is defined by a set of blocks (\p Blocks), and a set 892 /// of allocas which will be moved from the caller function into the extracted 893 /// function (\p SunkAllocas). 894 static SetVector<Value *> 895 eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks, 896 const SetVector<Value *> &SunkAllocas) { 897 SetVector<Value *> InputObjectsWithLifetime; 898 for (BasicBlock *BB : Blocks) { 899 for (auto It = BB->begin(), End = BB->end(); It != End;) { 900 auto *II = dyn_cast<IntrinsicInst>(&*It); 901 ++It; 902 if (!II || !II->isLifetimeStartOrEnd()) 903 continue; 904 905 // Get the memory operand of the lifetime marker. If the underlying 906 // object is a sunk alloca, or is otherwise defined in the extraction 907 // region, the lifetime marker must not be erased. 908 Value *Mem = II->getOperand(1)->stripInBoundsOffsets(); 909 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem)) 910 continue; 911 912 InputObjectsWithLifetime.insert(Mem); 913 II->eraseFromParent(); 914 } 915 } 916 return InputObjectsWithLifetime; 917 } 918 919 /// Insert lifetime start/end markers surrounding the call to the new function 920 /// for objects defined in the caller. 921 static void insertLifetimeMarkersSurroundingCall(Module *M, 922 ArrayRef<Value *> Objects, 923 CallInst *TheCall) { 924 if (Objects.empty()) 925 return; 926 927 LLVMContext &Ctx = M->getContext(); 928 auto Int8PtrTy = Type::getInt8PtrTy(Ctx); 929 auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1); 930 auto StartFn = llvm::Intrinsic::getDeclaration( 931 M, llvm::Intrinsic::lifetime_start, Int8PtrTy); 932 auto EndFn = llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::lifetime_end, 933 Int8PtrTy); 934 Instruction *Term = TheCall->getParent()->getTerminator(); 935 for (Value *Mem : Objects) { 936 assert((!isa<Instruction>(Mem) || 937 cast<Instruction>(Mem)->getFunction() == TheCall->getFunction()) && 938 "Input memory not defined in original function"); 939 Value *MemAsI8Ptr = nullptr; 940 if (Mem->getType() == Int8PtrTy) 941 MemAsI8Ptr = Mem; 942 else 943 MemAsI8Ptr = 944 CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall); 945 946 auto StartMarker = CallInst::Create(StartFn, {NegativeOne, MemAsI8Ptr}); 947 StartMarker->insertBefore(TheCall); 948 auto EndMarker = CallInst::Create(EndFn, {NegativeOne, MemAsI8Ptr}); 949 EndMarker->insertBefore(Term); 950 } 951 } 952 953 /// emitCallAndSwitchStatement - This method sets up the caller side by adding 954 /// the call instruction, splitting any PHI nodes in the header block as 955 /// necessary. 956 CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, 957 BasicBlock *codeReplacer, 958 ValueSet &inputs, 959 ValueSet &outputs) { 960 // Emit a call to the new function, passing in: *pointer to struct (if 961 // aggregating parameters), or plan inputs and allocated memory for outputs 962 std::vector<Value *> params, StructValues, ReloadOutputs, Reloads; 963 964 Module *M = newFunction->getParent(); 965 LLVMContext &Context = M->getContext(); 966 const DataLayout &DL = M->getDataLayout(); 967 CallInst *call = nullptr; 968 969 // Add inputs as params, or to be filled into the struct 970 unsigned ArgNo = 0; 971 SmallVector<unsigned, 1> SwiftErrorArgs; 972 for (Value *input : inputs) { 973 if (AggregateArgs) 974 StructValues.push_back(input); 975 else { 976 params.push_back(input); 977 if (input->isSwiftError()) 978 SwiftErrorArgs.push_back(ArgNo); 979 } 980 ++ArgNo; 981 } 982 983 // Create allocas for the outputs 984 for (Value *output : outputs) { 985 if (AggregateArgs) { 986 StructValues.push_back(output); 987 } else { 988 AllocaInst *alloca = 989 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), 990 nullptr, output->getName() + ".loc", 991 &codeReplacer->getParent()->front().front()); 992 ReloadOutputs.push_back(alloca); 993 params.push_back(alloca); 994 } 995 } 996 997 StructType *StructArgTy = nullptr; 998 AllocaInst *Struct = nullptr; 999 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 1000 std::vector<Type *> ArgTypes; 1001 for (ValueSet::iterator v = StructValues.begin(), 1002 ve = StructValues.end(); v != ve; ++v) 1003 ArgTypes.push_back((*v)->getType()); 1004 1005 // Allocate a struct at the beginning of this function 1006 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 1007 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, 1008 "structArg", 1009 &codeReplacer->getParent()->front().front()); 1010 params.push_back(Struct); 1011 1012 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 1013 Value *Idx[2]; 1014 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1015 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 1016 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1017 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); 1018 codeReplacer->getInstList().push_back(GEP); 1019 StoreInst *SI = new StoreInst(StructValues[i], GEP); 1020 codeReplacer->getInstList().push_back(SI); 1021 } 1022 } 1023 1024 // Emit the call to the function 1025 call = CallInst::Create(newFunction, params, 1026 NumExitBlocks > 1 ? "targetBlock" : ""); 1027 // Add debug location to the new call, if the original function has debug 1028 // info. In that case, the terminator of the entry block of the extracted 1029 // function contains the first debug location of the extracted function, 1030 // set in extractCodeRegion. 1031 if (codeReplacer->getParent()->getSubprogram()) { 1032 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc()) 1033 call->setDebugLoc(DL); 1034 } 1035 codeReplacer->getInstList().push_back(call); 1036 1037 // Set swifterror parameter attributes. 1038 for (unsigned SwiftErrArgNo : SwiftErrorArgs) { 1039 call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError); 1040 newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError); 1041 } 1042 1043 Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 1044 unsigned FirstOut = inputs.size(); 1045 if (!AggregateArgs) 1046 std::advance(OutputArgBegin, inputs.size()); 1047 1048 // Reload the outputs passed in by reference. 1049 Function::arg_iterator OAI = OutputArgBegin; 1050 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 1051 Value *Output = nullptr; 1052 if (AggregateArgs) { 1053 Value *Idx[2]; 1054 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1055 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 1056 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1057 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); 1058 codeReplacer->getInstList().push_back(GEP); 1059 Output = GEP; 1060 } else { 1061 Output = ReloadOutputs[i]; 1062 } 1063 LoadInst *load = new LoadInst(outputs[i]->getType(), Output, 1064 outputs[i]->getName() + ".reload"); 1065 Reloads.push_back(load); 1066 codeReplacer->getInstList().push_back(load); 1067 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 1068 for (unsigned u = 0, e = Users.size(); u != e; ++u) { 1069 Instruction *inst = cast<Instruction>(Users[u]); 1070 if (!Blocks.count(inst->getParent())) 1071 inst->replaceUsesOfWith(outputs[i], load); 1072 } 1073 1074 // Store to argument right after the definition of output value. 1075 auto *OutI = dyn_cast<Instruction>(outputs[i]); 1076 if (!OutI) 1077 continue; 1078 1079 // Find proper insertion point. 1080 BasicBlock::iterator InsertPt; 1081 // In case OutI is an invoke, we insert the store at the beginning in the 1082 // 'normal destination' BB. Otherwise we insert the store right after OutI. 1083 if (auto *InvokeI = dyn_cast<InvokeInst>(OutI)) 1084 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt(); 1085 else if (auto *Phi = dyn_cast<PHINode>(OutI)) 1086 InsertPt = Phi->getParent()->getFirstInsertionPt(); 1087 else 1088 InsertPt = std::next(OutI->getIterator()); 1089 1090 assert(OAI != newFunction->arg_end() && 1091 "Number of output arguments should match " 1092 "the amount of defined values"); 1093 if (AggregateArgs) { 1094 Value *Idx[2]; 1095 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1096 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 1097 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1098 StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), &*InsertPt); 1099 new StoreInst(outputs[i], GEP, &*InsertPt); 1100 // Since there should be only one struct argument aggregating 1101 // all the output values, we shouldn't increment OAI, which always 1102 // points to the struct argument, in this case. 1103 } else { 1104 new StoreInst(outputs[i], &*OAI, &*InsertPt); 1105 ++OAI; 1106 } 1107 } 1108 1109 // Now we can emit a switch statement using the call as a value. 1110 SwitchInst *TheSwitch = 1111 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 1112 codeReplacer, 0, codeReplacer); 1113 1114 // Since there may be multiple exits from the original region, make the new 1115 // function return an unsigned, switch on that number. This loop iterates 1116 // over all of the blocks in the extracted region, updating any terminator 1117 // instructions in the to-be-extracted region that branch to blocks that are 1118 // not in the region to be extracted. 1119 std::map<BasicBlock *, BasicBlock *> ExitBlockMap; 1120 1121 unsigned switchVal = 0; 1122 for (BasicBlock *Block : Blocks) { 1123 Instruction *TI = Block->getTerminator(); 1124 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 1125 if (!Blocks.count(TI->getSuccessor(i))) { 1126 BasicBlock *OldTarget = TI->getSuccessor(i); 1127 // add a new basic block which returns the appropriate value 1128 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 1129 if (!NewTarget) { 1130 // If we don't already have an exit stub for this non-extracted 1131 // destination, create one now! 1132 NewTarget = BasicBlock::Create(Context, 1133 OldTarget->getName() + ".exitStub", 1134 newFunction); 1135 unsigned SuccNum = switchVal++; 1136 1137 Value *brVal = nullptr; 1138 switch (NumExitBlocks) { 1139 case 0: 1140 case 1: break; // No value needed. 1141 case 2: // Conditional branch, return a bool 1142 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 1143 break; 1144 default: 1145 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 1146 break; 1147 } 1148 1149 ReturnInst::Create(Context, brVal, NewTarget); 1150 1151 // Update the switch instruction. 1152 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 1153 SuccNum), 1154 OldTarget); 1155 } 1156 1157 // rewrite the original branch instruction with this new target 1158 TI->setSuccessor(i, NewTarget); 1159 } 1160 } 1161 1162 // Now that we've done the deed, simplify the switch instruction. 1163 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 1164 switch (NumExitBlocks) { 1165 case 0: 1166 // There are no successors (the block containing the switch itself), which 1167 // means that previously this was the last part of the function, and hence 1168 // this should be rewritten as a `ret' 1169 1170 // Check if the function should return a value 1171 if (OldFnRetTy->isVoidTy()) { 1172 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void 1173 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 1174 // return what we have 1175 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 1176 } else { 1177 // Otherwise we must have code extracted an unwind or something, just 1178 // return whatever we want. 1179 ReturnInst::Create(Context, 1180 Constant::getNullValue(OldFnRetTy), TheSwitch); 1181 } 1182 1183 TheSwitch->eraseFromParent(); 1184 break; 1185 case 1: 1186 // Only a single destination, change the switch into an unconditional 1187 // branch. 1188 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 1189 TheSwitch->eraseFromParent(); 1190 break; 1191 case 2: 1192 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 1193 call, TheSwitch); 1194 TheSwitch->eraseFromParent(); 1195 break; 1196 default: 1197 // Otherwise, make the default destination of the switch instruction be one 1198 // of the other successors. 1199 TheSwitch->setCondition(call); 1200 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 1201 // Remove redundant case 1202 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); 1203 break; 1204 } 1205 1206 // Insert lifetime markers around the reloads of any output values. The 1207 // allocas output values are stored in are only in-use in the codeRepl block. 1208 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, call); 1209 1210 return call; 1211 } 1212 1213 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 1214 Function *oldFunc = (*Blocks.begin())->getParent(); 1215 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 1216 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 1217 1218 for (BasicBlock *Block : Blocks) { 1219 // Delete the basic block from the old function, and the list of blocks 1220 oldBlocks.remove(Block); 1221 1222 // Insert this basic block into the new function 1223 newBlocks.push_back(Block); 1224 1225 // Remove @llvm.assume calls that were moved to the new function from the 1226 // old function's assumption cache. 1227 if (AC) 1228 for (auto &I : *Block) 1229 if (match(&I, m_Intrinsic<Intrinsic::assume>())) 1230 AC->unregisterAssumption(cast<CallInst>(&I)); 1231 } 1232 } 1233 1234 void CodeExtractor::calculateNewCallTerminatorWeights( 1235 BasicBlock *CodeReplacer, 1236 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, 1237 BranchProbabilityInfo *BPI) { 1238 using Distribution = BlockFrequencyInfoImplBase::Distribution; 1239 using BlockNode = BlockFrequencyInfoImplBase::BlockNode; 1240 1241 // Update the branch weights for the exit block. 1242 Instruction *TI = CodeReplacer->getTerminator(); 1243 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); 1244 1245 // Block Frequency distribution with dummy node. 1246 Distribution BranchDist; 1247 1248 // Add each of the frequencies of the successors. 1249 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { 1250 BlockNode ExitNode(i); 1251 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency(); 1252 if (ExitFreq != 0) 1253 BranchDist.addExit(ExitNode, ExitFreq); 1254 else 1255 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero()); 1256 } 1257 1258 // Check for no total weight. 1259 if (BranchDist.Total == 0) 1260 return; 1261 1262 // Normalize the distribution so that they can fit in unsigned. 1263 BranchDist.normalize(); 1264 1265 // Create normalized branch weights and set the metadata. 1266 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { 1267 const auto &Weight = BranchDist.Weights[I]; 1268 1269 // Get the weight and update the current BFI. 1270 BranchWeights[Weight.TargetNode.Index] = Weight.Amount; 1271 BranchProbability BP(Weight.Amount, BranchDist.Total); 1272 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP); 1273 } 1274 TI->setMetadata( 1275 LLVMContext::MD_prof, 1276 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); 1277 } 1278 1279 Function *CodeExtractor::extractCodeRegion() { 1280 if (!isEligible()) 1281 return nullptr; 1282 1283 // Assumption: this is a single-entry code region, and the header is the first 1284 // block in the region. 1285 BasicBlock *header = *Blocks.begin(); 1286 Function *oldFunction = header->getParent(); 1287 1288 // For functions with varargs, check that varargs handling is only done in the 1289 // outlined function, i.e vastart and vaend are only used in outlined blocks. 1290 if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) { 1291 auto containsVarArgIntrinsic = [](Instruction &I) { 1292 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 1293 if (const Function *F = CI->getCalledFunction()) 1294 return F->getIntrinsicID() == Intrinsic::vastart || 1295 F->getIntrinsicID() == Intrinsic::vaend; 1296 return false; 1297 }; 1298 1299 for (auto &BB : *oldFunction) { 1300 if (Blocks.count(&BB)) 1301 continue; 1302 if (llvm::any_of(BB, containsVarArgIntrinsic)) 1303 return nullptr; 1304 } 1305 } 1306 ValueSet inputs, outputs, SinkingCands, HoistingCands; 1307 BasicBlock *CommonExit = nullptr; 1308 1309 // Calculate the entry frequency of the new function before we change the root 1310 // block. 1311 BlockFrequency EntryFreq; 1312 if (BFI) { 1313 assert(BPI && "Both BPI and BFI are required to preserve profile info"); 1314 for (BasicBlock *Pred : predecessors(header)) { 1315 if (Blocks.count(Pred)) 1316 continue; 1317 EntryFreq += 1318 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); 1319 } 1320 } 1321 1322 // If we have any return instructions in the region, split those blocks so 1323 // that the return is not in the region. 1324 splitReturnBlocks(); 1325 1326 // Calculate the exit blocks for the extracted region and the total exit 1327 // weights for each of those blocks. 1328 DenseMap<BasicBlock *, BlockFrequency> ExitWeights; 1329 SmallPtrSet<BasicBlock *, 1> ExitBlocks; 1330 for (BasicBlock *Block : Blocks) { 1331 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE; 1332 ++SI) { 1333 if (!Blocks.count(*SI)) { 1334 // Update the branch weight for this successor. 1335 if (BFI) { 1336 BlockFrequency &BF = ExitWeights[*SI]; 1337 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI); 1338 } 1339 ExitBlocks.insert(*SI); 1340 } 1341 } 1342 } 1343 NumExitBlocks = ExitBlocks.size(); 1344 1345 // If we have to split PHI nodes of the entry or exit blocks, do so now. 1346 severSplitPHINodesOfEntry(header); 1347 severSplitPHINodesOfExits(ExitBlocks); 1348 1349 // This takes place of the original loop 1350 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 1351 "codeRepl", oldFunction, 1352 header); 1353 1354 // The new function needs a root node because other nodes can branch to the 1355 // head of the region, but the entry node of a function cannot have preds. 1356 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 1357 "newFuncRoot"); 1358 auto *BranchI = BranchInst::Create(header); 1359 // If the original function has debug info, we have to add a debug location 1360 // to the new branch instruction from the artificial entry block. 1361 // We use the debug location of the first instruction in the extracted 1362 // blocks, as there is no other equivalent line in the source code. 1363 if (oldFunction->getSubprogram()) { 1364 any_of(Blocks, [&BranchI](const BasicBlock *BB) { 1365 return any_of(*BB, [&BranchI](const Instruction &I) { 1366 if (!I.getDebugLoc()) 1367 return false; 1368 BranchI->setDebugLoc(I.getDebugLoc()); 1369 return true; 1370 }); 1371 }); 1372 } 1373 newFuncRoot->getInstList().push_back(BranchI); 1374 1375 findAllocas(SinkingCands, HoistingCands, CommonExit); 1376 assert(HoistingCands.empty() || CommonExit); 1377 1378 // Find inputs to, outputs from the code region. 1379 findInputsOutputs(inputs, outputs, SinkingCands); 1380 1381 // Now sink all instructions which only have non-phi uses inside the region 1382 for (auto *II : SinkingCands) 1383 cast<Instruction>(II)->moveBefore(*newFuncRoot, 1384 newFuncRoot->getFirstInsertionPt()); 1385 1386 if (!HoistingCands.empty()) { 1387 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit); 1388 Instruction *TI = HoistToBlock->getTerminator(); 1389 for (auto *II : HoistingCands) 1390 cast<Instruction>(II)->moveBefore(TI); 1391 } 1392 1393 // Collect objects which are inputs to the extraction region and also 1394 // referenced by lifetime start/end markers within it. The effects of these 1395 // markers must be replicated in the calling function to prevent the stack 1396 // coloring pass from merging slots which store input objects. 1397 ValueSet InputObjectsWithLifetime = 1398 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands); 1399 1400 // Construct new function based on inputs/outputs & add allocas for all defs. 1401 Function *newFunction = 1402 constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer, 1403 oldFunction, oldFunction->getParent()); 1404 1405 // Update the entry count of the function. 1406 if (BFI) { 1407 auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); 1408 if (Count.hasValue()) 1409 newFunction->setEntryCount( 1410 ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME 1411 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); 1412 } 1413 1414 CallInst *TheCall = 1415 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 1416 1417 moveCodeToFunction(newFunction); 1418 1419 // Replicate the effects of any lifetime start/end markers which referenced 1420 // input objects in the extraction region by placing markers around the call. 1421 insertLifetimeMarkersSurroundingCall(oldFunction->getParent(), 1422 InputObjectsWithLifetime.getArrayRef(), 1423 TheCall); 1424 1425 // Propagate personality info to the new function if there is one. 1426 if (oldFunction->hasPersonalityFn()) 1427 newFunction->setPersonalityFn(oldFunction->getPersonalityFn()); 1428 1429 // Update the branch weights for the exit block. 1430 if (BFI && NumExitBlocks > 1) 1431 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); 1432 1433 // Loop over all of the PHI nodes in the header and exit blocks, and change 1434 // any references to the old incoming edge to be the new incoming edge. 1435 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 1436 PHINode *PN = cast<PHINode>(I); 1437 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1438 if (!Blocks.count(PN->getIncomingBlock(i))) 1439 PN->setIncomingBlock(i, newFuncRoot); 1440 } 1441 1442 for (BasicBlock *ExitBB : ExitBlocks) 1443 for (PHINode &PN : ExitBB->phis()) { 1444 Value *IncomingCodeReplacerVal = nullptr; 1445 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1446 // Ignore incoming values from outside of the extracted region. 1447 if (!Blocks.count(PN.getIncomingBlock(i))) 1448 continue; 1449 1450 // Ensure that there is only one incoming value from codeReplacer. 1451 if (!IncomingCodeReplacerVal) { 1452 PN.setIncomingBlock(i, codeReplacer); 1453 IncomingCodeReplacerVal = PN.getIncomingValue(i); 1454 } else 1455 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) && 1456 "PHI has two incompatbile incoming values from codeRepl"); 1457 } 1458 } 1459 1460 // Erase debug info intrinsics. Variable updates within the new function are 1461 // invisible to debuggers. This could be improved by defining a DISubprogram 1462 // for the new function. 1463 for (BasicBlock &BB : *newFunction) { 1464 auto BlockIt = BB.begin(); 1465 // Remove debug info intrinsics from the new function. 1466 while (BlockIt != BB.end()) { 1467 Instruction *Inst = &*BlockIt; 1468 ++BlockIt; 1469 if (isa<DbgInfoIntrinsic>(Inst)) 1470 Inst->eraseFromParent(); 1471 } 1472 // Remove debug info intrinsics which refer to values in the new function 1473 // from the old function. 1474 SmallVector<DbgVariableIntrinsic *, 4> DbgUsers; 1475 for (Instruction &I : BB) 1476 findDbgUsers(DbgUsers, &I); 1477 for (DbgVariableIntrinsic *DVI : DbgUsers) 1478 DVI->eraseFromParent(); 1479 } 1480 1481 // Mark the new function `noreturn` if applicable. Terminators which resume 1482 // exception propagation are treated as returning instructions. This is to 1483 // avoid inserting traps after calls to outlined functions which unwind. 1484 bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) { 1485 const Instruction *Term = BB.getTerminator(); 1486 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term); 1487 }); 1488 if (doesNotReturn) 1489 newFunction->setDoesNotReturn(); 1490 1491 LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) { 1492 newFunction->dump(); 1493 report_fatal_error("verification of newFunction failed!"); 1494 }); 1495 LLVM_DEBUG(if (verifyFunction(*oldFunction)) 1496 report_fatal_error("verification of oldFunction failed!")); 1497 return newFunction; 1498 } 1499