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/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/BlockFrequencyInfo.h"
21 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/RegionInfo.h"
25 #include "llvm/Analysis/RegionIterator.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/MDBuilder.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/BlockFrequency.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include <algorithm>
43 #include <set>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "code-extractor"
47 
48 // Provide a command-line option to aggregate function arguments into a struct
49 // for functions produced by the code extractor. This is useful when converting
50 // extracted functions to pthread-based code, as only one argument (void*) can
51 // be passed in to pthread_create().
52 static cl::opt<bool>
53 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
54                  cl::desc("Aggregate arguments to code-extracted functions"));
55 
56 /// \brief Test whether a block is valid for extraction.
57 bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) {
58   // Landing pads must be in the function where they were inserted for cleanup.
59   if (BB.isEHPad())
60     return false;
61 
62   // Don't hoist code containing allocas, invokes, or vastarts.
63   for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
64     if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
65       return false;
66     if (const CallInst *CI = dyn_cast<CallInst>(I))
67       if (const Function *F = CI->getCalledFunction())
68         if (F->getIntrinsicID() == Intrinsic::vastart)
69           return false;
70   }
71 
72   return true;
73 }
74 
75 /// \brief Build a set of blocks to extract if the input blocks are viable.
76 template <typename IteratorT>
77 static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin,
78                                                        IteratorT BBEnd) {
79   SetVector<BasicBlock *> Result;
80 
81   assert(BBBegin != BBEnd);
82 
83   // Loop over the blocks, adding them to our set-vector, and aborting with an
84   // empty set if we encounter invalid blocks.
85   do {
86     if (!Result.insert(*BBBegin))
87       llvm_unreachable("Repeated basic blocks in extraction input");
88 
89     if (!CodeExtractor::isBlockValidForExtraction(**BBBegin)) {
90       Result.clear();
91       return Result;
92     }
93   } while (++BBBegin != BBEnd);
94 
95 #ifndef NDEBUG
96   for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
97                                          E = Result.end();
98        I != E; ++I)
99     for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
100          PI != PE; ++PI)
101       assert(Result.count(*PI) &&
102              "No blocks in this region may have entries from outside the region"
103              " except for the first block!");
104 #endif
105 
106   return Result;
107 }
108 
109 /// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
110 static SetVector<BasicBlock *>
111 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
112   return buildExtractionBlockSet(BBs.begin(), BBs.end());
113 }
114 
115 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
116                              bool AggregateArgs, BlockFrequencyInfo *BFI,
117                              BranchProbabilityInfo *BPI)
118     : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
119       BPI(BPI), Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
120 
121 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
122                              BlockFrequencyInfo *BFI,
123                              BranchProbabilityInfo *BPI)
124     : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
125       BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks())),
126       NumExitBlocks(~0U) {}
127 
128 /// definedInRegion - Return true if the specified value is defined in the
129 /// extracted region.
130 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
131   if (Instruction *I = dyn_cast<Instruction>(V))
132     if (Blocks.count(I->getParent()))
133       return true;
134   return false;
135 }
136 
137 /// definedInCaller - Return true if the specified value is defined in the
138 /// function being code extracted, but not in the region being extracted.
139 /// These values must be passed in as live-ins to the function.
140 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
141   if (isa<Argument>(V)) return true;
142   if (Instruction *I = dyn_cast<Instruction>(V))
143     if (!Blocks.count(I->getParent()))
144       return true;
145   return false;
146 }
147 
148 void CodeExtractor::findInputsOutputs(ValueSet &Inputs,
149                                       ValueSet &Outputs) const {
150   for (BasicBlock *BB : Blocks) {
151     // If a used value is defined outside the region, it's an input.  If an
152     // instruction is used outside the region, it's an output.
153     for (Instruction &II : *BB) {
154       for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
155            ++OI)
156         if (definedInCaller(Blocks, *OI))
157           Inputs.insert(*OI);
158 
159       for (User *U : II.users())
160         if (!definedInRegion(Blocks, U)) {
161           Outputs.insert(&II);
162           break;
163         }
164     }
165   }
166 }
167 
168 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
169 /// region, we need to split the entry block of the region so that the PHI node
170 /// is easier to deal with.
171 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
172   unsigned NumPredsFromRegion = 0;
173   unsigned NumPredsOutsideRegion = 0;
174 
175   if (Header != &Header->getParent()->getEntryBlock()) {
176     PHINode *PN = dyn_cast<PHINode>(Header->begin());
177     if (!PN) return;  // No PHI nodes.
178 
179     // If the header node contains any PHI nodes, check to see if there is more
180     // than one entry from outside the region.  If so, we need to sever the
181     // header block into two.
182     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
183       if (Blocks.count(PN->getIncomingBlock(i)))
184         ++NumPredsFromRegion;
185       else
186         ++NumPredsOutsideRegion;
187 
188     // If there is one (or fewer) predecessor from outside the region, we don't
189     // need to do anything special.
190     if (NumPredsOutsideRegion <= 1) return;
191   }
192 
193   // Otherwise, we need to split the header block into two pieces: one
194   // containing PHI nodes merging values from outside of the region, and a
195   // second that contains all of the code for the block and merges back any
196   // incoming values from inside of the region.
197   BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT);
198 
199   // We only want to code extract the second block now, and it becomes the new
200   // header of the region.
201   BasicBlock *OldPred = Header;
202   Blocks.remove(OldPred);
203   Blocks.insert(NewBB);
204   Header = NewBB;
205 
206   // Okay, now we need to adjust the PHI nodes and any branches from within the
207   // region to go to the new header block instead of the old header block.
208   if (NumPredsFromRegion) {
209     PHINode *PN = cast<PHINode>(OldPred->begin());
210     // Loop over all of the predecessors of OldPred that are in the region,
211     // changing them to branch to NewBB instead.
212     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
213       if (Blocks.count(PN->getIncomingBlock(i))) {
214         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
215         TI->replaceUsesOfWith(OldPred, NewBB);
216       }
217 
218     // Okay, everything within the region is now branching to the right block, we
219     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
220     BasicBlock::iterator AfterPHIs;
221     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
222       PHINode *PN = cast<PHINode>(AfterPHIs);
223       // Create a new PHI node in the new region, which has an incoming value
224       // from OldPred of PN.
225       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
226                                        PN->getName() + ".ce", &NewBB->front());
227       NewPN->addIncoming(PN, OldPred);
228 
229       // Loop over all of the incoming value in PN, moving them to NewPN if they
230       // are from the extracted region.
231       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
232         if (Blocks.count(PN->getIncomingBlock(i))) {
233           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
234           PN->removeIncomingValue(i);
235           --i;
236         }
237       }
238     }
239   }
240 }
241 
242 void CodeExtractor::splitReturnBlocks() {
243   for (BasicBlock *Block : Blocks)
244     if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
245       BasicBlock *New =
246           Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
247       if (DT) {
248         // Old dominates New. New node dominates all other nodes dominated
249         // by Old.
250         DomTreeNode *OldNode = DT->getNode(Block);
251         SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
252                                                OldNode->end());
253 
254         DomTreeNode *NewNode = DT->addNewBlock(New, Block);
255 
256         for (DomTreeNode *I : Children)
257           DT->changeImmediateDominator(I, NewNode);
258       }
259     }
260 }
261 
262 /// constructFunction - make a function based on inputs and outputs, as follows:
263 /// f(in0, ..., inN, out0, ..., outN)
264 ///
265 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
266                                            const ValueSet &outputs,
267                                            BasicBlock *header,
268                                            BasicBlock *newRootNode,
269                                            BasicBlock *newHeader,
270                                            Function *oldFunction,
271                                            Module *M) {
272   DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
273   DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
274 
275   // This function returns unsigned, outputs will go back by reference.
276   switch (NumExitBlocks) {
277   case 0:
278   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
279   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
280   default: RetTy = Type::getInt16Ty(header->getContext()); break;
281   }
282 
283   std::vector<Type*> paramTy;
284 
285   // Add the types of the input values to the function's argument list
286   for (Value *value : inputs) {
287     DEBUG(dbgs() << "value used in func: " << *value << "\n");
288     paramTy.push_back(value->getType());
289   }
290 
291   // Add the types of the output values to the function's argument list.
292   for (Value *output : outputs) {
293     DEBUG(dbgs() << "instr used in func: " << *output << "\n");
294     if (AggregateArgs)
295       paramTy.push_back(output->getType());
296     else
297       paramTy.push_back(PointerType::getUnqual(output->getType()));
298   }
299 
300   DEBUG({
301     dbgs() << "Function type: " << *RetTy << " f(";
302     for (Type *i : paramTy)
303       dbgs() << *i << ", ";
304     dbgs() << ")\n";
305   });
306 
307   StructType *StructTy;
308   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
309     StructTy = StructType::get(M->getContext(), paramTy);
310     paramTy.clear();
311     paramTy.push_back(PointerType::getUnqual(StructTy));
312   }
313   FunctionType *funcType =
314                   FunctionType::get(RetTy, paramTy, false);
315 
316   // Create the new function
317   Function *newFunction = Function::Create(funcType,
318                                            GlobalValue::InternalLinkage,
319                                            oldFunction->getName() + "_" +
320                                            header->getName(), M);
321   // If the old function is no-throw, so is the new one.
322   if (oldFunction->doesNotThrow())
323     newFunction->setDoesNotThrow();
324 
325   // Inherit the uwtable attribute if we need to.
326   if (oldFunction->hasUWTable())
327     newFunction->setHasUWTable();
328 
329   // Inherit all of the target dependent attributes.
330   //  (e.g. If the extracted region contains a call to an x86.sse
331   //  instruction we need to make sure that the extracted region has the
332   //  "target-features" attribute allowing it to be lowered.
333   // FIXME: This should be changed to check to see if a specific
334   //           attribute can not be inherited.
335   AttrBuilder AB(oldFunction->getAttributes().getFnAttributes());
336   for (const auto &Attr : AB.td_attrs())
337     newFunction->addFnAttr(Attr.first, Attr.second);
338 
339   newFunction->getBasicBlockList().push_back(newRootNode);
340 
341   // Create an iterator to name all of the arguments we inserted.
342   Function::arg_iterator AI = newFunction->arg_begin();
343 
344   // Rewrite all users of the inputs in the extracted region to use the
345   // arguments (or appropriate addressing into struct) instead.
346   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
347     Value *RewriteVal;
348     if (AggregateArgs) {
349       Value *Idx[2];
350       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
351       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
352       TerminatorInst *TI = newFunction->begin()->getTerminator();
353       GetElementPtrInst *GEP = GetElementPtrInst::Create(
354           StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
355       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
356     } else
357       RewriteVal = &*AI++;
358 
359     std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
360     for (User *use : Users)
361       if (Instruction *inst = dyn_cast<Instruction>(use))
362         if (Blocks.count(inst->getParent()))
363           inst->replaceUsesOfWith(inputs[i], RewriteVal);
364   }
365 
366   // Set names for input and output arguments.
367   if (!AggregateArgs) {
368     AI = newFunction->arg_begin();
369     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
370       AI->setName(inputs[i]->getName());
371     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
372       AI->setName(outputs[i]->getName()+".out");
373   }
374 
375   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
376   // within the new function. This must be done before we lose track of which
377   // blocks were originally in the code region.
378   std::vector<User*> Users(header->user_begin(), header->user_end());
379   for (unsigned i = 0, e = Users.size(); i != e; ++i)
380     // The BasicBlock which contains the branch is not in the region
381     // modify the branch target to a new block
382     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
383       if (!Blocks.count(TI->getParent()) &&
384           TI->getParent()->getParent() == oldFunction)
385         TI->replaceUsesOfWith(header, newHeader);
386 
387   return newFunction;
388 }
389 
390 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
391 /// that uses the value within the basic block, and return the predecessor
392 /// block associated with that use, or return 0 if none is found.
393 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
394   for (Use &U : Used->uses()) {
395      PHINode *P = dyn_cast<PHINode>(U.getUser());
396      if (P && P->getParent() == BB)
397        return P->getIncomingBlock(U);
398   }
399 
400   return nullptr;
401 }
402 
403 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
404 /// the call instruction, splitting any PHI nodes in the header block as
405 /// necessary.
406 void CodeExtractor::
407 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
408                            ValueSet &inputs, ValueSet &outputs) {
409   // Emit a call to the new function, passing in: *pointer to struct (if
410   // aggregating parameters), or plan inputs and allocated memory for outputs
411   std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
412 
413   Module *M = newFunction->getParent();
414   LLVMContext &Context = M->getContext();
415   const DataLayout &DL = M->getDataLayout();
416 
417   // Add inputs as params, or to be filled into the struct
418   for (Value *input : inputs)
419     if (AggregateArgs)
420       StructValues.push_back(input);
421     else
422       params.push_back(input);
423 
424   // Create allocas for the outputs
425   for (Value *output : outputs) {
426     if (AggregateArgs) {
427       StructValues.push_back(output);
428     } else {
429       AllocaInst *alloca =
430         new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
431                        nullptr, output->getName() + ".loc",
432                        &codeReplacer->getParent()->front().front());
433       ReloadOutputs.push_back(alloca);
434       params.push_back(alloca);
435     }
436   }
437 
438   StructType *StructArgTy = nullptr;
439   AllocaInst *Struct = nullptr;
440   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
441     std::vector<Type*> ArgTypes;
442     for (ValueSet::iterator v = StructValues.begin(),
443            ve = StructValues.end(); v != ve; ++v)
444       ArgTypes.push_back((*v)->getType());
445 
446     // Allocate a struct at the beginning of this function
447     StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
448     Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
449                             "structArg",
450                             &codeReplacer->getParent()->front().front());
451     params.push_back(Struct);
452 
453     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
454       Value *Idx[2];
455       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
456       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
457       GetElementPtrInst *GEP = GetElementPtrInst::Create(
458           StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
459       codeReplacer->getInstList().push_back(GEP);
460       StoreInst *SI = new StoreInst(StructValues[i], GEP);
461       codeReplacer->getInstList().push_back(SI);
462     }
463   }
464 
465   // Emit the call to the function
466   CallInst *call = CallInst::Create(newFunction, params,
467                                     NumExitBlocks > 1 ? "targetBlock" : "");
468   codeReplacer->getInstList().push_back(call);
469 
470   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
471   unsigned FirstOut = inputs.size();
472   if (!AggregateArgs)
473     std::advance(OutputArgBegin, inputs.size());
474 
475   // Reload the outputs passed in by reference
476   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
477     Value *Output = nullptr;
478     if (AggregateArgs) {
479       Value *Idx[2];
480       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
481       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
482       GetElementPtrInst *GEP = GetElementPtrInst::Create(
483           StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
484       codeReplacer->getInstList().push_back(GEP);
485       Output = GEP;
486     } else {
487       Output = ReloadOutputs[i];
488     }
489     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
490     Reloads.push_back(load);
491     codeReplacer->getInstList().push_back(load);
492     std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
493     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
494       Instruction *inst = cast<Instruction>(Users[u]);
495       if (!Blocks.count(inst->getParent()))
496         inst->replaceUsesOfWith(outputs[i], load);
497     }
498   }
499 
500   // Now we can emit a switch statement using the call as a value.
501   SwitchInst *TheSwitch =
502       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
503                          codeReplacer, 0, codeReplacer);
504 
505   // Since there may be multiple exits from the original region, make the new
506   // function return an unsigned, switch on that number.  This loop iterates
507   // over all of the blocks in the extracted region, updating any terminator
508   // instructions in the to-be-extracted region that branch to blocks that are
509   // not in the region to be extracted.
510   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
511 
512   unsigned switchVal = 0;
513   for (BasicBlock *Block : Blocks) {
514     TerminatorInst *TI = Block->getTerminator();
515     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
516       if (!Blocks.count(TI->getSuccessor(i))) {
517         BasicBlock *OldTarget = TI->getSuccessor(i);
518         // add a new basic block which returns the appropriate value
519         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
520         if (!NewTarget) {
521           // If we don't already have an exit stub for this non-extracted
522           // destination, create one now!
523           NewTarget = BasicBlock::Create(Context,
524                                          OldTarget->getName() + ".exitStub",
525                                          newFunction);
526           unsigned SuccNum = switchVal++;
527 
528           Value *brVal = nullptr;
529           switch (NumExitBlocks) {
530           case 0:
531           case 1: break;  // No value needed.
532           case 2:         // Conditional branch, return a bool
533             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
534             break;
535           default:
536             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
537             break;
538           }
539 
540           ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
541 
542           // Update the switch instruction.
543           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
544                                               SuccNum),
545                              OldTarget);
546 
547           // Restore values just before we exit
548           Function::arg_iterator OAI = OutputArgBegin;
549           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
550             // For an invoke, the normal destination is the only one that is
551             // dominated by the result of the invocation
552             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
553 
554             bool DominatesDef = true;
555 
556             BasicBlock *NormalDest = nullptr;
557             if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
558               NormalDest = Invoke->getNormalDest();
559 
560             if (NormalDest) {
561               DefBlock = NormalDest;
562 
563               // Make sure we are looking at the original successor block, not
564               // at a newly inserted exit block, which won't be in the dominator
565               // info.
566               for (const auto &I : ExitBlockMap)
567                 if (DefBlock == I.second) {
568                   DefBlock = I.first;
569                   break;
570                 }
571 
572               // In the extract block case, if the block we are extracting ends
573               // with an invoke instruction, make sure that we don't emit a
574               // store of the invoke value for the unwind block.
575               if (!DT && DefBlock != OldTarget)
576                 DominatesDef = false;
577             }
578 
579             if (DT) {
580               DominatesDef = DT->dominates(DefBlock, OldTarget);
581 
582               // If the output value is used by a phi in the target block,
583               // then we need to test for dominance of the phi's predecessor
584               // instead.  Unfortunately, this a little complicated since we
585               // have already rewritten uses of the value to uses of the reload.
586               BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
587                                                           OldTarget);
588               if (pred && DT && DT->dominates(DefBlock, pred))
589                 DominatesDef = true;
590             }
591 
592             if (DominatesDef) {
593               if (AggregateArgs) {
594                 Value *Idx[2];
595                 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
596                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
597                                           FirstOut+out);
598                 GetElementPtrInst *GEP = GetElementPtrInst::Create(
599                     StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(),
600                     NTRet);
601                 new StoreInst(outputs[out], GEP, NTRet);
602               } else {
603                 new StoreInst(outputs[out], &*OAI, NTRet);
604               }
605             }
606             // Advance output iterator even if we don't emit a store
607             if (!AggregateArgs) ++OAI;
608           }
609         }
610 
611         // rewrite the original branch instruction with this new target
612         TI->setSuccessor(i, NewTarget);
613       }
614   }
615 
616   // Now that we've done the deed, simplify the switch instruction.
617   Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
618   switch (NumExitBlocks) {
619   case 0:
620     // There are no successors (the block containing the switch itself), which
621     // means that previously this was the last part of the function, and hence
622     // this should be rewritten as a `ret'
623 
624     // Check if the function should return a value
625     if (OldFnRetTy->isVoidTy()) {
626       ReturnInst::Create(Context, nullptr, TheSwitch);  // Return void
627     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
628       // return what we have
629       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
630     } else {
631       // Otherwise we must have code extracted an unwind or something, just
632       // return whatever we want.
633       ReturnInst::Create(Context,
634                          Constant::getNullValue(OldFnRetTy), TheSwitch);
635     }
636 
637     TheSwitch->eraseFromParent();
638     break;
639   case 1:
640     // Only a single destination, change the switch into an unconditional
641     // branch.
642     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
643     TheSwitch->eraseFromParent();
644     break;
645   case 2:
646     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
647                        call, TheSwitch);
648     TheSwitch->eraseFromParent();
649     break;
650   default:
651     // Otherwise, make the default destination of the switch instruction be one
652     // of the other successors.
653     TheSwitch->setCondition(call);
654     TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
655     // Remove redundant case
656     TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
657     break;
658   }
659 }
660 
661 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
662   Function *oldFunc = (*Blocks.begin())->getParent();
663   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
664   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
665 
666   for (BasicBlock *Block : Blocks) {
667     // Delete the basic block from the old function, and the list of blocks
668     oldBlocks.remove(Block);
669 
670     // Insert this basic block into the new function
671     newBlocks.push_back(Block);
672   }
673 }
674 
675 void CodeExtractor::calculateNewCallTerminatorWeights(
676     BasicBlock *CodeReplacer,
677     DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
678     BranchProbabilityInfo *BPI) {
679   typedef BlockFrequencyInfoImplBase::Distribution Distribution;
680   typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
681 
682   // Update the branch weights for the exit block.
683   TerminatorInst *TI = CodeReplacer->getTerminator();
684   SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
685 
686   // Block Frequency distribution with dummy node.
687   Distribution BranchDist;
688 
689   // Add each of the frequencies of the successors.
690   for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
691     BlockNode ExitNode(i);
692     uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
693     if (ExitFreq != 0)
694       BranchDist.addExit(ExitNode, ExitFreq);
695     else
696       BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
697   }
698 
699   // Check for no total weight.
700   if (BranchDist.Total == 0)
701     return;
702 
703   // Normalize the distribution so that they can fit in unsigned.
704   BranchDist.normalize();
705 
706   // Create normalized branch weights and set the metadata.
707   for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
708     const auto &Weight = BranchDist.Weights[I];
709 
710     // Get the weight and update the current BFI.
711     BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
712     BranchProbability BP(Weight.Amount, BranchDist.Total);
713     BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
714   }
715   TI->setMetadata(
716       LLVMContext::MD_prof,
717       MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
718 }
719 
720 Function *CodeExtractor::extractCodeRegion() {
721   if (!isEligible())
722     return nullptr;
723 
724   ValueSet inputs, outputs;
725 
726   // Assumption: this is a single-entry code region, and the header is the first
727   // block in the region.
728   BasicBlock *header = *Blocks.begin();
729 
730   // Calculate the entry frequency of the new function before we change the root
731   //   block.
732   BlockFrequency EntryFreq;
733   if (BFI) {
734     assert(BPI && "Both BPI and BFI are required to preserve profile info");
735     for (BasicBlock *Pred : predecessors(header)) {
736       if (Blocks.count(Pred))
737         continue;
738       EntryFreq +=
739           BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
740     }
741   }
742 
743   // If we have to split PHI nodes or the entry block, do so now.
744   severSplitPHINodes(header);
745 
746   // If we have any return instructions in the region, split those blocks so
747   // that the return is not in the region.
748   splitReturnBlocks();
749 
750   Function *oldFunction = header->getParent();
751 
752   // This takes place of the original loop
753   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
754                                                 "codeRepl", oldFunction,
755                                                 header);
756 
757   // The new function needs a root node because other nodes can branch to the
758   // head of the region, but the entry node of a function cannot have preds.
759   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
760                                                "newFuncRoot");
761   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
762 
763   // Find inputs to, outputs from the code region.
764   findInputsOutputs(inputs, outputs);
765 
766   // Calculate the exit blocks for the extracted region and the total exit
767   //  weights for each of those blocks.
768   DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
769   SmallPtrSet<BasicBlock *, 1> ExitBlocks;
770   for (BasicBlock *Block : Blocks) {
771     for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
772          ++SI) {
773       if (!Blocks.count(*SI)) {
774         // Update the branch weight for this successor.
775         if (BFI) {
776           BlockFrequency &BF = ExitWeights[*SI];
777           BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
778         }
779         ExitBlocks.insert(*SI);
780       }
781     }
782   }
783   NumExitBlocks = ExitBlocks.size();
784 
785   // Construct new function based on inputs/outputs & add allocas for all defs.
786   Function *newFunction = constructFunction(inputs, outputs, header,
787                                             newFuncRoot,
788                                             codeReplacer, oldFunction,
789                                             oldFunction->getParent());
790 
791   // Update the entry count of the function.
792   if (BFI) {
793     Optional<uint64_t> EntryCount =
794         BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
795     if (EntryCount.hasValue())
796       newFunction->setEntryCount(EntryCount.getValue());
797     BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
798   }
799 
800   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
801 
802   moveCodeToFunction(newFunction);
803 
804   // Update the branch weights for the exit block.
805   if (BFI && NumExitBlocks > 1)
806     calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
807 
808   // Loop over all of the PHI nodes in the header block, and change any
809   // references to the old incoming edge to be the new incoming edge.
810   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
811     PHINode *PN = cast<PHINode>(I);
812     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
813       if (!Blocks.count(PN->getIncomingBlock(i)))
814         PN->setIncomingBlock(i, newFuncRoot);
815   }
816 
817   // Look at all successors of the codeReplacer block.  If any of these blocks
818   // had PHI nodes in them, we need to update the "from" block to be the code
819   // replacer, not the original block in the extracted region.
820   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
821                                  succ_end(codeReplacer));
822   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
823     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
824       PHINode *PN = cast<PHINode>(I);
825       std::set<BasicBlock*> ProcessedPreds;
826       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
827         if (Blocks.count(PN->getIncomingBlock(i))) {
828           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
829             PN->setIncomingBlock(i, codeReplacer);
830           else {
831             // There were multiple entries in the PHI for this block, now there
832             // is only one, so remove the duplicated entries.
833             PN->removeIncomingValue(i, false);
834             --i; --e;
835           }
836         }
837     }
838 
839   //cerr << "NEW FUNCTION: " << *newFunction;
840   //  verifyFunction(*newFunction);
841 
842   //  cerr << "OLD FUNCTION: " << *oldFunction;
843   //  verifyFunction(*oldFunction);
844 
845   DEBUG(if (verifyFunction(*newFunction))
846         report_fatal_error("verifyFunction failed!"));
847   return newFunction;
848 }
849