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