1f22ef01cSRoman Divacky //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the interface to tear out a code region, such as an
11f22ef01cSRoman Divacky // individual loop or a parallel section, into a new function, replacing it with
12f22ef01cSRoman Divacky // a call to the new function.
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
15f22ef01cSRoman Divacky 
167ae0e2c9SDimitry Andric #include "llvm/Transforms/Utils/CodeExtractor.h"
17139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
1891bc56edSDimitry Andric #include "llvm/ADT/SetVector.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/StringExtras.h"
20f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h"
217ae0e2c9SDimitry Andric #include "llvm/Analysis/RegionInfo.h"
227ae0e2c9SDimitry Andric #include "llvm/Analysis/RegionIterator.h"
23139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
24139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
2591bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
26139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
28139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
29139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
3091bc56edSDimitry Andric #include "llvm/IR/Verifier.h"
31139f7f9bSDimitry Andric #include "llvm/Pass.h"
32f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
33f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
34f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
35f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
36139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37f22ef01cSRoman Divacky #include <algorithm>
38f22ef01cSRoman Divacky #include <set>
39f22ef01cSRoman Divacky using namespace llvm;
40f22ef01cSRoman Divacky 
4191bc56edSDimitry Andric #define DEBUG_TYPE "code-extractor"
4291bc56edSDimitry Andric 
43f22ef01cSRoman Divacky // Provide a command-line option to aggregate function arguments into a struct
44f22ef01cSRoman Divacky // for functions produced by the code extractor. This is useful when converting
45f22ef01cSRoman Divacky // extracted functions to pthread-based code, as only one argument (void*) can
46f22ef01cSRoman Divacky // be passed in to pthread_create().
47f22ef01cSRoman Divacky static cl::opt<bool>
48f22ef01cSRoman Divacky AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
49f22ef01cSRoman Divacky                  cl::desc("Aggregate arguments to code-extracted functions"));
50f22ef01cSRoman Divacky 
517ae0e2c9SDimitry Andric /// \brief Test whether a block is valid for extraction.
527ae0e2c9SDimitry Andric static bool isBlockValidForExtraction(const BasicBlock &BB) {
537ae0e2c9SDimitry Andric   // Landing pads must be in the function where they were inserted for cleanup.
547d523365SDimitry Andric   if (BB.isEHPad())
557ae0e2c9SDimitry Andric     return false;
56f22ef01cSRoman Divacky 
577ae0e2c9SDimitry Andric   // Don't hoist code containing allocas, invokes, or vastarts.
587ae0e2c9SDimitry Andric   for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
597ae0e2c9SDimitry Andric     if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
607ae0e2c9SDimitry Andric       return false;
617ae0e2c9SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(I))
627ae0e2c9SDimitry Andric       if (const Function *F = CI->getCalledFunction())
637ae0e2c9SDimitry Andric         if (F->getIntrinsicID() == Intrinsic::vastart)
647ae0e2c9SDimitry Andric           return false;
657ae0e2c9SDimitry Andric   }
66f22ef01cSRoman Divacky 
677ae0e2c9SDimitry Andric   return true;
687ae0e2c9SDimitry Andric }
69f22ef01cSRoman Divacky 
707ae0e2c9SDimitry Andric /// \brief Build a set of blocks to extract if the input blocks are viable.
717ae0e2c9SDimitry Andric template <typename IteratorT>
727ae0e2c9SDimitry Andric static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin,
737ae0e2c9SDimitry Andric                                                        IteratorT BBEnd) {
747ae0e2c9SDimitry Andric   SetVector<BasicBlock *> Result;
757ae0e2c9SDimitry Andric 
767ae0e2c9SDimitry Andric   assert(BBBegin != BBEnd);
777ae0e2c9SDimitry Andric 
787ae0e2c9SDimitry Andric   // Loop over the blocks, adding them to our set-vector, and aborting with an
797ae0e2c9SDimitry Andric   // empty set if we encounter invalid blocks.
803ca95b02SDimitry Andric   do {
813ca95b02SDimitry Andric     if (!Result.insert(*BBBegin))
827ae0e2c9SDimitry Andric       llvm_unreachable("Repeated basic blocks in extraction input");
837ae0e2c9SDimitry Andric 
843ca95b02SDimitry Andric     if (!isBlockValidForExtraction(**BBBegin)) {
857ae0e2c9SDimitry Andric       Result.clear();
867ae0e2c9SDimitry Andric       return Result;
877ae0e2c9SDimitry Andric     }
883ca95b02SDimitry Andric   } while (++BBBegin != BBEnd);
897ae0e2c9SDimitry Andric 
907ae0e2c9SDimitry Andric #ifndef NDEBUG
9191bc56edSDimitry Andric   for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
927ae0e2c9SDimitry Andric                                          E = Result.end();
937ae0e2c9SDimitry Andric        I != E; ++I)
947ae0e2c9SDimitry Andric     for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
957ae0e2c9SDimitry Andric          PI != PE; ++PI)
967ae0e2c9SDimitry Andric       assert(Result.count(*PI) &&
977ae0e2c9SDimitry Andric              "No blocks in this region may have entries from outside the region"
987ae0e2c9SDimitry Andric              " except for the first block!");
997ae0e2c9SDimitry Andric #endif
1007ae0e2c9SDimitry Andric 
1017ae0e2c9SDimitry Andric   return Result;
1027ae0e2c9SDimitry Andric }
1037ae0e2c9SDimitry Andric 
1047ae0e2c9SDimitry Andric /// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
1057ae0e2c9SDimitry Andric static SetVector<BasicBlock *>
1067ae0e2c9SDimitry Andric buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
1077ae0e2c9SDimitry Andric   return buildExtractionBlockSet(BBs.begin(), BBs.end());
1087ae0e2c9SDimitry Andric }
1097ae0e2c9SDimitry Andric 
1107ae0e2c9SDimitry Andric /// \brief Helper to call buildExtractionBlockSet with a RegionNode.
1117ae0e2c9SDimitry Andric static SetVector<BasicBlock *>
1127ae0e2c9SDimitry Andric buildExtractionBlockSet(const RegionNode &RN) {
1137ae0e2c9SDimitry Andric   if (!RN.isSubRegion())
1147ae0e2c9SDimitry Andric     // Just a single BasicBlock.
1157ae0e2c9SDimitry Andric     return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>());
1167ae0e2c9SDimitry Andric 
1177ae0e2c9SDimitry Andric   const Region &R = *RN.getNodeAs<Region>();
1187ae0e2c9SDimitry Andric 
1197ae0e2c9SDimitry Andric   return buildExtractionBlockSet(R.block_begin(), R.block_end());
1207ae0e2c9SDimitry Andric }
1217ae0e2c9SDimitry Andric 
1227ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
12391bc56edSDimitry Andric   : DT(nullptr), AggregateArgs(AggregateArgs||AggregateArgsOpt),
1247ae0e2c9SDimitry Andric     Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
1257ae0e2c9SDimitry Andric 
1267ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
1277ae0e2c9SDimitry Andric                              bool AggregateArgs)
1287ae0e2c9SDimitry Andric   : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
1297ae0e2c9SDimitry Andric     Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
1307ae0e2c9SDimitry Andric 
1317ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
1327ae0e2c9SDimitry Andric   : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
1337ae0e2c9SDimitry Andric     Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
1347ae0e2c9SDimitry Andric 
1357ae0e2c9SDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN,
1367ae0e2c9SDimitry Andric                              bool AggregateArgs)
1377ae0e2c9SDimitry Andric   : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
1387ae0e2c9SDimitry Andric     Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {}
1397ae0e2c9SDimitry Andric 
140f22ef01cSRoman Divacky /// definedInRegion - Return true if the specified value is defined in the
141f22ef01cSRoman Divacky /// extracted region.
1427ae0e2c9SDimitry Andric static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
143f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(V))
1447ae0e2c9SDimitry Andric     if (Blocks.count(I->getParent()))
145f22ef01cSRoman Divacky       return true;
146f22ef01cSRoman Divacky   return false;
147f22ef01cSRoman Divacky }
148f22ef01cSRoman Divacky 
149f22ef01cSRoman Divacky /// definedInCaller - Return true if the specified value is defined in the
150f22ef01cSRoman Divacky /// function being code extracted, but not in the region being extracted.
151f22ef01cSRoman Divacky /// These values must be passed in as live-ins to the function.
1527ae0e2c9SDimitry Andric static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
153f22ef01cSRoman Divacky   if (isa<Argument>(V)) return true;
154f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(V))
1557ae0e2c9SDimitry Andric     if (!Blocks.count(I->getParent()))
156f22ef01cSRoman Divacky       return true;
157f22ef01cSRoman Divacky   return false;
158f22ef01cSRoman Divacky }
159f22ef01cSRoman Divacky 
1607ae0e2c9SDimitry Andric void CodeExtractor::findInputsOutputs(ValueSet &Inputs,
1617ae0e2c9SDimitry Andric                                       ValueSet &Outputs) const {
1623ca95b02SDimitry Andric   for (BasicBlock *BB : Blocks) {
1637ae0e2c9SDimitry Andric     // If a used value is defined outside the region, it's an input.  If an
1647ae0e2c9SDimitry Andric     // instruction is used outside the region, it's an output.
1653ca95b02SDimitry Andric     for (Instruction &II : *BB) {
1663ca95b02SDimitry Andric       for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
1673ca95b02SDimitry Andric            ++OI)
1687ae0e2c9SDimitry Andric         if (definedInCaller(Blocks, *OI))
1697ae0e2c9SDimitry Andric           Inputs.insert(*OI);
170f22ef01cSRoman Divacky 
1713ca95b02SDimitry Andric       for (User *U : II.users())
17291bc56edSDimitry Andric         if (!definedInRegion(Blocks, U)) {
1733ca95b02SDimitry Andric           Outputs.insert(&II);
1747ae0e2c9SDimitry Andric           break;
1757ae0e2c9SDimitry Andric         }
1767ae0e2c9SDimitry Andric     }
1777ae0e2c9SDimitry Andric   }
178f22ef01cSRoman Divacky }
179f22ef01cSRoman Divacky 
180f22ef01cSRoman Divacky /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
181f22ef01cSRoman Divacky /// region, we need to split the entry block of the region so that the PHI node
182f22ef01cSRoman Divacky /// is easier to deal with.
183f22ef01cSRoman Divacky void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
1843b0f4066SDimitry Andric   unsigned NumPredsFromRegion = 0;
185f22ef01cSRoman Divacky   unsigned NumPredsOutsideRegion = 0;
186f22ef01cSRoman Divacky 
187f22ef01cSRoman Divacky   if (Header != &Header->getParent()->getEntryBlock()) {
188f22ef01cSRoman Divacky     PHINode *PN = dyn_cast<PHINode>(Header->begin());
189f22ef01cSRoman Divacky     if (!PN) return;  // No PHI nodes.
190f22ef01cSRoman Divacky 
191f22ef01cSRoman Divacky     // If the header node contains any PHI nodes, check to see if there is more
192f22ef01cSRoman Divacky     // than one entry from outside the region.  If so, we need to sever the
193f22ef01cSRoman Divacky     // header block into two.
194f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1957ae0e2c9SDimitry Andric       if (Blocks.count(PN->getIncomingBlock(i)))
1963b0f4066SDimitry Andric         ++NumPredsFromRegion;
197f22ef01cSRoman Divacky       else
198f22ef01cSRoman Divacky         ++NumPredsOutsideRegion;
199f22ef01cSRoman Divacky 
200f22ef01cSRoman Divacky     // If there is one (or fewer) predecessor from outside the region, we don't
201f22ef01cSRoman Divacky     // need to do anything special.
202f22ef01cSRoman Divacky     if (NumPredsOutsideRegion <= 1) return;
203f22ef01cSRoman Divacky   }
204f22ef01cSRoman Divacky 
205f22ef01cSRoman Divacky   // Otherwise, we need to split the header block into two pieces: one
206f22ef01cSRoman Divacky   // containing PHI nodes merging values from outside of the region, and a
207f22ef01cSRoman Divacky   // second that contains all of the code for the block and merges back any
208f22ef01cSRoman Divacky   // incoming values from inside of the region.
2097d523365SDimitry Andric   BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI()->getIterator();
210f22ef01cSRoman Divacky   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
211f22ef01cSRoman Divacky                                               Header->getName()+".ce");
212f22ef01cSRoman Divacky 
213f22ef01cSRoman Divacky   // We only want to code extract the second block now, and it becomes the new
214f22ef01cSRoman Divacky   // header of the region.
215f22ef01cSRoman Divacky   BasicBlock *OldPred = Header;
2167ae0e2c9SDimitry Andric   Blocks.remove(OldPred);
2177ae0e2c9SDimitry Andric   Blocks.insert(NewBB);
218f22ef01cSRoman Divacky   Header = NewBB;
219f22ef01cSRoman Divacky 
220f22ef01cSRoman Divacky   // Okay, update dominator sets. The blocks that dominate the new one are the
221f22ef01cSRoman Divacky   // blocks that dominate TIBB plus the new block itself.
222f22ef01cSRoman Divacky   if (DT)
223f22ef01cSRoman Divacky     DT->splitBlock(NewBB);
224f22ef01cSRoman Divacky 
225f22ef01cSRoman Divacky   // Okay, now we need to adjust the PHI nodes and any branches from within the
226f22ef01cSRoman Divacky   // region to go to the new header block instead of the old header block.
2273b0f4066SDimitry Andric   if (NumPredsFromRegion) {
228f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(OldPred->begin());
229f22ef01cSRoman Divacky     // Loop over all of the predecessors of OldPred that are in the region,
230f22ef01cSRoman Divacky     // changing them to branch to NewBB instead.
231f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2327ae0e2c9SDimitry Andric       if (Blocks.count(PN->getIncomingBlock(i))) {
233f22ef01cSRoman Divacky         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
234f22ef01cSRoman Divacky         TI->replaceUsesOfWith(OldPred, NewBB);
235f22ef01cSRoman Divacky       }
236f22ef01cSRoman Divacky 
2373b0f4066SDimitry Andric     // Okay, everything within the region is now branching to the right block, we
238f22ef01cSRoman Divacky     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
239f22ef01cSRoman Divacky     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
240f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(AfterPHIs);
241f22ef01cSRoman Divacky       // Create a new PHI node in the new region, which has an incoming value
242f22ef01cSRoman Divacky       // from OldPred of PN.
2433b0f4066SDimitry Andric       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
2447d523365SDimitry Andric                                        PN->getName() + ".ce", &NewBB->front());
245f22ef01cSRoman Divacky       NewPN->addIncoming(PN, OldPred);
246f22ef01cSRoman Divacky 
247f22ef01cSRoman Divacky       // Loop over all of the incoming value in PN, moving them to NewPN if they
248f22ef01cSRoman Divacky       // are from the extracted region.
249f22ef01cSRoman Divacky       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
2507ae0e2c9SDimitry Andric         if (Blocks.count(PN->getIncomingBlock(i))) {
251f22ef01cSRoman Divacky           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
252f22ef01cSRoman Divacky           PN->removeIncomingValue(i);
253f22ef01cSRoman Divacky           --i;
254f22ef01cSRoman Divacky         }
255f22ef01cSRoman Divacky       }
256f22ef01cSRoman Divacky     }
257f22ef01cSRoman Divacky   }
258f22ef01cSRoman Divacky }
259f22ef01cSRoman Divacky 
260f22ef01cSRoman Divacky void CodeExtractor::splitReturnBlocks() {
2613ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks)
2623ca95b02SDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
2637d523365SDimitry Andric       BasicBlock *New =
2643ca95b02SDimitry Andric           Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
265f22ef01cSRoman Divacky       if (DT) {
2662754fe60SDimitry Andric         // Old dominates New. New node dominates all other nodes dominated
267f22ef01cSRoman Divacky         // by Old.
2683ca95b02SDimitry Andric         DomTreeNode *OldNode = DT->getNode(Block);
2693ca95b02SDimitry Andric         SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
2703ca95b02SDimitry Andric                                                OldNode->end());
271f22ef01cSRoman Divacky 
2723ca95b02SDimitry Andric         DomTreeNode *NewNode = DT->addNewBlock(New, Block);
273f22ef01cSRoman Divacky 
2743ca95b02SDimitry Andric         for (DomTreeNode *I : Children)
2753ca95b02SDimitry Andric           DT->changeImmediateDominator(I, NewNode);
276f22ef01cSRoman Divacky       }
277f22ef01cSRoman Divacky     }
278f22ef01cSRoman Divacky }
279f22ef01cSRoman Divacky 
280f22ef01cSRoman Divacky /// constructFunction - make a function based on inputs and outputs, as follows:
281f22ef01cSRoman Divacky /// f(in0, ..., inN, out0, ..., outN)
282f22ef01cSRoman Divacky ///
2837ae0e2c9SDimitry Andric Function *CodeExtractor::constructFunction(const ValueSet &inputs,
2847ae0e2c9SDimitry Andric                                            const ValueSet &outputs,
285f22ef01cSRoman Divacky                                            BasicBlock *header,
286f22ef01cSRoman Divacky                                            BasicBlock *newRootNode,
287f22ef01cSRoman Divacky                                            BasicBlock *newHeader,
288f22ef01cSRoman Divacky                                            Function *oldFunction,
289f22ef01cSRoman Divacky                                            Module *M) {
290f22ef01cSRoman Divacky   DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
291f22ef01cSRoman Divacky   DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
292f22ef01cSRoman Divacky 
293f22ef01cSRoman Divacky   // This function returns unsigned, outputs will go back by reference.
294f22ef01cSRoman Divacky   switch (NumExitBlocks) {
295f22ef01cSRoman Divacky   case 0:
296f22ef01cSRoman Divacky   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
297f22ef01cSRoman Divacky   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
298f22ef01cSRoman Divacky   default: RetTy = Type::getInt16Ty(header->getContext()); break;
299f22ef01cSRoman Divacky   }
300f22ef01cSRoman Divacky 
30117a519f9SDimitry Andric   std::vector<Type*> paramTy;
302f22ef01cSRoman Divacky 
303f22ef01cSRoman Divacky   // Add the types of the input values to the function's argument list
3043ca95b02SDimitry Andric   for (Value *value : inputs) {
305f22ef01cSRoman Divacky     DEBUG(dbgs() << "value used in func: " << *value << "\n");
306f22ef01cSRoman Divacky     paramTy.push_back(value->getType());
307f22ef01cSRoman Divacky   }
308f22ef01cSRoman Divacky 
309f22ef01cSRoman Divacky   // Add the types of the output values to the function's argument list.
3103ca95b02SDimitry Andric   for (Value *output : outputs) {
3113ca95b02SDimitry Andric     DEBUG(dbgs() << "instr used in func: " << *output << "\n");
312f22ef01cSRoman Divacky     if (AggregateArgs)
3133ca95b02SDimitry Andric       paramTy.push_back(output->getType());
314f22ef01cSRoman Divacky     else
3153ca95b02SDimitry Andric       paramTy.push_back(PointerType::getUnqual(output->getType()));
316f22ef01cSRoman Divacky   }
317f22ef01cSRoman Divacky 
3183ca95b02SDimitry Andric   DEBUG({
3193ca95b02SDimitry Andric     dbgs() << "Function type: " << *RetTy << " f(";
3203ca95b02SDimitry Andric     for (Type *i : paramTy)
3213ca95b02SDimitry Andric       dbgs() << *i << ", ";
3223ca95b02SDimitry Andric     dbgs() << ")\n";
3233ca95b02SDimitry Andric   });
324f22ef01cSRoman Divacky 
325ff0cc061SDimitry Andric   StructType *StructTy;
326f22ef01cSRoman Divacky   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
327ff0cc061SDimitry Andric     StructTy = StructType::get(M->getContext(), paramTy);
328f22ef01cSRoman Divacky     paramTy.clear();
329ff0cc061SDimitry Andric     paramTy.push_back(PointerType::getUnqual(StructTy));
330f22ef01cSRoman Divacky   }
3316122f3e6SDimitry Andric   FunctionType *funcType =
332f22ef01cSRoman Divacky                   FunctionType::get(RetTy, paramTy, false);
333f22ef01cSRoman Divacky 
334f22ef01cSRoman Divacky   // Create the new function
335f22ef01cSRoman Divacky   Function *newFunction = Function::Create(funcType,
336f22ef01cSRoman Divacky                                            GlobalValue::InternalLinkage,
337f22ef01cSRoman Divacky                                            oldFunction->getName() + "_" +
338f22ef01cSRoman Divacky                                            header->getName(), M);
339f22ef01cSRoman Divacky   // If the old function is no-throw, so is the new one.
340f22ef01cSRoman Divacky   if (oldFunction->doesNotThrow())
3413861d79fSDimitry Andric     newFunction->setDoesNotThrow();
342f22ef01cSRoman Divacky 
343f22ef01cSRoman Divacky   newFunction->getBasicBlockList().push_back(newRootNode);
344f22ef01cSRoman Divacky 
345f22ef01cSRoman Divacky   // Create an iterator to name all of the arguments we inserted.
346f22ef01cSRoman Divacky   Function::arg_iterator AI = newFunction->arg_begin();
347f22ef01cSRoman Divacky 
348f22ef01cSRoman Divacky   // Rewrite all users of the inputs in the extracted region to use the
349f22ef01cSRoman Divacky   // arguments (or appropriate addressing into struct) instead.
350f22ef01cSRoman Divacky   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
351f22ef01cSRoman Divacky     Value *RewriteVal;
352f22ef01cSRoman Divacky     if (AggregateArgs) {
353f22ef01cSRoman Divacky       Value *Idx[2];
354f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
355f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
356f22ef01cSRoman Divacky       TerminatorInst *TI = newFunction->begin()->getTerminator();
357ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
3587d523365SDimitry Andric           StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
359f22ef01cSRoman Divacky       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
360f22ef01cSRoman Divacky     } else
3617d523365SDimitry Andric       RewriteVal = &*AI++;
362f22ef01cSRoman Divacky 
36391bc56edSDimitry Andric     std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
3643ca95b02SDimitry Andric     for (User *use : Users)
3653ca95b02SDimitry Andric       if (Instruction *inst = dyn_cast<Instruction>(use))
3667ae0e2c9SDimitry Andric         if (Blocks.count(inst->getParent()))
367f22ef01cSRoman Divacky           inst->replaceUsesOfWith(inputs[i], RewriteVal);
368f22ef01cSRoman Divacky   }
369f22ef01cSRoman Divacky 
370f22ef01cSRoman Divacky   // Set names for input and output arguments.
371f22ef01cSRoman Divacky   if (!AggregateArgs) {
372f22ef01cSRoman Divacky     AI = newFunction->arg_begin();
373f22ef01cSRoman Divacky     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
374f22ef01cSRoman Divacky       AI->setName(inputs[i]->getName());
375f22ef01cSRoman Divacky     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
376f22ef01cSRoman Divacky       AI->setName(outputs[i]->getName()+".out");
377f22ef01cSRoman Divacky   }
378f22ef01cSRoman Divacky 
379f22ef01cSRoman Divacky   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
380f22ef01cSRoman Divacky   // within the new function. This must be done before we lose track of which
381f22ef01cSRoman Divacky   // blocks were originally in the code region.
38291bc56edSDimitry Andric   std::vector<User*> Users(header->user_begin(), header->user_end());
383f22ef01cSRoman Divacky   for (unsigned i = 0, e = Users.size(); i != e; ++i)
384f22ef01cSRoman Divacky     // The BasicBlock which contains the branch is not in the region
385f22ef01cSRoman Divacky     // modify the branch target to a new block
386f22ef01cSRoman Divacky     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
3877ae0e2c9SDimitry Andric       if (!Blocks.count(TI->getParent()) &&
388f22ef01cSRoman Divacky           TI->getParent()->getParent() == oldFunction)
389f22ef01cSRoman Divacky         TI->replaceUsesOfWith(header, newHeader);
390f22ef01cSRoman Divacky 
391f22ef01cSRoman Divacky   return newFunction;
392f22ef01cSRoman Divacky }
393f22ef01cSRoman Divacky 
394f22ef01cSRoman Divacky /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
395f22ef01cSRoman Divacky /// that uses the value within the basic block, and return the predecessor
396f22ef01cSRoman Divacky /// block associated with that use, or return 0 if none is found.
397f22ef01cSRoman Divacky static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
39891bc56edSDimitry Andric   for (Use &U : Used->uses()) {
39991bc56edSDimitry Andric      PHINode *P = dyn_cast<PHINode>(U.getUser());
400f22ef01cSRoman Divacky      if (P && P->getParent() == BB)
40191bc56edSDimitry Andric        return P->getIncomingBlock(U);
402f22ef01cSRoman Divacky   }
403f22ef01cSRoman Divacky 
40491bc56edSDimitry Andric   return nullptr;
405f22ef01cSRoman Divacky }
406f22ef01cSRoman Divacky 
407f22ef01cSRoman Divacky /// emitCallAndSwitchStatement - This method sets up the caller side by adding
408f22ef01cSRoman Divacky /// the call instruction, splitting any PHI nodes in the header block as
409f22ef01cSRoman Divacky /// necessary.
410f22ef01cSRoman Divacky void CodeExtractor::
411f22ef01cSRoman Divacky emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
4127ae0e2c9SDimitry Andric                            ValueSet &inputs, ValueSet &outputs) {
413f22ef01cSRoman Divacky   // Emit a call to the new function, passing in: *pointer to struct (if
414f22ef01cSRoman Divacky   // aggregating parameters), or plan inputs and allocated memory for outputs
415f22ef01cSRoman Divacky   std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
416f22ef01cSRoman Divacky 
417f22ef01cSRoman Divacky   LLVMContext &Context = newFunction->getContext();
418f22ef01cSRoman Divacky 
419f22ef01cSRoman Divacky   // Add inputs as params, or to be filled into the struct
4203ca95b02SDimitry Andric   for (Value *input : inputs)
421f22ef01cSRoman Divacky     if (AggregateArgs)
4223ca95b02SDimitry Andric       StructValues.push_back(input);
423f22ef01cSRoman Divacky     else
4243ca95b02SDimitry Andric       params.push_back(input);
425f22ef01cSRoman Divacky 
426f22ef01cSRoman Divacky   // Create allocas for the outputs
4273ca95b02SDimitry Andric   for (Value *output : outputs) {
428f22ef01cSRoman Divacky     if (AggregateArgs) {
4293ca95b02SDimitry Andric       StructValues.push_back(output);
430f22ef01cSRoman Divacky     } else {
431f22ef01cSRoman Divacky       AllocaInst *alloca =
4323ca95b02SDimitry Andric           new AllocaInst(output->getType(), nullptr, output->getName() + ".loc",
4337d523365SDimitry Andric                          &codeReplacer->getParent()->front().front());
434f22ef01cSRoman Divacky       ReloadOutputs.push_back(alloca);
435f22ef01cSRoman Divacky       params.push_back(alloca);
436f22ef01cSRoman Divacky     }
437f22ef01cSRoman Divacky   }
438f22ef01cSRoman Divacky 
439ff0cc061SDimitry Andric   StructType *StructArgTy = nullptr;
44091bc56edSDimitry Andric   AllocaInst *Struct = nullptr;
441f22ef01cSRoman Divacky   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
44217a519f9SDimitry Andric     std::vector<Type*> ArgTypes;
4437ae0e2c9SDimitry Andric     for (ValueSet::iterator v = StructValues.begin(),
444f22ef01cSRoman Divacky            ve = StructValues.end(); v != ve; ++v)
445f22ef01cSRoman Divacky       ArgTypes.push_back((*v)->getType());
446f22ef01cSRoman Divacky 
447f22ef01cSRoman Divacky     // Allocate a struct at the beginning of this function
448ff0cc061SDimitry Andric     StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
4497d523365SDimitry Andric     Struct = new AllocaInst(StructArgTy, nullptr, "structArg",
4507d523365SDimitry Andric                             &codeReplacer->getParent()->front().front());
451f22ef01cSRoman Divacky     params.push_back(Struct);
452f22ef01cSRoman Divacky 
453f22ef01cSRoman Divacky     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
454f22ef01cSRoman Divacky       Value *Idx[2];
455f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
456f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
457ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
458ff0cc061SDimitry Andric           StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
459f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(GEP);
460f22ef01cSRoman Divacky       StoreInst *SI = new StoreInst(StructValues[i], GEP);
461f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(SI);
462f22ef01cSRoman Divacky     }
463f22ef01cSRoman Divacky   }
464f22ef01cSRoman Divacky 
465f22ef01cSRoman Divacky   // Emit the call to the function
46617a519f9SDimitry Andric   CallInst *call = CallInst::Create(newFunction, params,
467f22ef01cSRoman Divacky                                     NumExitBlocks > 1 ? "targetBlock" : "");
468f22ef01cSRoman Divacky   codeReplacer->getInstList().push_back(call);
469f22ef01cSRoman Divacky 
470f22ef01cSRoman Divacky   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
471f22ef01cSRoman Divacky   unsigned FirstOut = inputs.size();
472f22ef01cSRoman Divacky   if (!AggregateArgs)
473f22ef01cSRoman Divacky     std::advance(OutputArgBegin, inputs.size());
474f22ef01cSRoman Divacky 
475f22ef01cSRoman Divacky   // Reload the outputs passed in by reference
476f22ef01cSRoman Divacky   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
47791bc56edSDimitry Andric     Value *Output = nullptr;
478f22ef01cSRoman Divacky     if (AggregateArgs) {
479f22ef01cSRoman Divacky       Value *Idx[2];
480f22ef01cSRoman Divacky       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
481f22ef01cSRoman Divacky       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
482ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
483ff0cc061SDimitry Andric           StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
484f22ef01cSRoman Divacky       codeReplacer->getInstList().push_back(GEP);
485f22ef01cSRoman Divacky       Output = GEP;
486f22ef01cSRoman Divacky     } else {
487f22ef01cSRoman Divacky       Output = ReloadOutputs[i];
488f22ef01cSRoman Divacky     }
489f22ef01cSRoman Divacky     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
490f22ef01cSRoman Divacky     Reloads.push_back(load);
491f22ef01cSRoman Divacky     codeReplacer->getInstList().push_back(load);
49291bc56edSDimitry Andric     std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
493f22ef01cSRoman Divacky     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
494f22ef01cSRoman Divacky       Instruction *inst = cast<Instruction>(Users[u]);
4957ae0e2c9SDimitry Andric       if (!Blocks.count(inst->getParent()))
496f22ef01cSRoman Divacky         inst->replaceUsesOfWith(outputs[i], load);
497f22ef01cSRoman Divacky     }
498f22ef01cSRoman Divacky   }
499f22ef01cSRoman Divacky 
500f22ef01cSRoman Divacky   // Now we can emit a switch statement using the call as a value.
501f22ef01cSRoman Divacky   SwitchInst *TheSwitch =
502f22ef01cSRoman Divacky       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
503f22ef01cSRoman Divacky                          codeReplacer, 0, codeReplacer);
504f22ef01cSRoman Divacky 
505f22ef01cSRoman Divacky   // Since there may be multiple exits from the original region, make the new
506f22ef01cSRoman Divacky   // function return an unsigned, switch on that number.  This loop iterates
507f22ef01cSRoman Divacky   // over all of the blocks in the extracted region, updating any terminator
508f22ef01cSRoman Divacky   // instructions in the to-be-extracted region that branch to blocks that are
509f22ef01cSRoman Divacky   // not in the region to be extracted.
510f22ef01cSRoman Divacky   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
511f22ef01cSRoman Divacky 
512f22ef01cSRoman Divacky   unsigned switchVal = 0;
5133ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks) {
5143ca95b02SDimitry Andric     TerminatorInst *TI = Block->getTerminator();
515f22ef01cSRoman Divacky     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
5167ae0e2c9SDimitry Andric       if (!Blocks.count(TI->getSuccessor(i))) {
517f22ef01cSRoman Divacky         BasicBlock *OldTarget = TI->getSuccessor(i);
518f22ef01cSRoman Divacky         // add a new basic block which returns the appropriate value
519f22ef01cSRoman Divacky         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
520f22ef01cSRoman Divacky         if (!NewTarget) {
521f22ef01cSRoman Divacky           // If we don't already have an exit stub for this non-extracted
522f22ef01cSRoman Divacky           // destination, create one now!
523f22ef01cSRoman Divacky           NewTarget = BasicBlock::Create(Context,
524f22ef01cSRoman Divacky                                          OldTarget->getName() + ".exitStub",
525f22ef01cSRoman Divacky                                          newFunction);
526f22ef01cSRoman Divacky           unsigned SuccNum = switchVal++;
527f22ef01cSRoman Divacky 
52891bc56edSDimitry Andric           Value *brVal = nullptr;
529f22ef01cSRoman Divacky           switch (NumExitBlocks) {
530f22ef01cSRoman Divacky           case 0:
531f22ef01cSRoman Divacky           case 1: break;  // No value needed.
532f22ef01cSRoman Divacky           case 2:         // Conditional branch, return a bool
533f22ef01cSRoman Divacky             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
534f22ef01cSRoman Divacky             break;
535f22ef01cSRoman Divacky           default:
536f22ef01cSRoman Divacky             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
537f22ef01cSRoman Divacky             break;
538f22ef01cSRoman Divacky           }
539f22ef01cSRoman Divacky 
540f22ef01cSRoman Divacky           ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
541f22ef01cSRoman Divacky 
542f22ef01cSRoman Divacky           // Update the switch instruction.
543f22ef01cSRoman Divacky           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
544f22ef01cSRoman Divacky                                               SuccNum),
545f22ef01cSRoman Divacky                              OldTarget);
546f22ef01cSRoman Divacky 
547f22ef01cSRoman Divacky           // Restore values just before we exit
548f22ef01cSRoman Divacky           Function::arg_iterator OAI = OutputArgBegin;
549f22ef01cSRoman Divacky           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
550f22ef01cSRoman Divacky             // For an invoke, the normal destination is the only one that is
551f22ef01cSRoman Divacky             // dominated by the result of the invocation
552f22ef01cSRoman Divacky             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
553f22ef01cSRoman Divacky 
554f22ef01cSRoman Divacky             bool DominatesDef = true;
555f22ef01cSRoman Divacky 
5567d523365SDimitry Andric             BasicBlock *NormalDest = nullptr;
5577d523365SDimitry Andric             if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
5587d523365SDimitry Andric               NormalDest = Invoke->getNormalDest();
5597d523365SDimitry Andric 
5607d523365SDimitry Andric             if (NormalDest) {
5617d523365SDimitry Andric               DefBlock = NormalDest;
562f22ef01cSRoman Divacky 
563f22ef01cSRoman Divacky               // Make sure we are looking at the original successor block, not
564f22ef01cSRoman Divacky               // at a newly inserted exit block, which won't be in the dominator
565f22ef01cSRoman Divacky               // info.
5663ca95b02SDimitry Andric               for (const auto &I : ExitBlockMap)
5673ca95b02SDimitry Andric                 if (DefBlock == I.second) {
5683ca95b02SDimitry Andric                   DefBlock = I.first;
569f22ef01cSRoman Divacky                   break;
570f22ef01cSRoman Divacky                 }
571f22ef01cSRoman Divacky 
572f22ef01cSRoman Divacky               // In the extract block case, if the block we are extracting ends
573f22ef01cSRoman Divacky               // with an invoke instruction, make sure that we don't emit a
574f22ef01cSRoman Divacky               // store of the invoke value for the unwind block.
575f22ef01cSRoman Divacky               if (!DT && DefBlock != OldTarget)
576f22ef01cSRoman Divacky                 DominatesDef = false;
577f22ef01cSRoman Divacky             }
578f22ef01cSRoman Divacky 
579f22ef01cSRoman Divacky             if (DT) {
580f22ef01cSRoman Divacky               DominatesDef = DT->dominates(DefBlock, OldTarget);
581f22ef01cSRoman Divacky 
582f22ef01cSRoman Divacky               // If the output value is used by a phi in the target block,
583f22ef01cSRoman Divacky               // then we need to test for dominance of the phi's predecessor
584f22ef01cSRoman Divacky               // instead.  Unfortunately, this a little complicated since we
585f22ef01cSRoman Divacky               // have already rewritten uses of the value to uses of the reload.
586f22ef01cSRoman Divacky               BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
587f22ef01cSRoman Divacky                                                           OldTarget);
588f22ef01cSRoman Divacky               if (pred && DT && DT->dominates(DefBlock, pred))
589f22ef01cSRoman Divacky                 DominatesDef = true;
590f22ef01cSRoman Divacky             }
591f22ef01cSRoman Divacky 
592f22ef01cSRoman Divacky             if (DominatesDef) {
593f22ef01cSRoman Divacky               if (AggregateArgs) {
594f22ef01cSRoman Divacky                 Value *Idx[2];
595f22ef01cSRoman Divacky                 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
596f22ef01cSRoman Divacky                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
597f22ef01cSRoman Divacky                                           FirstOut+out);
598ff0cc061SDimitry Andric                 GetElementPtrInst *GEP = GetElementPtrInst::Create(
5997d523365SDimitry Andric                     StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(),
600f22ef01cSRoman Divacky                     NTRet);
601f22ef01cSRoman Divacky                 new StoreInst(outputs[out], GEP, NTRet);
602f22ef01cSRoman Divacky               } else {
6037d523365SDimitry Andric                 new StoreInst(outputs[out], &*OAI, NTRet);
604f22ef01cSRoman Divacky               }
605f22ef01cSRoman Divacky             }
606f22ef01cSRoman Divacky             // Advance output iterator even if we don't emit a store
607f22ef01cSRoman Divacky             if (!AggregateArgs) ++OAI;
608f22ef01cSRoman Divacky           }
609f22ef01cSRoman Divacky         }
610f22ef01cSRoman Divacky 
611f22ef01cSRoman Divacky         // rewrite the original branch instruction with this new target
612f22ef01cSRoman Divacky         TI->setSuccessor(i, NewTarget);
613f22ef01cSRoman Divacky       }
614f22ef01cSRoman Divacky   }
615f22ef01cSRoman Divacky 
616f22ef01cSRoman Divacky   // Now that we've done the deed, simplify the switch instruction.
6176122f3e6SDimitry Andric   Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
618f22ef01cSRoman Divacky   switch (NumExitBlocks) {
619f22ef01cSRoman Divacky   case 0:
620f22ef01cSRoman Divacky     // There are no successors (the block containing the switch itself), which
621f22ef01cSRoman Divacky     // means that previously this was the last part of the function, and hence
622f22ef01cSRoman Divacky     // this should be rewritten as a `ret'
623f22ef01cSRoman Divacky 
624f22ef01cSRoman Divacky     // Check if the function should return a value
625f22ef01cSRoman Divacky     if (OldFnRetTy->isVoidTy()) {
62691bc56edSDimitry Andric       ReturnInst::Create(Context, nullptr, TheSwitch);  // Return void
627f22ef01cSRoman Divacky     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
628f22ef01cSRoman Divacky       // return what we have
629f22ef01cSRoman Divacky       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
630f22ef01cSRoman Divacky     } else {
631f22ef01cSRoman Divacky       // Otherwise we must have code extracted an unwind or something, just
632f22ef01cSRoman Divacky       // return whatever we want.
633f22ef01cSRoman Divacky       ReturnInst::Create(Context,
634f22ef01cSRoman Divacky                          Constant::getNullValue(OldFnRetTy), TheSwitch);
635f22ef01cSRoman Divacky     }
636f22ef01cSRoman Divacky 
637f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
638f22ef01cSRoman Divacky     break;
639f22ef01cSRoman Divacky   case 1:
640f22ef01cSRoman Divacky     // Only a single destination, change the switch into an unconditional
641f22ef01cSRoman Divacky     // branch.
642f22ef01cSRoman Divacky     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
643f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
644f22ef01cSRoman Divacky     break;
645f22ef01cSRoman Divacky   case 2:
646f22ef01cSRoman Divacky     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
647f22ef01cSRoman Divacky                        call, TheSwitch);
648f22ef01cSRoman Divacky     TheSwitch->eraseFromParent();
649f22ef01cSRoman Divacky     break;
650f22ef01cSRoman Divacky   default:
651f22ef01cSRoman Divacky     // Otherwise, make the default destination of the switch instruction be one
652f22ef01cSRoman Divacky     // of the other successors.
653dff0c46cSDimitry Andric     TheSwitch->setCondition(call);
654dff0c46cSDimitry Andric     TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
655dff0c46cSDimitry Andric     // Remove redundant case
656f785676fSDimitry Andric     TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
657f22ef01cSRoman Divacky     break;
658f22ef01cSRoman Divacky   }
659f22ef01cSRoman Divacky }
660f22ef01cSRoman Divacky 
661f22ef01cSRoman Divacky void CodeExtractor::moveCodeToFunction(Function *newFunction) {
6627ae0e2c9SDimitry Andric   Function *oldFunc = (*Blocks.begin())->getParent();
663f22ef01cSRoman Divacky   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
664f22ef01cSRoman Divacky   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
665f22ef01cSRoman Divacky 
6663ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks) {
667f22ef01cSRoman Divacky     // Delete the basic block from the old function, and the list of blocks
6683ca95b02SDimitry Andric     oldBlocks.remove(Block);
669f22ef01cSRoman Divacky 
670f22ef01cSRoman Divacky     // Insert this basic block into the new function
6713ca95b02SDimitry Andric     newBlocks.push_back(Block);
672f22ef01cSRoman Divacky   }
673f22ef01cSRoman Divacky }
674f22ef01cSRoman Divacky 
6757ae0e2c9SDimitry Andric Function *CodeExtractor::extractCodeRegion() {
6767ae0e2c9SDimitry Andric   if (!isEligible())
67791bc56edSDimitry Andric     return nullptr;
678f22ef01cSRoman Divacky 
6797ae0e2c9SDimitry Andric   ValueSet inputs, outputs;
680f22ef01cSRoman Divacky 
681f22ef01cSRoman Divacky   // Assumption: this is a single-entry code region, and the header is the first
682f22ef01cSRoman Divacky   // block in the region.
6837ae0e2c9SDimitry Andric   BasicBlock *header = *Blocks.begin();
684f22ef01cSRoman Divacky 
685f22ef01cSRoman Divacky   // If we have to split PHI nodes or the entry block, do so now.
686f22ef01cSRoman Divacky   severSplitPHINodes(header);
687f22ef01cSRoman Divacky 
688f22ef01cSRoman Divacky   // If we have any return instructions in the region, split those blocks so
689f22ef01cSRoman Divacky   // that the return is not in the region.
690f22ef01cSRoman Divacky   splitReturnBlocks();
691f22ef01cSRoman Divacky 
692f22ef01cSRoman Divacky   Function *oldFunction = header->getParent();
693f22ef01cSRoman Divacky 
694f22ef01cSRoman Divacky   // This takes place of the original loop
695f22ef01cSRoman Divacky   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
696f22ef01cSRoman Divacky                                                 "codeRepl", oldFunction,
697f22ef01cSRoman Divacky                                                 header);
698f22ef01cSRoman Divacky 
699f22ef01cSRoman Divacky   // The new function needs a root node because other nodes can branch to the
700f22ef01cSRoman Divacky   // head of the region, but the entry node of a function cannot have preds.
701f22ef01cSRoman Divacky   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
702f22ef01cSRoman Divacky                                                "newFuncRoot");
703f22ef01cSRoman Divacky   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
704f22ef01cSRoman Divacky 
705f22ef01cSRoman Divacky   // Find inputs to, outputs from the code region.
706f22ef01cSRoman Divacky   findInputsOutputs(inputs, outputs);
707f22ef01cSRoman Divacky 
7087ae0e2c9SDimitry Andric   SmallPtrSet<BasicBlock *, 1> ExitBlocks;
7093ca95b02SDimitry Andric   for (BasicBlock *Block : Blocks)
7103ca95b02SDimitry Andric     for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
7113ca95b02SDimitry Andric          ++SI)
7127ae0e2c9SDimitry Andric       if (!Blocks.count(*SI))
7137ae0e2c9SDimitry Andric         ExitBlocks.insert(*SI);
7147ae0e2c9SDimitry Andric   NumExitBlocks = ExitBlocks.size();
7157ae0e2c9SDimitry Andric 
716f22ef01cSRoman Divacky   // Construct new function based on inputs/outputs & add allocas for all defs.
717f22ef01cSRoman Divacky   Function *newFunction = constructFunction(inputs, outputs, header,
718f22ef01cSRoman Divacky                                             newFuncRoot,
719f22ef01cSRoman Divacky                                             codeReplacer, oldFunction,
720f22ef01cSRoman Divacky                                             oldFunction->getParent());
721f22ef01cSRoman Divacky 
722f22ef01cSRoman Divacky   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
723f22ef01cSRoman Divacky 
724f22ef01cSRoman Divacky   moveCodeToFunction(newFunction);
725f22ef01cSRoman Divacky 
726f22ef01cSRoman Divacky   // Loop over all of the PHI nodes in the header block, and change any
727f22ef01cSRoman Divacky   // references to the old incoming edge to be the new incoming edge.
728f22ef01cSRoman Divacky   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
729f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(I);
730f22ef01cSRoman Divacky     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7317ae0e2c9SDimitry Andric       if (!Blocks.count(PN->getIncomingBlock(i)))
732f22ef01cSRoman Divacky         PN->setIncomingBlock(i, newFuncRoot);
733f22ef01cSRoman Divacky   }
734f22ef01cSRoman Divacky 
735f22ef01cSRoman Divacky   // Look at all successors of the codeReplacer block.  If any of these blocks
736f22ef01cSRoman Divacky   // had PHI nodes in them, we need to update the "from" block to be the code
737f22ef01cSRoman Divacky   // replacer, not the original block in the extracted region.
738f22ef01cSRoman Divacky   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
739f22ef01cSRoman Divacky                                  succ_end(codeReplacer));
740f22ef01cSRoman Divacky   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
741f22ef01cSRoman Divacky     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
742f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(I);
743f22ef01cSRoman Divacky       std::set<BasicBlock*> ProcessedPreds;
744f22ef01cSRoman Divacky       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7457ae0e2c9SDimitry Andric         if (Blocks.count(PN->getIncomingBlock(i))) {
746f22ef01cSRoman Divacky           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
747f22ef01cSRoman Divacky             PN->setIncomingBlock(i, codeReplacer);
748f22ef01cSRoman Divacky           else {
749f22ef01cSRoman Divacky             // There were multiple entries in the PHI for this block, now there
750f22ef01cSRoman Divacky             // is only one, so remove the duplicated entries.
751f22ef01cSRoman Divacky             PN->removeIncomingValue(i, false);
752f22ef01cSRoman Divacky             --i; --e;
753f22ef01cSRoman Divacky           }
754f22ef01cSRoman Divacky         }
755f22ef01cSRoman Divacky     }
756f22ef01cSRoman Divacky 
757f22ef01cSRoman Divacky   //cerr << "NEW FUNCTION: " << *newFunction;
758f22ef01cSRoman Divacky   //  verifyFunction(*newFunction);
759f22ef01cSRoman Divacky 
760f22ef01cSRoman Divacky   //  cerr << "OLD FUNCTION: " << *oldFunction;
761f22ef01cSRoman Divacky   //  verifyFunction(*oldFunction);
762f22ef01cSRoman Divacky 
763f22ef01cSRoman Divacky   DEBUG(if (verifyFunction(*newFunction))
764f22ef01cSRoman Divacky         report_fatal_error("verifyFunction failed!"));
765f22ef01cSRoman Divacky   return newFunction;
766f22ef01cSRoman Divacky }
767