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