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