blob: 182f85649a1e1039f46d6dc7601a2ea6e1b8d5d8 [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
16#include "llvm/BasicBlock.h"
17#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"
25#include "llvm/Transforms/Utils/FunctionUtils.h"
26#include "Support/Debug.h"
27#include "Support/StringExtras.h"
28#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000029#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000030using namespace llvm;
31
32namespace {
33
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000034 /// getFunctionArg - Return a pointer to F's ARGNOth argument.
35 ///
36 Argument *getFunctionArg(Function *F, unsigned argno) {
Chris Lattner5b2072e2004-03-14 23:43:24 +000037 Function::aiterator I = F->abegin();
38 std::advance(I, argno);
39 return I;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000040 }
41
42 struct CodeExtractor {
43 typedef std::vector<Value*> Values;
44 typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy;
45 typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy;
46 PhiVal2ArgTy PhiVal2Arg;
Chris Lattner9c431f62004-03-14 22:34:55 +000047 std::set<BasicBlock*> BlocksToExtract;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000048 public:
49 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
50
51 private:
Chris Lattner9c431f62004-03-14 22:34:55 +000052 void findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000053 BasicBlock *newHeader,
54 BasicBlock *newRootNode);
55
56 void processPhiNodeInputs(PHINode *Phi,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000057 Values &inputs,
58 BasicBlock *newHeader,
59 BasicBlock *newRootNode);
60
61 void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot);
62
63 Function *constructFunction(const Values &inputs,
64 const Values &outputs,
65 BasicBlock *newRootNode, BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000066 Function *oldFunction, Module *M);
67
Chris Lattner9c431f62004-03-14 22:34:55 +000068 void moveCodeToFunction(Function *newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000069
70 void emitCallAndSwitchStatement(Function *newFunction,
71 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000072 Values &inputs,
73 Values &outputs);
74
75 };
76}
77
78void CodeExtractor::processPhiNodeInputs(PHINode *Phi,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000079 Values &inputs,
80 BasicBlock *codeReplacer,
81 BasicBlock *newFuncRoot)
82{
83 // Separate incoming values and BasicBlocks as internal/external. We ignore
84 // the case where both the value and BasicBlock are internal, because we don't
85 // need to do a thing.
86 std::vector<unsigned> EValEBB;
87 std::vector<unsigned> EValIBB;
88 std::vector<unsigned> IValEBB;
89
90 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
91 Value *phiVal = Phi->getIncomingValue(i);
92 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) {
Chris Lattner9c431f62004-03-14 22:34:55 +000093 if (BlocksToExtract.count(Inst->getParent())) {
94 if (!BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000095 IValEBB.push_back(i);
96 } else {
Chris Lattner9c431f62004-03-14 22:34:55 +000097 if (BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000098 EValIBB.push_back(i);
99 else
100 EValEBB.push_back(i);
101 }
102 } else if (Constant *Const = dyn_cast<Constant>(phiVal)) {
103 // Constants are internal, but considered `external' if they are coming
104 // from an external block.
Chris Lattner9c431f62004-03-14 22:34:55 +0000105 if (!BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000106 EValEBB.push_back(i);
107 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) {
108 // arguments are external
Chris Lattner9c431f62004-03-14 22:34:55 +0000109 if (BlocksToExtract.count(Phi->getIncomingBlock(i)))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000110 EValIBB.push_back(i);
111 else
112 EValEBB.push_back(i);
113 } else {
114 phiVal->dump();
115 assert(0 && "Unhandled input in a Phi node");
116 }
117 }
118
119 // Both value and block are external. Need to group all of
120 // these, have an external phi, pass the result as an
121 // argument, and have THIS phi use that result.
122 if (EValEBB.size() > 0) {
123 if (EValEBB.size() == 1) {
124 // Now if it's coming from the newFuncRoot, it's that funky input
125 unsigned phiIdx = EValEBB[0];
126 if (!dyn_cast<Constant>(Phi->getIncomingValue(phiIdx)))
127 {
128 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size()));
129 // We can just pass this value in as argument
130 inputs.push_back(Phi->getIncomingValue(phiIdx));
131 }
132 Phi->setIncomingBlock(phiIdx, newFuncRoot);
133 } else {
134 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi");
135 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi);
136 for (std::vector<unsigned>::iterator i = EValEBB.begin(),
137 e = EValEBB.end(); i != e; ++i)
138 {
139 externalPhi->addIncoming(Phi->getIncomingValue(*i),
140 Phi->getIncomingBlock(*i));
141
142 // We make these values invalid instead of deleting them because that
143 // would shift the indices of other values... The fixPhiNodes should
144 // clean these phi nodes up later.
145 Phi->setIncomingValue(*i, 0);
146 Phi->setIncomingBlock(*i, 0);
147 }
148 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(),
149 inputs.size()));
150 // We can just pass this value in as argument
151 inputs.push_back(externalPhi);
152 }
153 }
154
155 // When the value is external, but block internal...
156 // just pass it in as argument, no change to phi node
157 for (std::vector<unsigned>::iterator i = EValIBB.begin(),
158 e = EValIBB.end(); i != e; ++i)
159 {
160 // rewrite the phi input node to be an argument
161 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size()));
162 inputs.push_back(Phi->getIncomingValue(*i));
163 }
164
165 // Value internal, block external
166 // this can happen if we are extracting a part of a loop
167 for (std::vector<unsigned>::iterator i = IValEBB.begin(),
168 e = IValEBB.end(); i != e; ++i)
169 {
170 assert(0 && "Cannot (YET) handle internal values via external blocks");
171 }
172}
173
174
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000175void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000176 BasicBlock *newHeader,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000177 BasicBlock *newRootNode) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000178 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
179 ce = BlocksToExtract.end(); ci != ce; ++ci) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000180 BasicBlock *BB = *ci;
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000181 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
182 // If a used value is defined outside the region, it's an input. If an
183 // instruction is used outside the region, it's an output.
184 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
185 processPhiNodeInputs(Phi, inputs, newHeader, newRootNode);
186 } else {
187 // All other instructions go through the generic input finder
188 // Loop over the operands of each instruction (inputs)
189 for (User::op_iterator op = I->op_begin(), opE = I->op_end();
190 op != opE; ++op)
191 if (Instruction *opI = dyn_cast<Instruction>(*op)) {
192 // Check if definition of this operand is within the loop
193 if (!BlocksToExtract.count(opI->getParent())) {
194 // add this operand to the inputs
195 inputs.push_back(opI);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000196 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000197 } else if (isa<Argument>(*op)) {
198 inputs.push_back(*op);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000199 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000200 }
201
202 // Consider uses of this instruction (outputs)
203 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
204 UI != E; ++UI)
205 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent()))
206 outputs.push_back(*UI);
207 } // for: insts
208 } // for: basic blocks
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000209}
210
211void CodeExtractor::rewritePhiNodes(Function *F,
212 BasicBlock *newFuncRoot) {
213 // Write any changes that were saved before: use function arguments as inputs
214 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
215 i != e; ++i)
216 {
217 PHINode *phi = (*i).first;
218 PhiValChangesTy &values = (*i).second;
219 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx)
220 {
221 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second;
222 if (phiValueIdx < phi->getNumIncomingValues())
223 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum));
224 else
225 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot);
226 }
227 }
228
229 // Delete any invalid Phi node inputs that were marked as NULL previously
230 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
231 i != e; ++i)
232 {
233 PHINode *phi = (*i).first;
234 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx)
235 {
236 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) {
237 phi->removeIncomingValue(idx);
238 --idx;
239 --end;
240 }
241 }
242 }
243
244 // We are done with the saved values
245 PhiVal2Arg.clear();
246}
247
248
249/// constructFunction - make a function based on inputs and outputs, as follows:
250/// f(in0, ..., inN, out0, ..., outN)
251///
252Function *CodeExtractor::constructFunction(const Values &inputs,
253 const Values &outputs,
254 BasicBlock *newRootNode,
255 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000256 Function *oldFunction, Module *M) {
257 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
258 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
Chris Lattner9c431f62004-03-14 22:34:55 +0000259 BasicBlock *header = *BlocksToExtract.begin();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000260
261 // This function returns unsigned, outputs will go back by reference.
262 Type *retTy = Type::UShortTy;
263 std::vector<const Type*> paramTy;
264
265 // Add the types of the input values to the function's argument list
266 for (Values::const_iterator i = inputs.begin(),
267 e = inputs.end(); i != e; ++i) {
268 const Value *value = *i;
269 DEBUG(std::cerr << "value used in func: " << value << "\n");
270 paramTy.push_back(value->getType());
271 }
272
273 // Add the types of the output values to the function's argument list, but
274 // make them pointer types for scalars
275 for (Values::const_iterator i = outputs.begin(),
276 e = outputs.end(); i != e; ++i) {
277 const Value *value = *i;
278 DEBUG(std::cerr << "instr used in func: " << value << "\n");
279 const Type *valueType = value->getType();
280 // Convert scalar types into a pointer of that type
281 if (valueType->isPrimitiveType()) {
282 valueType = PointerType::get(valueType);
283 }
284 paramTy.push_back(valueType);
285 }
286
287 DEBUG(std::cerr << "Function type: " << retTy << " f(");
288 for (std::vector<const Type*>::iterator i = paramTy.begin(),
289 e = paramTy.end(); i != e; ++i)
290 DEBUG(std::cerr << (*i) << ", ");
291 DEBUG(std::cerr << ")\n");
292
293 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
294
295 // Create the new function
296 Function *newFunction = new Function(funcType,
297 GlobalValue::InternalLinkage,
298 oldFunction->getName() + "_code", M);
299 newFunction->getBasicBlockList().push_back(newRootNode);
300
301 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
302 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
303 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000304 use != useE; ++use)
305 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chris Lattner9c431f62004-03-14 22:34:55 +0000306 if (BlocksToExtract.count(inst->getParent()))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000307 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000308 }
309
310 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
311 // within the new function. This must be done before we lose track of which
312 // blocks were originally in the code region.
313 std::vector<User*> Users(header->use_begin(), header->use_end());
314 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end();
315 i != e; ++i) {
316 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) {
317 BasicBlock *BB = inst->getParent();
Chris Lattner9c431f62004-03-14 22:34:55 +0000318 if (!BlocksToExtract.count(BB) && BB->getParent() == oldFunction) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000319 // The BasicBlock which contains the branch is not in the region
320 // modify the branch target to a new block
321 inst->replaceUsesOfWith(header, newHeader);
322 }
323 }
324 }
325
326 return newFunction;
327}
328
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000329void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000330 Function *oldFunc = (*BlocksToExtract.begin())->getParent();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000331 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000332 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000333
Chris Lattner9c431f62004-03-14 22:34:55 +0000334 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
335 e = BlocksToExtract.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000336 // Delete the basic block from the old function, and the list of blocks
Chris Lattner9c431f62004-03-14 22:34:55 +0000337 oldBlocks.remove(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000338
339 // Insert this basic block into the new function
Chris Lattner9c431f62004-03-14 22:34:55 +0000340 newBlocks.push_back(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000341 }
342}
343
344void
345CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
346 BasicBlock *codeReplacer,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000347 Values &inputs,
348 Values &outputs)
349{
350 // Emit a call to the new function, passing allocated memory for outputs and
351 // just plain inputs for non-scalars
Chris Lattner5b2072e2004-03-14 23:43:24 +0000352 std::vector<Value*> params(inputs);
353
354 for (Values::const_iterator i = outputs.begin(), e = outputs.end(); i != e;
355 ++i) {
356 Value *Output = *i;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000357 // Create allocas for scalar outputs
Chris Lattner5b2072e2004-03-14 23:43:24 +0000358 if (Output->getType()->isPrimitiveType()) {
359 AllocaInst *alloca =
360 new AllocaInst((*i)->getType(), 0, Output->getName()+".loc",
361 codeReplacer->getParent()->begin()->begin());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000362 params.push_back(alloca);
363
Chris Lattner5b2072e2004-03-14 23:43:24 +0000364 LoadInst *load = new LoadInst(alloca, Output->getName()+".reload");
365 codeReplacer->getInstList().push_back(load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000366 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end());
367 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end();
368 use != useE; ++use) {
369 if (Instruction* inst = dyn_cast<Instruction>(*use)) {
Chris Lattner5b2072e2004-03-14 23:43:24 +0000370 if (!BlocksToExtract.count(inst->getParent()))
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000371 inst->replaceUsesOfWith(*i, load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000372 }
373 }
374 } else {
375 params.push_back(*i);
376 }
377 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000378
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000379 CallInst *call = new CallInst(newFunction, params, "targetBlock");
Chris Lattner5b2072e2004-03-14 23:43:24 +0000380 codeReplacer->getInstList().push_front(call);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000381
382 // Now we can emit a switch statement using the call as a value.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000383 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000384
385 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000386 // function return an unsigned, switch on that number. This loop iterates
387 // over all of the blocks in the extracted region, updating any terminator
388 // instructions in the to-be-extracted region that branch to blocks that are
389 // not in the region to be extracted.
390 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
391
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000392 unsigned switchVal = 0;
Chris Lattner9c431f62004-03-14 22:34:55 +0000393 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
394 e = BlocksToExtract.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000395 TerminatorInst *TI = (*i)->getTerminator();
396 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
397 if (!BlocksToExtract.count(TI->getSuccessor(i))) {
398 BasicBlock *OldTarget = TI->getSuccessor(i);
399 // add a new basic block which returns the appropriate value
400 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
401 if (!NewTarget) {
402 // If we don't already have an exit stub for this non-extracted
403 // destination, create one now!
404 NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub",
405 newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000406
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000407 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++);
408 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000409
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000410 // Update the switch instruction.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000411 TheSwitch->addCase(brVal, OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000412
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000413 // Restore values just before we exit
414 // FIXME: Use a GetElementPtr to bunch the outputs in a struct
415 for (unsigned out = 0, e = outputs.size(); out != e; ++out)
416 new StoreInst(outputs[out], getFunctionArg(newFunction, out),NTRet);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000417 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000418
419 // rewrite the original branch instruction with this new target
420 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000421 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000422 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000423
424 // Now that we've done the deed, make the default destination of the switch
425 // instruction be one of the exit blocks of the region.
426 if (TheSwitch->getNumSuccessors() > 1) {
427 // FIXME: this is broken w.r.t. PHI nodes, but the old code was more broken.
428 // This edge is not traversable.
429 TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(1));
430 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000431}
432
433
434/// ExtractRegion - Removes a loop from a function, replaces it with a call to
435/// new function. Returns pointer to the new function.
436///
437/// algorithm:
438///
439/// find inputs and outputs for the region
440///
441/// for inputs: add to function as args, map input instr* to arg#
442/// for outputs: add allocas for scalars,
443/// add to func as args, map output instr* to arg#
444///
445/// rewrite func to use argument #s instead of instr*
446///
447/// for each scalar output in the function: at every exit, store intermediate
448/// computed result back into memory.
449///
450Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
451{
452 // 1) Find inputs, outputs
453 // 2) Construct new function
454 // * Add allocas for defs, pass as args by reference
455 // * Pass in uses as args
456 // 3) Move code region, add call instr to func
Chris Lattner9c431f62004-03-14 22:34:55 +0000457 //
458 BlocksToExtract.insert(code.begin(), code.end());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000459
460 Values inputs, outputs;
461
462 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000463 // block in the region.
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000464 BasicBlock *header = code[0];
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000465 for (unsigned i = 1, e = code.size(); i != e; ++i)
466 for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
467 PI != E; ++PI)
468 assert(BlocksToExtract.count(*PI) &&
469 "No blocks in this region may have entries from outside the region"
470 " except for the first block!");
471
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000472 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000473
474 // This takes place of the original loop
475 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
476
477 // The new function needs a root node because other nodes can branch to the
478 // head of the loop, and the root cannot have predecessors
479 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
480 newFuncRoot->getInstList().push_back(new BranchInst(header));
481
482 // Find inputs to, outputs from the code region
483 //
484 // If one of the inputs is coming from a different basic block and it's in a
485 // phi node, we need to rewrite the phi node:
486 //
487 // * All the inputs which involve basic blocks OUTSIDE of this region go into
488 // a NEW phi node that takes care of finding which value really came in.
489 // The result of this phi is passed to the function as an argument.
490 //
491 // * All the other phi values stay.
492 //
493 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
494 // blocks moving to a new function.
495 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
496 // the values as parameters to the function
Chris Lattner9c431f62004-03-14 22:34:55 +0000497 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000498
499 // Step 2: Construct new function based on inputs/outputs,
500 // Add allocas for all defs
501 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000502 codeReplacer, oldFunction,
503 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000504
505 rewritePhiNodes(newFunction, newFuncRoot);
506
Chris Lattner9c431f62004-03-14 22:34:55 +0000507 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000508
Chris Lattner9c431f62004-03-14 22:34:55 +0000509 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000510
Chris Lattner36844692004-03-14 03:17:22 +0000511 DEBUG(if (verifyFunction(*newFunction)) abort());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000512 return newFunction;
513}
514
Misha Brukmanf44acae2004-03-02 00:20:57 +0000515/// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
516/// function
517///
518Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
Chris Lattner4fca71e2004-03-14 04:01:47 +0000519 return CodeExtractor().ExtractCodeRegion(code);
Misha Brukmanf44acae2004-03-02 00:20:57 +0000520}
521
Misha Brukman5af2be72004-03-01 18:28:34 +0000522/// ExtractBasicBlock - slurp a natural loop into a brand new function
523///
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000524Function* llvm::ExtractLoop(Loop *L) {
Chris Lattner4fca71e2004-03-14 04:01:47 +0000525 return CodeExtractor().ExtractCodeRegion(L->getBlocks());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000526}
527
Misha Brukman5af2be72004-03-01 18:28:34 +0000528/// ExtractBasicBlock - slurp a basic block into a brand new function
529///
530Function* llvm::ExtractBasicBlock(BasicBlock *BB) {
Misha Brukman5af2be72004-03-01 18:28:34 +0000531 std::vector<BasicBlock*> Blocks;
532 Blocks.push_back(BB);
Chris Lattner4fca71e2004-03-14 04:01:47 +0000533 return CodeExtractor().ExtractCodeRegion(Blocks);
Misha Brukman5af2be72004-03-01 18:28:34 +0000534}