blob: e008fd763231951112602da593d56f25446360ff [file] [log] [blame]
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the interface to tear out a code region, such as an
11// individual loop or a parallel section, into a new function, replacing it with
12// a call to the new function.
13//
14//===----------------------------------------------------------------------===//
15
Chris Lattnercee34042004-03-18 03:15:29 +000016#include "llvm/Transforms/Utils/FunctionUtils.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Module.h"
21#include "llvm/Pass.h"
22#include "llvm/Analysis/LoopInfo.h"
Chris Lattner36844692004-03-14 03:17:22 +000023#include "llvm/Analysis/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000025#include "Support/Debug.h"
26#include "Support/StringExtras.h"
27#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000028#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000029using namespace llvm;
30
31namespace {
32
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000033 /// getFunctionArg - Return a pointer to F's ARGNOth argument.
34 ///
35 Argument *getFunctionArg(Function *F, unsigned argno) {
Chris Lattner5b2072e2004-03-14 23:43:24 +000036 Function::aiterator I = F->abegin();
37 std::advance(I, argno);
38 return I;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000039 }
40
41 struct CodeExtractor {
42 typedef std::vector<Value*> Values;
43 typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy;
44 typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy;
45 PhiVal2ArgTy PhiVal2Arg;
Chris Lattner9c431f62004-03-14 22:34:55 +000046 std::set<BasicBlock*> BlocksToExtract;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000047 public:
48 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
49
50 private:
Chris Lattner9c431f62004-03-14 22:34:55 +000051 void findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000052 BasicBlock *newHeader,
53 BasicBlock *newRootNode);
54
55 void processPhiNodeInputs(PHINode *Phi,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000056 Values &inputs,
57 BasicBlock *newHeader,
58 BasicBlock *newRootNode);
59
60 void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot);
61
62 Function *constructFunction(const Values &inputs,
63 const Values &outputs,
64 BasicBlock *newRootNode, BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000065 Function *oldFunction, Module *M);
66
Chris Lattner9c431f62004-03-14 22:34:55 +000067 void moveCodeToFunction(Function *newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000068
69 void emitCallAndSwitchStatement(Function *newFunction,
70 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000071 Values &inputs,
72 Values &outputs);
73
74 };
75}
76
77void CodeExtractor::processPhiNodeInputs(PHINode *Phi,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000078 Values &inputs,
79 BasicBlock *codeReplacer,
Chris Lattnerfb87cde2004-03-15 01:26:44 +000080 BasicBlock *newFuncRoot) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000081 // Separate incoming values and BasicBlocks as internal/external. We ignore
82 // the case where both the value and BasicBlock are internal, because we don't
83 // need to do a thing.
84 std::vector<unsigned> EValEBB;
85 std::vector<unsigned> EValIBB;
86 std::vector<unsigned> IValEBB;
87
88 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
89 Value *phiVal = Phi->getIncomingValue(i);
90 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) {
Chris Lattner9c431f62004-03-14 22:34:55 +000091 if (BlocksToExtract.count(Inst->getParent())) {
92 if (!BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000093 IValEBB.push_back(i);
94 } else {
Chris Lattner9c431f62004-03-14 22:34:55 +000095 if (BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000096 EValIBB.push_back(i);
97 else
98 EValEBB.push_back(i);
99 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000100 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) {
101 // arguments are external
Chris Lattner9c431f62004-03-14 22:34:55 +0000102 if (BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000103 EValIBB.push_back(i);
104 else
105 EValEBB.push_back(i);
106 } else {
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000107 // Globals/Constants are internal, but considered `external' if they are
108 // coming from an external block.
109 if (!BlocksToExtract.count(Phi->getIncomingBlock(i)))
110 EValEBB.push_back(i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000111 }
112 }
113
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000114 // Both value and block are external. Need to group all of these, have an
115 // external phi, pass the result as an argument, and have THIS phi use that
116 // result.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000117 if (EValEBB.size() > 0) {
118 if (EValEBB.size() == 1) {
119 // Now if it's coming from the newFuncRoot, it's that funky input
120 unsigned phiIdx = EValEBB[0];
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000121 if (!isa<Constant>(Phi->getIncomingValue(phiIdx))) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000122 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size()));
123 // We can just pass this value in as argument
124 inputs.push_back(Phi->getIncomingValue(phiIdx));
125 }
126 Phi->setIncomingBlock(phiIdx, newFuncRoot);
127 } else {
128 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi");
129 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi);
130 for (std::vector<unsigned>::iterator i = EValEBB.begin(),
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000131 e = EValEBB.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000132 externalPhi->addIncoming(Phi->getIncomingValue(*i),
133 Phi->getIncomingBlock(*i));
134
135 // We make these values invalid instead of deleting them because that
136 // would shift the indices of other values... The fixPhiNodes should
137 // clean these phi nodes up later.
138 Phi->setIncomingValue(*i, 0);
139 Phi->setIncomingBlock(*i, 0);
140 }
141 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(),
142 inputs.size()));
143 // We can just pass this value in as argument
144 inputs.push_back(externalPhi);
145 }
146 }
147
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000148 // When the value is external, but block internal... just pass it in as
149 // argument, no change to phi node
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000150 for (std::vector<unsigned>::iterator i = EValIBB.begin(),
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000151 e = EValIBB.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000152 // rewrite the phi input node to be an argument
153 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size()));
154 inputs.push_back(Phi->getIncomingValue(*i));
155 }
156
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000157 // Value internal, block external this can happen if we are extracting a part
158 // of a loop.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000159 for (std::vector<unsigned>::iterator i = IValEBB.begin(),
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000160 e = IValEBB.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000161 assert(0 && "Cannot (YET) handle internal values via external blocks");
162 }
163}
164
165
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000166void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000167 BasicBlock *newHeader,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000168 BasicBlock *newRootNode) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000169 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
170 ce = BlocksToExtract.end(); ci != ce; ++ci) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000171 BasicBlock *BB = *ci;
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000172 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
173 // If a used value is defined outside the region, it's an input. If an
174 // instruction is used outside the region, it's an output.
175 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
176 processPhiNodeInputs(Phi, inputs, newHeader, newRootNode);
177 } else {
178 // All other instructions go through the generic input finder
179 // Loop over the operands of each instruction (inputs)
180 for (User::op_iterator op = I->op_begin(), opE = I->op_end();
181 op != opE; ++op)
182 if (Instruction *opI = dyn_cast<Instruction>(*op)) {
183 // Check if definition of this operand is within the loop
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000184 if (!BlocksToExtract.count(opI->getParent()))
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000185 inputs.push_back(opI);
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000186 } else if (isa<Argument>(*op)) {
187 inputs.push_back(*op);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000188 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000189 }
190
191 // Consider uses of this instruction (outputs)
192 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
193 UI != E; ++UI)
194 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent()))
195 outputs.push_back(*UI);
196 } // for: insts
197 } // for: basic blocks
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000198}
199
200void CodeExtractor::rewritePhiNodes(Function *F,
201 BasicBlock *newFuncRoot) {
202 // Write any changes that were saved before: use function arguments as inputs
203 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000204 i != e; ++i) {
205 PHINode *phi = i->first;
206 PhiValChangesTy &values = i->second;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000207 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx)
208 {
209 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second;
210 if (phiValueIdx < phi->getNumIncomingValues())
211 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum));
212 else
213 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot);
214 }
215 }
216
217 // Delete any invalid Phi node inputs that were marked as NULL previously
218 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000219 i != e; ++i) {
220 PHINode *phi = i->first;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000221 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx)
222 {
223 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) {
224 phi->removeIncomingValue(idx);
225 --idx;
226 --end;
227 }
228 }
229 }
230
231 // We are done with the saved values
232 PhiVal2Arg.clear();
233}
234
235
236/// constructFunction - make a function based on inputs and outputs, as follows:
237/// f(in0, ..., inN, out0, ..., outN)
238///
239Function *CodeExtractor::constructFunction(const Values &inputs,
240 const Values &outputs,
241 BasicBlock *newRootNode,
242 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000243 Function *oldFunction, Module *M) {
244 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
245 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
Chris Lattner9c431f62004-03-14 22:34:55 +0000246 BasicBlock *header = *BlocksToExtract.begin();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000247
248 // This function returns unsigned, outputs will go back by reference.
249 Type *retTy = Type::UShortTy;
250 std::vector<const Type*> paramTy;
251
252 // Add the types of the input values to the function's argument list
253 for (Values::const_iterator i = inputs.begin(),
254 e = inputs.end(); i != e; ++i) {
255 const Value *value = *i;
256 DEBUG(std::cerr << "value used in func: " << value << "\n");
257 paramTy.push_back(value->getType());
258 }
259
260 // Add the types of the output values to the function's argument list, but
261 // make them pointer types for scalars
262 for (Values::const_iterator i = outputs.begin(),
263 e = outputs.end(); i != e; ++i) {
264 const Value *value = *i;
265 DEBUG(std::cerr << "instr used in func: " << value << "\n");
266 const Type *valueType = value->getType();
267 // Convert scalar types into a pointer of that type
268 if (valueType->isPrimitiveType()) {
269 valueType = PointerType::get(valueType);
270 }
271 paramTy.push_back(valueType);
272 }
273
274 DEBUG(std::cerr << "Function type: " << retTy << " f(");
275 for (std::vector<const Type*>::iterator i = paramTy.begin(),
276 e = paramTy.end(); i != e; ++i)
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000277 DEBUG(std::cerr << *i << ", ");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000278 DEBUG(std::cerr << ")\n");
279
280 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
281
282 // Create the new function
283 Function *newFunction = new Function(funcType,
284 GlobalValue::InternalLinkage,
285 oldFunction->getName() + "_code", M);
286 newFunction->getBasicBlockList().push_back(newRootNode);
287
288 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
289 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
290 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000291 use != useE; ++use)
292 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chris Lattner9c431f62004-03-14 22:34:55 +0000293 if (BlocksToExtract.count(inst->getParent()))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000294 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000295 }
296
297 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
298 // within the new function. This must be done before we lose track of which
299 // blocks were originally in the code region.
300 std::vector<User*> Users(header->use_begin(), header->use_end());
301 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end();
302 i != e; ++i) {
303 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) {
304 BasicBlock *BB = inst->getParent();
Chris Lattner9c431f62004-03-14 22:34:55 +0000305 if (!BlocksToExtract.count(BB) && BB->getParent() == oldFunction) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000306 // The BasicBlock which contains the branch is not in the region
307 // modify the branch target to a new block
308 inst->replaceUsesOfWith(header, newHeader);
309 }
310 }
311 }
312
313 return newFunction;
314}
315
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000316void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000317 Function *oldFunc = (*BlocksToExtract.begin())->getParent();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000318 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000319 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000320
Chris Lattner9c431f62004-03-14 22:34:55 +0000321 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
322 e = BlocksToExtract.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000323 // Delete the basic block from the old function, and the list of blocks
Chris Lattner9c431f62004-03-14 22:34:55 +0000324 oldBlocks.remove(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000325
326 // Insert this basic block into the new function
Chris Lattner9c431f62004-03-14 22:34:55 +0000327 newBlocks.push_back(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000328 }
329}
330
331void
332CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
333 BasicBlock *codeReplacer,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000334 Values &inputs,
335 Values &outputs)
336{
337 // Emit a call to the new function, passing allocated memory for outputs and
338 // just plain inputs for non-scalars
Chris Lattner5b2072e2004-03-14 23:43:24 +0000339 std::vector<Value*> params(inputs);
340
341 for (Values::const_iterator i = outputs.begin(), e = outputs.end(); i != e;
342 ++i) {
343 Value *Output = *i;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000344 // Create allocas for scalar outputs
Chris Lattner5b2072e2004-03-14 23:43:24 +0000345 if (Output->getType()->isPrimitiveType()) {
346 AllocaInst *alloca =
347 new AllocaInst((*i)->getType(), 0, Output->getName()+".loc",
348 codeReplacer->getParent()->begin()->begin());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000349 params.push_back(alloca);
350
Chris Lattner5b2072e2004-03-14 23:43:24 +0000351 LoadInst *load = new LoadInst(alloca, Output->getName()+".reload");
352 codeReplacer->getInstList().push_back(load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000353 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end());
354 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end();
355 use != useE; ++use) {
356 if (Instruction* inst = dyn_cast<Instruction>(*use)) {
Chris Lattner5b2072e2004-03-14 23:43:24 +0000357 if (!BlocksToExtract.count(inst->getParent()))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000358 inst->replaceUsesOfWith(*i, load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000359 }
360 }
361 } else {
362 params.push_back(*i);
363 }
364 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000365
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000366 CallInst *call = new CallInst(newFunction, params, "targetBlock");
Chris Lattner5b2072e2004-03-14 23:43:24 +0000367 codeReplacer->getInstList().push_front(call);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000368
369 // Now we can emit a switch statement using the call as a value.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000370 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000371
372 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000373 // function return an unsigned, switch on that number. This loop iterates
374 // over all of the blocks in the extracted region, updating any terminator
375 // instructions in the to-be-extracted region that branch to blocks that are
376 // not in the region to be extracted.
377 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
378
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000379 unsigned switchVal = 0;
Chris Lattner9c431f62004-03-14 22:34:55 +0000380 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
381 e = BlocksToExtract.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000382 TerminatorInst *TI = (*i)->getTerminator();
383 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
384 if (!BlocksToExtract.count(TI->getSuccessor(i))) {
385 BasicBlock *OldTarget = TI->getSuccessor(i);
386 // add a new basic block which returns the appropriate value
387 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
388 if (!NewTarget) {
389 // If we don't already have an exit stub for this non-extracted
390 // destination, create one now!
391 NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub",
392 newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000393
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000394 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++);
395 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000396
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000397 // Update the switch instruction.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000398 TheSwitch->addCase(brVal, OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000399
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000400 // Restore values just before we exit
401 // FIXME: Use a GetElementPtr to bunch the outputs in a struct
402 for (unsigned out = 0, e = outputs.size(); out != e; ++out)
403 new StoreInst(outputs[out], getFunctionArg(newFunction, out),NTRet);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000404 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000405
406 // rewrite the original branch instruction with this new target
407 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000408 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000409 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000410
411 // Now that we've done the deed, make the default destination of the switch
412 // instruction be one of the exit blocks of the region.
413 if (TheSwitch->getNumSuccessors() > 1) {
414 // FIXME: this is broken w.r.t. PHI nodes, but the old code was more broken.
415 // This edge is not traversable.
416 TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(1));
417 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000418}
419
420
421/// ExtractRegion - Removes a loop from a function, replaces it with a call to
422/// new function. Returns pointer to the new function.
423///
424/// algorithm:
425///
426/// find inputs and outputs for the region
427///
428/// for inputs: add to function as args, map input instr* to arg#
429/// for outputs: add allocas for scalars,
430/// add to func as args, map output instr* to arg#
431///
432/// rewrite func to use argument #s instead of instr*
433///
434/// for each scalar output in the function: at every exit, store intermediate
435/// computed result back into memory.
436///
437Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
438{
439 // 1) Find inputs, outputs
440 // 2) Construct new function
441 // * Add allocas for defs, pass as args by reference
442 // * Pass in uses as args
443 // 3) Move code region, add call instr to func
Chris Lattner9c431f62004-03-14 22:34:55 +0000444 //
445 BlocksToExtract.insert(code.begin(), code.end());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000446
447 Values inputs, outputs;
448
449 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000450 // block in the region.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000451 BasicBlock *header = code[0];
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000452 for (unsigned i = 1, e = code.size(); i != e; ++i)
453 for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
454 PI != E; ++PI)
455 assert(BlocksToExtract.count(*PI) &&
456 "No blocks in this region may have entries from outside the region"
457 " except for the first block!");
458
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000459 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000460
461 // This takes place of the original loop
462 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
463
464 // The new function needs a root node because other nodes can branch to the
465 // head of the loop, and the root cannot have predecessors
466 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
467 newFuncRoot->getInstList().push_back(new BranchInst(header));
468
469 // Find inputs to, outputs from the code region
470 //
471 // If one of the inputs is coming from a different basic block and it's in a
472 // phi node, we need to rewrite the phi node:
473 //
474 // * All the inputs which involve basic blocks OUTSIDE of this region go into
475 // a NEW phi node that takes care of finding which value really came in.
476 // The result of this phi is passed to the function as an argument.
477 //
478 // * All the other phi values stay.
479 //
480 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
481 // blocks moving to a new function.
482 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
483 // the values as parameters to the function
Chris Lattner9c431f62004-03-14 22:34:55 +0000484 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000485
486 // Step 2: Construct new function based on inputs/outputs,
487 // Add allocas for all defs
488 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000489 codeReplacer, oldFunction,
490 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000491
492 rewritePhiNodes(newFunction, newFuncRoot);
493
Chris Lattner9c431f62004-03-14 22:34:55 +0000494 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000495
Chris Lattner9c431f62004-03-14 22:34:55 +0000496 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000497
Chris Lattner36844692004-03-14 03:17:22 +0000498 DEBUG(if (verifyFunction(*newFunction)) abort());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000499 return newFunction;
500}
501
Misha Brukmanf44acae2004-03-02 00:20:57 +0000502/// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
503/// function
504///
505Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
Chris Lattner4fca71e2004-03-14 04:01:47 +0000506 return CodeExtractor().ExtractCodeRegion(code);
Misha Brukmanf44acae2004-03-02 00:20:57 +0000507}
508
Misha Brukman5af2be72004-03-01 18:28:34 +0000509/// ExtractBasicBlock - slurp a natural loop into a brand new function
510///
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000511Function* llvm::ExtractLoop(Loop *L) {
Chris Lattner4fca71e2004-03-14 04:01:47 +0000512 return CodeExtractor().ExtractCodeRegion(L->getBlocks());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000513}
514
Misha Brukman5af2be72004-03-01 18:28:34 +0000515/// ExtractBasicBlock - slurp a basic block into a brand new function
516///
517Function* llvm::ExtractBasicBlock(BasicBlock *BB) {
Misha Brukman5af2be72004-03-01 18:28:34 +0000518 std::vector<BasicBlock*> Blocks;
519 Blocks.push_back(BB);
Chris Lattner4fca71e2004-03-14 04:01:47 +0000520 return CodeExtractor().ExtractCodeRegion(Blocks);
Misha Brukman5af2be72004-03-01 18:28:34 +0000521}