blob: 50eb8a27e07afdf555c4aa6dbfa2c0fe4ef7e70f [file] [log] [blame]
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00008//===----------------------------------------------------------------------===//
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
Chandler Carruth0fde0012012-05-04 10:18:49 +000016#include "llvm/Transforms/Utils/CodeExtractor.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Chris Lattner3b2917b2004-05-12 06:01:40 +000020#include "llvm/Intrinsics.h"
Owen Andersone70b6372009-07-05 22:41:43 +000021#include "llvm/LLVMContext.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000022#include "llvm/Module.h"
23#include "llvm/Pass.h"
Chris Lattner37de2572004-03-18 03:49:40 +000024#include "llvm/Analysis/Dominators.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000025#include "llvm/Analysis/LoopInfo.h"
Chris Lattner36844692004-03-14 03:17:22 +000026#include "llvm/Analysis/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000031#include "llvm/Support/raw_ostream.h"
Julien Lerougef50a3f12010-01-09 01:06:49 +000032#include "llvm/ADT/SetVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000034#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000035#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000036using namespace llvm;
37
Misha Brukman3596f0a2004-04-23 23:54:17 +000038// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000039// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000040// extracted functions to pthread-based code, as only one argument (void*) can
41// be passed in to pthread_create().
42static cl::opt<bool>
43AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
44 cl::desc("Aggregate arguments to code-extracted functions"));
45
Chandler Carruth0fde0012012-05-04 10:18:49 +000046/// \brief Test whether a block is valid for extraction.
47static bool isBlockValidForExtraction(const BasicBlock &BB) {
48 // Landing pads must be in the function where they were inserted for cleanup.
49 if (BB.isLandingPad())
50 return false;
Chris Lattner37de2572004-03-18 03:49:40 +000051
Chandler Carruth0fde0012012-05-04 10:18:49 +000052 // Don't hoist code containing allocas, invokes, or vastarts.
53 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
54 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
Chris Lattner3b2917b2004-05-12 06:01:40 +000055 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +000056 if (const CallInst *CI = dyn_cast<CallInst>(I))
57 if (const Function *F = CI->getCalledFunction())
58 if (F->getIntrinsicID() == Intrinsic::vastart)
59 return false;
60 }
61
62 return true;
63}
64
65/// \brief Build a set of blocks to extract if the input blocks are viable.
66static SetVector<BasicBlock *>
67buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
68 SetVector<BasicBlock *> Result;
69
70 // Loop over the blocks, adding them to our set-vector, and aborting with an
71 // empty set if we encounter invalid blocks.
72 for (ArrayRef<BasicBlock *>::iterator I = BBs.begin(), E = BBs.end();
73 I != E; ++I) {
74 if (!Result.insert(*I))
75 continue;
76
77 if (!isBlockValidForExtraction(**I)) {
78 Result.clear();
79 break;
Chris Lattner3b2917b2004-05-12 06:01:40 +000080 }
Chandler Carruth0fde0012012-05-04 10:18:49 +000081 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000082
Chandler Carruth0fde0012012-05-04 10:18:49 +000083 return Result;
84}
Chris Lattner3b2917b2004-05-12 06:01:40 +000085
Chandler Carruth0fde0012012-05-04 10:18:49 +000086CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
87 : DT(0), AggregateArgs(AggregateArgs||AggregateArgsOpt),
88 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000089
Chandler Carruth0fde0012012-05-04 10:18:49 +000090CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
91 bool AggregateArgs)
92 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
93 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000094
Chandler Carruth0fde0012012-05-04 10:18:49 +000095CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
96 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
97 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000098
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000099
Chandler Carruth0fde0012012-05-04 10:18:49 +0000100/// definedInRegion - Return true if the specified value is defined in the
101/// extracted region.
102static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
103 if (Instruction *I = dyn_cast<Instruction>(V))
104 if (Blocks.count(I->getParent()))
105 return true;
106 return false;
107}
108
109/// definedInCaller - Return true if the specified value is defined in the
110/// function being code extracted, but not in the region being extracted.
111/// These values must be passed in as live-ins to the function.
112static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
113 if (isa<Argument>(V)) return true;
114 if (Instruction *I = dyn_cast<Instruction>(V))
115 if (!Blocks.count(I->getParent()))
116 return true;
117 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000118}
119
Chris Lattner3b2917b2004-05-12 06:01:40 +0000120/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
121/// region, we need to split the entry block of the region so that the PHI node
122/// is easier to deal with.
123void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000124 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000125 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000126
Dan Gohmandcb291f2007-03-22 16:38:57 +0000127 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000128 PHINode *PN = dyn_cast<PHINode>(Header->begin());
129 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000130
Chris Lattner795c9932004-05-12 15:29:13 +0000131 // If the header node contains any PHI nodes, check to see if there is more
132 // than one entry from outside the region. If so, we need to sever the
133 // header block into two.
134 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000135 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000136 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000137 else
138 ++NumPredsOutsideRegion;
139
140 // If there is one (or fewer) predecessor from outside the region, we don't
141 // need to do anything special.
142 if (NumPredsOutsideRegion <= 1) return;
143 }
144
145 // Otherwise, we need to split the header block into two pieces: one
146 // containing PHI nodes merging values from outside of the region, and a
147 // second that contains all of the code for the block and merges back any
148 // incoming values from inside of the region.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000149 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
Chris Lattner795c9932004-05-12 15:29:13 +0000150 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
151 Header->getName()+".ce");
152
153 // We only want to code extract the second block now, and it becomes the new
154 // header of the region.
155 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000156 Blocks.remove(OldPred);
157 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000158 Header = NewBB;
159
160 // Okay, update dominator sets. The blocks that dominate the new one are the
161 // blocks that dominate TIBB plus the new block itself.
Devang Pateld5258a232007-06-21 17:23:45 +0000162 if (DT)
163 DT->splitBlock(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000164
165 // Okay, now we need to adjust the PHI nodes and any branches from within the
166 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000167 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000168 PHINode *PN = cast<PHINode>(OldPred->begin());
169 // Loop over all of the predecessors of OldPred that are in the region,
170 // changing them to branch to NewBB instead.
171 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000172 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000173 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
174 TI->replaceUsesOfWith(OldPred, NewBB);
175 }
176
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000177 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000178 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Reid Spencer66149462004-09-15 17:06:42 +0000179 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
180 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000181 // Create a new PHI node in the new region, which has an incoming value
182 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000183 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
184 PN->getName()+".ce", NewBB->begin());
Chris Lattner795c9932004-05-12 15:29:13 +0000185 NewPN->addIncoming(PN, OldPred);
186
187 // Loop over all of the incoming value in PN, moving them to NewPN if they
188 // are from the extracted region.
189 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000190 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000191 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
192 PN->removeIncomingValue(i);
193 --i;
194 }
195 }
196 }
197 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000198}
Chris Lattner795c9932004-05-12 15:29:13 +0000199
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000200void CodeExtractor::splitReturnBlocks() {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000201 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
202 I != E; ++I)
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000203 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
204 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
205 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000206 // Old dominates New. New node dominates all other nodes dominated
207 // by Old.
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000208 DomTreeNode *OldNode = DT->getNode(*I);
Owen Andersonf18cae42009-08-25 17:35:37 +0000209 SmallVector<DomTreeNode*, 8> Children;
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000210 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
211 DI != DE; ++DI)
212 Children.push_back(*DI);
213
214 DomTreeNode *NewNode = DT->addNewBlock(New, *I);
215
Owen Andersonf18cae42009-08-25 17:35:37 +0000216 for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(),
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000217 E = Children.end(); I != E; ++I)
218 DT->changeImmediateDominator(*I, NewNode);
219 }
220 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000221}
222
223// findInputsOutputs - Find inputs to, outputs from the code region.
224//
Chandler Carruth0fde0012012-05-04 10:18:49 +0000225void CodeExtractor::findInputsOutputs(ValueSet &inputs, ValueSet &outputs) {
Chris Lattnerffc49262004-05-12 04:14:24 +0000226 std::set<BasicBlock*> ExitBlocks;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000227 for (SetVector<BasicBlock*>::const_iterator ci = Blocks.begin(),
228 ce = Blocks.end(); ci != ce; ++ci) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000229 BasicBlock *BB = *ci;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000230
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000231 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
232 // If a used value is defined outside the region, it's an input. If an
233 // instruction is used outside the region, it's an output.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000234 for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000235 if (definedInCaller(Blocks, *O))
Julien Lerouge321098e2010-01-10 01:07:22 +0000236 inputs.insert(*O);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000237
Chris Lattner3b2917b2004-05-12 06:01:40 +0000238 // Consider uses of this instruction (outputs).
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000239 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
240 UI != E; ++UI)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000241 if (!definedInRegion(Blocks, *UI)) {
Julien Lerouge321098e2010-01-10 01:07:22 +0000242 outputs.insert(I);
Chris Lattner37de2572004-03-18 03:49:40 +0000243 break;
244 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000245 } // for: insts
Chris Lattnerffc49262004-05-12 04:14:24 +0000246
Chris Lattner3b2917b2004-05-12 06:01:40 +0000247 // Keep track of the exit blocks from the region.
Chris Lattnerffc49262004-05-12 04:14:24 +0000248 TerminatorInst *TI = BB->getTerminator();
249 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000250 if (!Blocks.count(TI->getSuccessor(i)))
Chris Lattnerffc49262004-05-12 04:14:24 +0000251 ExitBlocks.insert(TI->getSuccessor(i));
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000252 } // for: basic blocks
Chris Lattnerffc49262004-05-12 04:14:24 +0000253
254 NumExitBlocks = ExitBlocks.size();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000255}
256
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000257/// constructFunction - make a function based on inputs and outputs, as follows:
258/// f(in0, ..., inN, out0, ..., outN)
259///
Chandler Carruth0fde0012012-05-04 10:18:49 +0000260Function *CodeExtractor::constructFunction(const ValueSet &inputs,
261 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000262 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000263 BasicBlock *newRootNode,
264 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000265 Function *oldFunction,
266 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000267 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
268 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000269
270 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000271 switch (NumExitBlocks) {
272 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000273 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
274 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
275 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000276 }
277
Jay Foadb804a2b2011-07-12 14:06:48 +0000278 std::vector<Type*> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000279
280 // Add the types of the input values to the function's argument list
Chandler Carruth0fde0012012-05-04 10:18:49 +0000281 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
282 i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000283 const Value *value = *i;
David Greene0ad6dce2010-01-05 01:26:44 +0000284 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000285 paramTy.push_back(value->getType());
286 }
287
Chris Lattner37de2572004-03-18 03:49:40 +0000288 // Add the types of the output values to the function's argument list.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000289 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
Chris Lattner37de2572004-03-18 03:49:40 +0000290 I != E; ++I) {
David Greene0ad6dce2010-01-05 01:26:44 +0000291 DEBUG(dbgs() << "instr used in func: " << **I << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000292 if (AggregateArgs)
293 paramTy.push_back((*I)->getType());
294 else
Owen Anderson4056ca92009-07-29 22:17:13 +0000295 paramTy.push_back(PointerType::getUnqual((*I)->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000296 }
297
David Greene0ad6dce2010-01-05 01:26:44 +0000298 DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
Jay Foadb804a2b2011-07-12 14:06:48 +0000299 for (std::vector<Type*>::iterator i = paramTy.begin(),
Bill Wendling4ae40102006-11-26 10:17:54 +0000300 e = paramTy.end(); i != e; ++i)
David Greene0ad6dce2010-01-05 01:26:44 +0000301 DEBUG(dbgs() << **i << ", ");
302 DEBUG(dbgs() << ")\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000303
Misha Brukman3596f0a2004-04-23 23:54:17 +0000304 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000305 PointerType *StructPtr =
Owen Anderson03cb69f2009-08-05 23:16:16 +0000306 PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000307 paramTy.clear();
308 paramTy.push_back(StructPtr);
309 }
Chris Lattner229907c2011-07-18 04:54:35 +0000310 FunctionType *funcType =
Owen Anderson4056ca92009-07-29 22:17:13 +0000311 FunctionType::get(RetTy, paramTy, false);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000312
313 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000314 Function *newFunction = Function::Create(funcType,
315 GlobalValue::InternalLinkage,
316 oldFunction->getName() + "_" +
317 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000318 // If the old function is no-throw, so is the new one.
319 if (oldFunction->doesNotThrow())
320 newFunction->setDoesNotThrow(true);
321
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000322 newFunction->getBasicBlockList().push_back(newRootNode);
323
Chris Lattner37de2572004-03-18 03:49:40 +0000324 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000325 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000326
327 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000328 // arguments (or appropriate addressing into struct) instead.
329 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
330 Value *RewriteVal;
331 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000332 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000333 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
334 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000335 TerminatorInst *TI = newFunction->begin()->getTerminator();
Daniel Dunbar123686852009-07-24 08:24:36 +0000336 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000337 GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000338 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000339 } else
340 RewriteVal = AI++;
341
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000342 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
343 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000344 use != useE; ++use)
345 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000346 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000347 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000348 }
349
Misha Brukman3596f0a2004-04-23 23:54:17 +0000350 // Set names for input and output arguments.
351 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000352 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000353 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000354 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000355 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000356 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000357 }
Chris Lattner37de2572004-03-18 03:49:40 +0000358
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000359 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
360 // within the new function. This must be done before we lose track of which
361 // blocks were originally in the code region.
362 std::vector<User*> Users(header->use_begin(), header->use_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000363 for (unsigned i = 0, e = Users.size(); i != e; ++i)
364 // The BasicBlock which contains the branch is not in the region
365 // modify the branch target to a new block
366 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000367 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000368 TI->getParent()->getParent() == oldFunction)
369 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000370
371 return newFunction;
372}
373
Owen Anderson4e9ac2a2009-08-25 17:42:07 +0000374/// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
375/// that uses the value within the basic block, and return the predecessor
376/// block associated with that use, or return 0 if none is found.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000377static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
378 for (Value::use_iterator UI = Used->use_begin(),
379 UE = Used->use_end(); UI != UE; ++UI) {
380 PHINode *P = dyn_cast<PHINode>(*UI);
381 if (P && P->getParent() == BB)
382 return P->getIncomingBlock(UI);
383 }
384
385 return 0;
386}
387
Chris Lattner3b2917b2004-05-12 06:01:40 +0000388/// emitCallAndSwitchStatement - This method sets up the caller side by adding
389/// the call instruction, splitting any PHI nodes in the header block as
390/// necessary.
391void CodeExtractor::
392emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000393 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000394 // Emit a call to the new function, passing in: *pointer to struct (if
395 // aggregating parameters), or plan inputs and allocated memory for outputs
Owen Anderson34e61482009-08-25 00:54:39 +0000396 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
Owen Anderson55f1c092009-08-13 21:58:54 +0000397
398 LLVMContext &Context = newFunction->getContext();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000399
Misha Brukman3596f0a2004-04-23 23:54:17 +0000400 // Add inputs as params, or to be filled into the struct
Chandler Carruth0fde0012012-05-04 10:18:49 +0000401 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000402 if (AggregateArgs)
403 StructValues.push_back(*i);
404 else
405 params.push_back(*i);
406
407 // Create allocas for the outputs
Chandler Carruth0fde0012012-05-04 10:18:49 +0000408 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000409 if (AggregateArgs) {
410 StructValues.push_back(*i);
411 } else {
412 AllocaInst *alloca =
Owen Anderson4fdeba92009-07-15 23:53:25 +0000413 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
Misha Brukman3596f0a2004-04-23 23:54:17 +0000414 codeReplacer->getParent()->begin()->begin());
415 ReloadOutputs.push_back(alloca);
416 params.push_back(alloca);
417 }
418 }
419
420 AllocaInst *Struct = 0;
421 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000422 std::vector<Type*> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000423 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000424 ve = StructValues.end(); v != ve; ++v)
425 ArgTypes.push_back((*v)->getType());
426
427 // Allocate a struct at the beginning of this function
Owen Anderson03cb69f2009-08-05 23:16:16 +0000428 Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000429 Struct =
Owen Anderson4fdeba92009-07-15 23:53:25 +0000430 new AllocaInst(StructArgTy, 0, "structArg",
Chris Lattner37de2572004-03-18 03:49:40 +0000431 codeReplacer->getParent()->begin()->begin());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000432 params.push_back(Struct);
433
434 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000435 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000436 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
437 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000438 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000439 GetElementPtrInst::Create(Struct, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000440 "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000441 codeReplacer->getInstList().push_back(GEP);
442 StoreInst *SI = new StoreInst(StructValues[i], GEP);
443 codeReplacer->getInstList().push_back(SI);
444 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000445 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000446
447 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000448 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000449 NumExitBlocks > 1 ? "targetBlock" : "");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000450 codeReplacer->getInstList().push_back(call);
451
Chris Lattner531f9e92005-03-15 04:54:21 +0000452 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000453 unsigned FirstOut = inputs.size();
454 if (!AggregateArgs)
455 std::advance(OutputArgBegin, inputs.size());
456
457 // Reload the outputs passed in by reference
458 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
459 Value *Output = 0;
460 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000461 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000462 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
463 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464 GetElementPtrInst *GEP
Jay Foadd1b78492011-07-25 09:48:08 +0000465 = GetElementPtrInst::Create(Struct, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000466 "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000467 codeReplacer->getInstList().push_back(GEP);
468 Output = GEP;
469 } else {
470 Output = ReloadOutputs[i];
471 }
472 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000473 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000474 codeReplacer->getInstList().push_back(load);
475 std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
476 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
477 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000478 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000479 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000480 }
481 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000482
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000483 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000484 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000485 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000486 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000487
488 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000489 // function return an unsigned, switch on that number. This loop iterates
490 // over all of the blocks in the extracted region, updating any terminator
491 // instructions in the to-be-extracted region that branch to blocks that are
492 // not in the region to be extracted.
493 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
494
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000495 unsigned switchVal = 0;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000496 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
497 e = Blocks.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000498 TerminatorInst *TI = (*i)->getTerminator();
499 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000500 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000501 BasicBlock *OldTarget = TI->getSuccessor(i);
502 // add a new basic block which returns the appropriate value
503 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
504 if (!NewTarget) {
505 // If we don't already have an exit stub for this non-extracted
506 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000507 NewTarget = BasicBlock::Create(Context,
508 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000509 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000510 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000511
Chris Lattnerffc49262004-05-12 04:14:24 +0000512 Value *brVal = 0;
513 switch (NumExitBlocks) {
514 case 0:
515 case 1: break; // No value needed.
516 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000517 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000518 break;
519 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000520 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000521 break;
522 }
523
Owen Anderson55f1c092009-08-13 21:58:54 +0000524 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000525
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000526 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000527 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
528 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000529 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000530
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000531 // Restore values just before we exit
Chris Lattner531f9e92005-03-15 04:54:21 +0000532 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000533 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
534 // For an invoke, the normal destination is the only one that is
535 // dominated by the result of the invocation
536 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
Chris Lattner9b0291b2004-11-13 00:06:45 +0000537
538 bool DominatesDef = true;
539
Chris Lattner5bcca602004-11-12 23:50:44 +0000540 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000541 DefBlock = Invoke->getNormalDest();
Chris Lattner5bcca602004-11-12 23:50:44 +0000542
543 // Make sure we are looking at the original successor block, not
544 // at a newly inserted exit block, which won't be in the dominator
545 // info.
546 for (std::map<BasicBlock*, BasicBlock*>::iterator I =
547 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
548 if (DefBlock == I->second) {
549 DefBlock = I->first;
550 break;
551 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000552
553 // In the extract block case, if the block we are extracting ends
554 // with an invoke instruction, make sure that we don't emit a
555 // store of the invoke value for the unwind block.
Devang Patelcf470e52007-06-07 22:17:16 +0000556 if (!DT && DefBlock != OldTarget)
Chris Lattner9b0291b2004-11-13 00:06:45 +0000557 DominatesDef = false;
Chris Lattner5bcca602004-11-12 23:50:44 +0000558 }
559
Owen Anderson34e61482009-08-25 00:54:39 +0000560 if (DT) {
Devang Patelcf470e52007-06-07 22:17:16 +0000561 DominatesDef = DT->dominates(DefBlock, OldTarget);
Owen Anderson34e61482009-08-25 00:54:39 +0000562
563 // If the output value is used by a phi in the target block,
564 // then we need to test for dominance of the phi's predecessor
565 // instead. Unfortunately, this a little complicated since we
566 // have already rewritten uses of the value to uses of the reload.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000567 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
568 OldTarget);
569 if (pred && DT && DT->dominates(DefBlock, pred))
570 DominatesDef = true;
Owen Anderson34e61482009-08-25 00:54:39 +0000571 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000572
573 if (DominatesDef) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000574 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000575 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000576 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
577 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
578 FirstOut+out);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000579 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000580 GetElementPtrInst::Create(OAI, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000581 "gep_" + outputs[out]->getName(),
582 NTRet);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000583 new StoreInst(outputs[out], GEP, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000584 } else {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000585 new StoreInst(outputs[out], OAI, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000586 }
587 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000588 // Advance output iterator even if we don't emit a store
589 if (!AggregateArgs) ++OAI;
590 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000591 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000592
593 // rewrite the original branch instruction with this new target
594 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000595 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000596 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000597
Chris Lattner3d1ca672004-05-12 03:22:33 +0000598 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000599 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000600 switch (NumExitBlocks) {
601 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000602 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000603 // means that previously this was the last part of the function, and hence
604 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000605
Misha Brukman3596f0a2004-04-23 23:54:17 +0000606 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000607 if (OldFnRetTy->isVoidTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000608 ReturnInst::Create(Context, 0, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000609 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000610 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000611 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000612 } else {
613 // Otherwise we must have code extracted an unwind or something, just
614 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000615 ReturnInst::Create(Context,
616 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000617 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000618
Dan Gohman158ff2c2008-06-21 22:08:46 +0000619 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000620 break;
621 case 1:
622 // Only a single destination, change the switch into an unconditional
623 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000624 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000625 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000626 break;
627 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000628 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
629 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000630 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000631 break;
632 default:
633 // Otherwise, make the default destination of the switch instruction be one
634 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000635 TheSwitch->setCondition(call);
636 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000637 // Remove redundant case
638 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000639 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000640 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000641}
642
Chris Lattner3b2917b2004-05-12 06:01:40 +0000643void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000644 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000645 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
646 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
647
Chandler Carruth0fde0012012-05-04 10:18:49 +0000648 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
649 e = Blocks.end(); i != e; ++i) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000650 // Delete the basic block from the old function, and the list of blocks
651 oldBlocks.remove(*i);
652
653 // Insert this basic block into the new function
654 newBlocks.push_back(*i);
655 }
656}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000657
Chandler Carruth0fde0012012-05-04 10:18:49 +0000658Function *CodeExtractor::extractCodeRegion() {
659 if (!isEligible())
Misha Brukman3596f0a2004-04-23 23:54:17 +0000660 return 0;
661
Chandler Carruth0fde0012012-05-04 10:18:49 +0000662 ValueSet inputs, outputs;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000663
664 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000665 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000666 BasicBlock *header = *Blocks.begin();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000667
Chandler Carruth0fde0012012-05-04 10:18:49 +0000668 for (SetVector<BasicBlock *>::iterator BI = llvm::next(Blocks.begin()),
669 BE = Blocks.end();
670 BI != BE; ++BI)
671 for (pred_iterator PI = pred_begin(*BI), E = pred_end(*BI);
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000672 PI != E; ++PI)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000673 assert(Blocks.count(*PI) &&
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000674 "No blocks in this region may have entries from outside the region"
675 " except for the first block!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000676
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000677 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +0000678 severSplitPHINodes(header);
679
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000680 // If we have any return instructions in the region, split those blocks so
681 // that the return is not in the region.
682 splitReturnBlocks();
683
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000684 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000685
686 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +0000687 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
688 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +0000689 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000690
691 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +0000692 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +0000693 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
694 "newFuncRoot");
Gabor Greife9ecc682008-04-06 20:25:17 +0000695 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000696
Chris Lattner3b2917b2004-05-12 06:01:40 +0000697 // Find inputs to, outputs from the code region.
698 findInputsOutputs(inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000699
Chris Lattner3b2917b2004-05-12 06:01:40 +0000700 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +0000701 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +0000702 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000703 codeReplacer, oldFunction,
704 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000705
Chris Lattner9c431f62004-03-14 22:34:55 +0000706 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000707
Chris Lattner9c431f62004-03-14 22:34:55 +0000708 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000709
Chris Lattner795c9932004-05-12 15:29:13 +0000710 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +0000711 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +0000712 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
713 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +0000714 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000715 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +0000716 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +0000717 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000718
Chris Lattneracd75982004-03-18 05:38:31 +0000719 // Look at all successors of the codeReplacer block. If any of these blocks
720 // had PHI nodes in them, we need to update the "from" block to be the code
721 // replacer, not the original block in the extracted region.
722 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
723 succ_end(codeReplacer));
724 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Reid Spencer66149462004-09-15 17:06:42 +0000725 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
726 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +0000727 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +0000728 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000729 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +0000730 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
731 PN->setIncomingBlock(i, codeReplacer);
732 else {
733 // There were multiple entries in the PHI for this block, now there
734 // is only one, so remove the duplicated entries.
735 PN->removeIncomingValue(i, false);
736 --i; --e;
737 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000738 }
Chris Lattner56273822004-08-13 03:27:07 +0000739 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000740
Bill Wendlingf3baad32006-12-07 01:30:32 +0000741 //cerr << "NEW FUNCTION: " << *newFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000742 // verifyFunction(*newFunction);
743
Bill Wendlingf3baad32006-12-07 01:30:32 +0000744 // cerr << "OLD FUNCTION: " << *oldFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000745 // verifyFunction(*oldFunction);
Chris Lattneracd75982004-03-18 05:38:31 +0000746
Torok Edwinccb29cd2009-07-11 13:10:19 +0000747 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +0000748 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000749 return newFunction;
750}