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