1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Utils/FunctionUtils.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/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Debug.h"
28 #include "Support/StringExtras.h"
33 // 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().
38 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
39 cl::desc("Aggregate arguments to code-extracted functions"));
43 typedef std::vector<Value*> Values;
44 std::set<BasicBlock*> BlocksToExtract;
48 CodeExtractor(DominatorSet *ds = 0, bool AggArgs = false)
49 : DS(ds), AggregateArgs(AggregateArgsOpt) {}
51 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
53 bool isEligible(const std::vector<BasicBlock*> &code);
56 void findInputsOutputs(Values &inputs, Values &outputs,
57 BasicBlock *newHeader,
58 BasicBlock *newRootNode);
60 Function *constructFunction(const Values &inputs,
61 const Values &outputs,
63 BasicBlock *newRootNode, BasicBlock *newHeader,
64 Function *oldFunction, Module *M);
66 void moveCodeToFunction(Function *newFunction);
68 void emitCallAndSwitchStatement(Function *newFunction,
69 BasicBlock *newHeader,
76 void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs,
77 BasicBlock *newHeader,
78 BasicBlock *newRootNode) {
79 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
80 ce = BlocksToExtract.end(); ci != ce; ++ci) {
82 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.
85 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)))
91 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))
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();
102 if (Instruction *opI = dyn_cast<Instruction>(*op)) {
103 // Check if definition of this operand is within the loop
104 if (!BlocksToExtract.count(opI->getParent()))
105 inputs.push_back(opI);
106 } else if (isa<Argument>(*op)) {
107 inputs.push_back(*op);
111 // Consider uses of this instruction (outputs)
112 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
114 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent())) {
115 outputs.push_back(I);
119 } // for: basic blocks
122 /// constructFunction - make a function based on inputs and outputs, as follows:
123 /// f(in0, ..., inN, out0, ..., outN)
125 Function *CodeExtractor::constructFunction(const Values &inputs,
126 const Values &outputs,
128 BasicBlock *newRootNode,
129 BasicBlock *newHeader,
130 Function *oldFunction,
132 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
133 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
135 // This function returns unsigned, outputs will go back by reference.
136 Type *retTy = Type::UShortTy;
137 std::vector<const Type*> paramTy;
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());
147 // Add the types of the output values to the function's argument list.
148 for (Values::const_iterator I = outputs.begin(), E = outputs.end();
150 DEBUG(std::cerr << "instr used in func: " << *I << "\n");
152 paramTy.push_back((*I)->getType());
154 paramTy.push_back(PointerType::get((*I)->getType()));
157 DEBUG(std::cerr << "Function type: " << retTy << " f(");
158 DEBUG(for (std::vector<const Type*>::iterator i = paramTy.begin(),
159 e = paramTy.end(); i != e; ++i) std::cerr << *i << ", ");
160 DEBUG(std::cerr << ")\n");
162 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
163 PointerType *StructPtr = PointerType::get(StructType::get(paramTy));
165 paramTy.push_back(StructPtr);
167 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
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);
175 // Create an iterator to name all of the arguments we inserted.
176 Function::aiterator AI = newFunction->abegin();
178 // Rewrite all users of the inputs in the extracted region to use the
179 // arguments (or appropriate addressing into struct) instead.
180 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
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);
193 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
194 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
196 if (Instruction* inst = dyn_cast<Instruction>(*use))
197 if (BlocksToExtract.count(inst->getParent()))
198 inst->replaceUsesOfWith(inputs[i], RewriteVal);
201 // 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");
210 // 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());
214 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);
225 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
226 Function *oldFunc = (*BlocksToExtract.begin())->getParent();
227 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
228 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
230 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
231 e = BlocksToExtract.end(); i != e; ++i) {
232 // Delete the basic block from the old function, and the list of blocks
233 oldBlocks.remove(*i);
235 // Insert this basic block into the new function
236 newBlocks.push_back(*i);
241 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
242 BasicBlock *codeReplacer,
246 // 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;
251 // Add inputs as params, or to be filled into the struct
252 for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
254 StructValues.push_back(*i);
256 params.push_back(*i);
258 // Create allocas for the outputs
259 for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
261 StructValues.push_back(*i);
264 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
265 codeReplacer->getParent()->begin()->begin());
266 ReloadOutputs.push_back(alloca);
267 params.push_back(alloca);
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());
278 // Allocate a struct at the beginning of this function
279 Type *StructArgTy = StructType::get(ArgTypes);
281 new AllocaInst(StructArgTy, 0, "structArg",
282 codeReplacer->getParent()->begin()->begin());
283 params.push_back(Struct);
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);
298 // Emit the call to the function
299 CallInst *call = new CallInst(newFunction, params, "targetBlock");
300 codeReplacer->getInstList().push_back(call);
302 Function::aiterator OutputArgBegin = newFunction->abegin();
303 unsigned FirstOut = inputs.size();
305 std::advance(OutputArgBegin, inputs.size());
307 // Reload the outputs passed in by reference
308 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
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);
320 Output = ReloadOutputs[i];
322 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
323 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);
332 // Now we can emit a switch statement using the call as a value.
333 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer);
335 // Since there may be multiple exits from the original region, make the new
336 // 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;
342 unsigned switchVal = 0;
343 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
344 e = BlocksToExtract.end(); i != e; ++i) {
345 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];
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",
357 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++);
358 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
360 // Update the switch instruction.
361 TheSwitch->addCase(brVal, OldTarget);
363 // Restore values just before we exit
364 Function::aiterator OAI = OutputArgBegin;
365 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()))
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(),
380 new StoreInst(outputs[out], GEP, NTRet);
382 new StoreInst(outputs[out], OAI, NTRet);
383 // Advance output iterator even if we don't emit a store
384 if (!AggregateArgs) ++OAI;
388 // rewrite the original branch instruction with this new target
389 TI->setSuccessor(i, NewTarget);
393 // Now that we've done the deed, simplify the switch instruction.
394 unsigned NumSuccs = TheSwitch->getNumSuccessors();
396 if (NumSuccs-1 == 1) {
397 // Only a single destination, change the switch into an unconditional
399 new BranchInst(TheSwitch->getSuccessor(1), TheSwitch);
400 TheSwitch->getParent()->getInstList().erase(TheSwitch);
402 // Otherwise, make the default destination of the switch instruction be
403 // one of the other successors.
404 TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumSuccs-1));
405 TheSwitch->removeCase(NumSuccs-1); // Remove redundant case
408 // There is only 1 successor (the block containing the switch itself), which
409 // means that previously this was the last part of the function, and hence
410 // this should be rewritten as a `ret'
412 // Check if the function should return a value
413 if (TheSwitch->getParent()->getParent()->getReturnType() != Type::VoidTy &&
414 TheSwitch->getParent()->getParent()->getReturnType() ==
415 TheSwitch->getCondition()->getType())
416 // return what we have
417 new ReturnInst(TheSwitch->getCondition(), TheSwitch);
420 new ReturnInst(0, TheSwitch);
422 TheSwitch->getParent()->getInstList().erase(TheSwitch);
427 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
428 /// new function. Returns pointer to the new function.
432 /// find inputs and outputs for the region
434 /// for inputs: add to function as args, map input instr* to arg#
435 /// for outputs: add allocas for scalars,
436 /// add to func as args, map output instr* to arg#
438 /// rewrite func to use argument #s instead of instr*
440 /// for each scalar output in the function: at every exit, store intermediate
441 /// computed result back into memory.
443 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
445 if (!isEligible(code))
448 // 1) Find inputs, outputs
449 // 2) Construct new function
450 // * Add allocas for defs, pass as args by reference
451 // * Pass in uses as args
452 // 3) Move code region, add call instr to func
454 BlocksToExtract.insert(code.begin(), code.end());
456 Values inputs, outputs;
458 // Assumption: this is a single-entry code region, and the header is the first
459 // block in the region.
460 BasicBlock *header = code[0];
461 for (unsigned i = 1, e = code.size(); i != e; ++i)
462 for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
464 assert(BlocksToExtract.count(*PI) &&
465 "No blocks in this region may have entries from outside the region"
466 " except for the first block!");
468 Function *oldFunction = header->getParent();
470 // This takes place of the original loop
471 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
473 // The new function needs a root node because other nodes can branch to the
474 // head of the loop, and the root cannot have predecessors
475 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
476 newFuncRoot->getInstList().push_back(new BranchInst(header));
478 // Find inputs to, outputs from the code region
480 // If one of the inputs is coming from a different basic block and it's in a
481 // phi node, we need to rewrite the phi node:
483 // * All the inputs which involve basic blocks OUTSIDE of this region go into
484 // a NEW phi node that takes care of finding which value really came in.
485 // The result of this phi is passed to the function as an argument.
487 // * All the other phi values stay.
489 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
490 // blocks moving to a new function.
491 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
492 // the values as parameters to the function
493 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot);
495 // Step 2: Construct new function based on inputs/outputs,
496 // Add allocas for all defs
497 Function *newFunction = constructFunction(inputs, outputs, code[0],
499 codeReplacer, oldFunction,
500 oldFunction->getParent());
502 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
504 moveCodeToFunction(newFunction);
506 // Loop over all of the PHI nodes in the entry block (code[0]), and change any
507 // references to the old incoming edge to be the new incoming edge.
508 for (BasicBlock::iterator I = code[0]->begin();
509 PHINode *PN = dyn_cast<PHINode>(I); ++I)
510 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
511 if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
512 PN->setIncomingBlock(i, newFuncRoot);
514 // Look at all successors of the codeReplacer block. If any of these blocks
515 // had PHI nodes in them, we need to update the "from" block to be the code
516 // replacer, not the original block in the extracted region.
517 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
518 succ_end(codeReplacer));
519 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
520 for (BasicBlock::iterator I = Succs[i]->begin();
521 PHINode *PN = dyn_cast<PHINode>(I); ++I)
522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
523 if (BlocksToExtract.count(PN->getIncomingBlock(i)))
524 PN->setIncomingBlock(i, codeReplacer);
527 DEBUG(if (verifyFunction(*newFunction)) abort());
531 bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
532 // Deny code region if it contains allocas
533 for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
535 for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
537 if (isa<AllocaInst>(*I))
543 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
546 Function* llvm::ExtractCodeRegion(DominatorSet &DS,
547 const std::vector<BasicBlock*> &code,
548 bool AggregateArgs) {
549 return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(code);
552 /// ExtractBasicBlock - slurp a natural loop into a brand new function
554 Function* llvm::ExtractLoop(DominatorSet &DS, Loop *L, bool AggregateArgs) {
555 return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(L->getBlocks());
558 /// ExtractBasicBlock - slurp a basic block into a brand new function
560 Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
561 std::vector<BasicBlock*> Blocks;
562 Blocks.push_back(BB);
563 return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);