blob: b16a71bb4dbedc3abeee3a43abea5429b169b4bd [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"
Chris Lattner37de2572004-03-18 03:49:40 +000022#include "llvm/Analysis/Dominators.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000023#include "llvm/Analysis/LoopInfo.h"
Chris Lattner36844692004-03-14 03:17:22 +000024#include "llvm/Analysis/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000025#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukman3596f0a2004-04-23 23:54:17 +000026#include "Support/CommandLine.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000027#include "Support/Debug.h"
28#include "Support/StringExtras.h"
29#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000030#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000031using namespace llvm;
32
Misha Brukman3596f0a2004-04-23 23:54:17 +000033// Provide a command-line option to aggregate function arguments into a struct
34// for functions produced by the code extrator. This is useful when converting
35// extracted functions to pthread-based code, as only one argument (void*) can
36// be passed in to pthread_create().
37static cl::opt<bool>
38AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
39 cl::desc("Aggregate arguments to code-extracted functions"));
40
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000041namespace {
Chris Lattner37de2572004-03-18 03:49:40 +000042 class CodeExtractor {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000043 typedef std::vector<Value*> Values;
Chris Lattner9c431f62004-03-14 22:34:55 +000044 std::set<BasicBlock*> BlocksToExtract;
Chris Lattner37de2572004-03-18 03:49:40 +000045 DominatorSet *DS;
Misha Brukman3596f0a2004-04-23 23:54:17 +000046 bool AggregateArgs;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000047 public:
Misha Brukman3596f0a2004-04-23 23:54:17 +000048 CodeExtractor(DominatorSet *ds = 0, bool AggArgs = false)
49 : DS(ds), AggregateArgs(AggregateArgsOpt) {}
Chris Lattner37de2572004-03-18 03:49:40 +000050
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000051 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
52
Misha Brukman3596f0a2004-04-23 23:54:17 +000053 bool isEligible(const std::vector<BasicBlock*> &code);
54
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000055 private:
Chris Lattner9c431f62004-03-14 22:34:55 +000056 void findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000057 BasicBlock *newHeader,
58 BasicBlock *newRootNode);
59
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000060 Function *constructFunction(const Values &inputs,
61 const Values &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +000062 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000063 BasicBlock *newRootNode, BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000064 Function *oldFunction, Module *M);
65
Chris Lattner9c431f62004-03-14 22:34:55 +000066 void moveCodeToFunction(Function *newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000067
68 void emitCallAndSwitchStatement(Function *newFunction,
69 BasicBlock *newHeader,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000070 Values &inputs,
71 Values &outputs);
72
73 };
74}
75
Chris Lattner73ab1fa2004-03-15 01:18:23 +000076void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000077 BasicBlock *newHeader,
Chris Lattner73ab1fa2004-03-15 01:18:23 +000078 BasicBlock *newRootNode) {
Chris Lattner9c431f62004-03-14 22:34:55 +000079 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
80 ce = BlocksToExtract.end(); ci != ce; ++ci) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000081 BasicBlock *BB = *ci;
Chris Lattner73ab1fa2004-03-15 01:18:23 +000082 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
83 // If a used value is defined outside the region, it's an input. If an
84 // instruction is used outside the region, it's an output.
Chris Lattner320d59f2004-03-18 05:28:49 +000085 if (PHINode *PN = dyn_cast<PHINode>(I)) {
86 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
87 Value *V = PN->getIncomingValue(i);
88 if (!BlocksToExtract.count(PN->getIncomingBlock(i)) &&
89 (isa<Instruction>(V) || isa<Argument>(V)))
90 inputs.push_back(V);
Chris Lattner232155d2004-03-18 05:56:32 +000091 else if (Instruction *opI = dyn_cast<Instruction>(V)) {
92 if (!BlocksToExtract.count(opI->getParent()))
93 inputs.push_back(opI);
94 } else if (isa<Argument>(V))
95 inputs.push_back(V);
Chris Lattner320d59f2004-03-18 05:28:49 +000096 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +000097 } else {
98 // All other instructions go through the generic input finder
99 // Loop over the operands of each instruction (inputs)
100 for (User::op_iterator op = I->op_begin(), opE = I->op_end();
101 op != opE; ++op)
102 if (Instruction *opI = dyn_cast<Instruction>(*op)) {
103 // Check if definition of this operand is within the loop
Chris Lattnerfb87cde2004-03-15 01:26:44 +0000104 if (!BlocksToExtract.count(opI->getParent()))
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000105 inputs.push_back(opI);
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000106 } else if (isa<Argument>(*op)) {
107 inputs.push_back(*op);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000108 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000109 }
110
111 // Consider uses of this instruction (outputs)
112 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
113 UI != E; ++UI)
Chris Lattner37de2572004-03-18 03:49:40 +0000114 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent())) {
115 outputs.push_back(I);
116 break;
117 }
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000118 } // for: insts
119 } // for: basic blocks
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000120}
121
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000122/// constructFunction - make a function based on inputs and outputs, as follows:
123/// f(in0, ..., inN, out0, ..., outN)
124///
125Function *CodeExtractor::constructFunction(const Values &inputs,
126 const Values &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000127 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000128 BasicBlock *newRootNode,
129 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000130 Function *oldFunction,
131 Module *M) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000132 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
133 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000134
135 // This function returns unsigned, outputs will go back by reference.
136 Type *retTy = Type::UShortTy;
137 std::vector<const Type*> paramTy;
138
139 // Add the types of the input values to the function's argument list
140 for (Values::const_iterator i = inputs.begin(),
141 e = inputs.end(); i != e; ++i) {
142 const Value *value = *i;
143 DEBUG(std::cerr << "value used in func: " << value << "\n");
144 paramTy.push_back(value->getType());
145 }
146
Chris Lattner37de2572004-03-18 03:49:40 +0000147 // Add the types of the output values to the function's argument list.
148 for (Values::const_iterator I = outputs.begin(), E = outputs.end();
149 I != E; ++I) {
150 DEBUG(std::cerr << "instr used in func: " << *I << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000151 if (AggregateArgs)
152 paramTy.push_back((*I)->getType());
153 else
154 paramTy.push_back(PointerType::get((*I)->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000155 }
156
157 DEBUG(std::cerr << "Function type: " << retTy << " f(");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000158 DEBUG(for (std::vector<const Type*>::iterator i = paramTy.begin(),
159 e = paramTy.end(); i != e; ++i) std::cerr << *i << ", ");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000160 DEBUG(std::cerr << ")\n");
161
Misha Brukman3596f0a2004-04-23 23:54:17 +0000162 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
163 PointerType *StructPtr = PointerType::get(StructType::get(paramTy));
164 paramTy.clear();
165 paramTy.push_back(StructPtr);
166 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000167 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
168
169 // Create the new function
170 Function *newFunction = new Function(funcType,
171 GlobalValue::InternalLinkage,
172 oldFunction->getName() + "_code", M);
173 newFunction->getBasicBlockList().push_back(newRootNode);
174
Chris Lattner37de2572004-03-18 03:49:40 +0000175 // Create an iterator to name all of the arguments we inserted.
176 Function::aiterator AI = newFunction->abegin();
177
178 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000179 // arguments (or appropriate addressing into struct) instead.
180 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
181 Value *RewriteVal;
182 if (AggregateArgs) {
183 std::vector<Value*> Indices;
184 Indices.push_back(Constant::getNullValue(Type::UIntTy));
185 Indices.push_back(ConstantUInt::get(Type::UIntTy, i));
186 std::string GEPname = "gep_" + inputs[i]->getName();
187 TerminatorInst *TI = newFunction->begin()->getTerminator();
188 GetElementPtrInst *GEP = new GetElementPtrInst(AI, Indices, GEPname, TI);
189 RewriteVal = new LoadInst(GEP, "load" + GEPname, TI);
190 } else
191 RewriteVal = AI++;
192
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000193 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
194 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000195 use != useE; ++use)
196 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chris Lattner9c431f62004-03-14 22:34:55 +0000197 if (BlocksToExtract.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000198 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000199 }
200
Misha Brukman3596f0a2004-04-23 23:54:17 +0000201 // Set names for input and output arguments.
202 if (!AggregateArgs) {
203 AI = newFunction->abegin();
204 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
205 AI->setName(inputs[i]->getName());
206 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
207 AI->setName(outputs[i]->getName()+".out");
208 }
Chris Lattner37de2572004-03-18 03:49:40 +0000209
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000210 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
211 // within the new function. This must be done before we lose track of which
212 // blocks were originally in the code region.
213 std::vector<User*> Users(header->use_begin(), header->use_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000214 for (unsigned i = 0, e = Users.size(); i != e; ++i)
215 // The BasicBlock which contains the branch is not in the region
216 // modify the branch target to a new block
217 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
218 if (!BlocksToExtract.count(TI->getParent()) &&
219 TI->getParent()->getParent() == oldFunction)
220 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000221
222 return newFunction;
223}
224
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000225void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chris Lattner9c431f62004-03-14 22:34:55 +0000226 Function *oldFunc = (*BlocksToExtract.begin())->getParent();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000227 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000228 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
Chris Lattner4fca71e2004-03-14 04:01:47 +0000229
Chris Lattner9c431f62004-03-14 22:34:55 +0000230 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
231 e = BlocksToExtract.end(); i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000232 // Delete the basic block from the old function, and the list of blocks
Chris Lattner9c431f62004-03-14 22:34:55 +0000233 oldBlocks.remove(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000234
235 // Insert this basic block into the new function
Chris Lattner9c431f62004-03-14 22:34:55 +0000236 newBlocks.push_back(*i);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000237 }
238}
239
240void
241CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
242 BasicBlock *codeReplacer,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000243 Values &inputs,
Chris Lattner37de2572004-03-18 03:49:40 +0000244 Values &outputs) {
Chris Lattner5b2072e2004-03-14 23:43:24 +0000245
Misha Brukman3596f0a2004-04-23 23:54:17 +0000246 // Emit a call to the new function, passing in:
247 // *pointer to struct (if aggregating parameters), or
248 // plan inputs and allocated memory for outputs
249 std::vector<Value*> params, StructValues, ReloadOutputs;
Chris Lattnerd8017a32004-03-18 04:12:05 +0000250
Misha Brukman3596f0a2004-04-23 23:54:17 +0000251 // Add inputs as params, or to be filled into the struct
252 for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
253 if (AggregateArgs)
254 StructValues.push_back(*i);
255 else
256 params.push_back(*i);
257
258 // Create allocas for the outputs
259 for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
260 if (AggregateArgs) {
261 StructValues.push_back(*i);
262 } else {
263 AllocaInst *alloca =
264 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
265 codeReplacer->getParent()->begin()->begin());
266 ReloadOutputs.push_back(alloca);
267 params.push_back(alloca);
268 }
269 }
270
271 AllocaInst *Struct = 0;
272 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
273 std::vector<const Type*> ArgTypes;
274 for (Values::iterator v = StructValues.begin(),
275 ve = StructValues.end(); v != ve; ++v)
276 ArgTypes.push_back((*v)->getType());
277
278 // Allocate a struct at the beginning of this function
279 Type *StructArgTy = StructType::get(ArgTypes);
280 Struct =
281 new AllocaInst(StructArgTy, 0, "structArg",
Chris Lattner37de2572004-03-18 03:49:40 +0000282 codeReplacer->getParent()->begin()->begin());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000283 params.push_back(Struct);
284
285 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
286 std::vector<Value*> Indices;
287 Indices.push_back(Constant::getNullValue(Type::UIntTy));
288 Indices.push_back(ConstantUInt::get(Type::UIntTy, i));
289 GetElementPtrInst *GEP =
290 new GetElementPtrInst(Struct, Indices,
291 "gep_" + StructValues[i]->getName(), 0);
292 codeReplacer->getInstList().push_back(GEP);
293 StoreInst *SI = new StoreInst(StructValues[i], GEP);
294 codeReplacer->getInstList().push_back(SI);
295 }
296 }
297
298 // Emit the call to the function
299 CallInst *call = new CallInst(newFunction, params, "targetBlock");
300 codeReplacer->getInstList().push_back(call);
301
302 Function::aiterator OutputArgBegin = newFunction->abegin();
303 unsigned FirstOut = inputs.size();
304 if (!AggregateArgs)
305 std::advance(OutputArgBegin, inputs.size());
306
307 // Reload the outputs passed in by reference
308 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
309 Value *Output = 0;
310 if (AggregateArgs) {
311 std::vector<Value*> Indices;
312 Indices.push_back(Constant::getNullValue(Type::UIntTy));
313 Indices.push_back(ConstantUInt::get(Type::UIntTy, FirstOut + i));
314 GetElementPtrInst *GEP
315 = new GetElementPtrInst(Struct, Indices,
316 "gep_reload_" + outputs[i]->getName(), 0);
317 codeReplacer->getInstList().push_back(GEP);
318 Output = GEP;
319 } else {
320 Output = ReloadOutputs[i];
321 }
322 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Chris Lattner37de2572004-03-18 03:49:40 +0000323 codeReplacer->getInstList().push_back(load);
324 std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
325 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
326 Instruction *inst = cast<Instruction>(Users[u]);
327 if (!BlocksToExtract.count(inst->getParent()))
328 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000329 }
330 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000331
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000332 // Now we can emit a switch statement using the call as a value.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000333 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000334
335 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000336 // function return an unsigned, switch on that number. This loop iterates
337 // over all of the blocks in the extracted region, updating any terminator
338 // instructions in the to-be-extracted region that branch to blocks that are
339 // not in the region to be extracted.
340 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
341
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000342 unsigned switchVal = 0;
Chris Lattner9c431f62004-03-14 22:34:55 +0000343 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
344 e = BlocksToExtract.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000345 TerminatorInst *TI = (*i)->getTerminator();
346 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
347 if (!BlocksToExtract.count(TI->getSuccessor(i))) {
348 BasicBlock *OldTarget = TI->getSuccessor(i);
349 // add a new basic block which returns the appropriate value
350 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
351 if (!NewTarget) {
352 // If we don't already have an exit stub for this non-extracted
353 // destination, create one now!
354 NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub",
355 newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000356
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000357 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++);
358 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000359
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000360 // Update the switch instruction.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000361 TheSwitch->addCase(brVal, OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000362
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000363 // Restore values just before we exit
Chris Lattnerd8017a32004-03-18 04:12:05 +0000364 Function::aiterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000365 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
366 // For an invoke, the normal destination is the only one that is
367 // dominated by the result of the invocation
368 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
369 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out]))
370 DefBlock = Invoke->getNormalDest();
371 if (!DS || DS->dominates(DefBlock, TI->getParent()))
372 if (AggregateArgs) {
373 std::vector<Value*> Indices;
374 Indices.push_back(Constant::getNullValue(Type::UIntTy));
375 Indices.push_back(ConstantUInt::get(Type::UIntTy,FirstOut+out));
376 GetElementPtrInst *GEP =
377 new GetElementPtrInst(OAI, Indices,
378 "gep_" + outputs[out]->getName(),
379 NTRet);
380 new StoreInst(outputs[out], GEP, NTRet);
381 } else
382 new StoreInst(outputs[out], OAI, NTRet);
383 // Advance output iterator even if we don't emit a store
384 if (!AggregateArgs) ++OAI;
385 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000386 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000387
388 // rewrite the original branch instruction with this new target
389 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000390 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000391 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000392
393 // Now that we've done the deed, make the default destination of the switch
Misha Brukman3596f0a2004-04-23 23:54:17 +0000394 // instruction be a block with a call to abort() -- since this path should not
395 // be taken, this will abort sooner rather than later.
Chris Lattner5b2072e2004-03-14 23:43:24 +0000396 if (TheSwitch->getNumSuccessors() > 1) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000397 Function *container = codeReplacer->getParent();
398 BasicBlock *abortBB = new BasicBlock("abortBlock", container);
399 std::vector<const Type*> paramTypes;
400 FunctionType *abortTy = FunctionType::get(Type::VoidTy, paramTypes, false);
401 Function *abortFunc =
402 container->getParent()->getOrInsertFunction("abort", abortTy);
403 abortBB->getInstList().push_back(new CallInst(abortFunc));
404 Function *ParentFunc = TheSwitch->getParent()->getParent();
405 if (ParentFunc->getReturnType() == Type::VoidTy)
406 new ReturnInst(0, abortBB);
407 else
408 new ReturnInst(Constant::getNullValue(ParentFunc->getReturnType()),
409 abortBB);
410 TheSwitch->setSuccessor(0, abortBB);
411 } else {
412 // There is only 1 successor (the block containing the switch itself), which
413 // means that previously this was the last part of the function, and hence
414 // this should be rewritten as a `ret'
415
416 // Check if the function should return a value
417 if (TheSwitch->getParent()->getParent()->getReturnType() != Type::VoidTy &&
418 TheSwitch->getParent()->getParent()->getReturnType() ==
419 TheSwitch->getCondition()->getType())
420 // return what we have
421 new ReturnInst(TheSwitch->getCondition(), TheSwitch);
422 else
423 // just return
424 new ReturnInst(0, TheSwitch);
425
426 TheSwitch->getParent()->getInstList().erase(TheSwitch);
Chris Lattner5b2072e2004-03-14 23:43:24 +0000427 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000428}
429
430
431/// ExtractRegion - Removes a loop from a function, replaces it with a call to
432/// new function. Returns pointer to the new function.
433///
434/// algorithm:
435///
436/// find inputs and outputs for the region
437///
438/// for inputs: add to function as args, map input instr* to arg#
439/// for outputs: add allocas for scalars,
440/// add to func as args, map output instr* to arg#
441///
442/// rewrite func to use argument #s instead of instr*
443///
444/// for each scalar output in the function: at every exit, store intermediate
445/// computed result back into memory.
446///
447Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
448{
Misha Brukman3596f0a2004-04-23 23:54:17 +0000449 if (!isEligible(code))
450 return 0;
451
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000452 // 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
Chris Lattner320d59f2004-03-18 05:28:49 +0000501 Function *newFunction = constructFunction(inputs, outputs, code[0],
502 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000503 codeReplacer, oldFunction,
504 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000505
Chris Lattner9c431f62004-03-14 22:34:55 +0000506 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000507
Chris Lattner9c431f62004-03-14 22:34:55 +0000508 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000509
Chris Lattner320d59f2004-03-18 05:28:49 +0000510 // Loop over all of the PHI nodes in the entry block (code[0]), and change any
511 // references to the old incoming edge to be the new incoming edge.
512 for (BasicBlock::iterator I = code[0]->begin();
513 PHINode *PN = dyn_cast<PHINode>(I); ++I)
514 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
515 if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
516 PN->setIncomingBlock(i, newFuncRoot);
517
Chris Lattneracd75982004-03-18 05:38:31 +0000518 // Look at all successors of the codeReplacer block. If any of these blocks
519 // had PHI nodes in them, we need to update the "from" block to be the code
520 // replacer, not the original block in the extracted region.
521 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
522 succ_end(codeReplacer));
523 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
524 for (BasicBlock::iterator I = Succs[i]->begin();
525 PHINode *PN = dyn_cast<PHINode>(I); ++I)
526 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
527 if (BlocksToExtract.count(PN->getIncomingBlock(i)))
528 PN->setIncomingBlock(i, codeReplacer);
529
530
Chris Lattner36844692004-03-14 03:17:22 +0000531 DEBUG(if (verifyFunction(*newFunction)) abort());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000532 return newFunction;
533}
534
Misha Brukman3596f0a2004-04-23 23:54:17 +0000535bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
536 // Deny code region if it contains allocas
537 for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
538 BB != e; ++BB)
539 for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
540 I != Ie; ++I)
541 if (isa<AllocaInst>(*I))
542 return false;
543 return true;
544}
545
546
Misha Brukmanf44acae2004-03-02 00:20:57 +0000547/// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
548/// function
549///
Chris Lattner37de2572004-03-18 03:49:40 +0000550Function* llvm::ExtractCodeRegion(DominatorSet &DS,
Misha Brukman3596f0a2004-04-23 23:54:17 +0000551 const std::vector<BasicBlock*> &code,
552 bool AggregateArgs) {
553 return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(code);
Misha Brukmanf44acae2004-03-02 00:20:57 +0000554}
555
Misha Brukman5af2be72004-03-01 18:28:34 +0000556/// ExtractBasicBlock - slurp a natural loop into a brand new function
557///
Misha Brukman3596f0a2004-04-23 23:54:17 +0000558Function* llvm::ExtractLoop(DominatorSet &DS, Loop *L, bool AggregateArgs) {
559 return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(L->getBlocks());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000560}
561
Misha Brukman5af2be72004-03-01 18:28:34 +0000562/// ExtractBasicBlock - slurp a basic block into a brand new function
563///
Misha Brukman3596f0a2004-04-23 23:54:17 +0000564Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
Misha Brukman5af2be72004-03-01 18:28:34 +0000565 std::vector<BasicBlock*> Blocks;
566 Blocks.push_back(BB);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000567 return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);
Misha Brukman5af2be72004-03-01 18:28:34 +0000568}