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