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