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