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