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