4 #include "llvm/Transforms/Utils/CloneFunction.h"
5 #include "llvm/Function.h"
6 #include "llvm/BasicBlock.h"
7 #include "llvm/Instruction.h"
10 // FIXME: This should be merged with FunctionInlining
12 // RemapInstruction - Convert the instruction operands from referencing the
13 // current values into those specified by ValueMap.
15 static inline void RemapInstruction(Instruction *I,
16 std::map<const Value *, Value*> &ValueMap) {
17 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
18 const Value *Op = I->getOperand(op);
19 Value *V = ValueMap[Op];
20 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
21 continue; // Globals and constants don't get relocated
25 std::cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
26 std::cerr << "\nInst = " << I;
29 assert(V && "Referenced value not in value map!");
34 // Clone OldFunc into NewFunc, transforming the old arguments into references to
37 void CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
38 const std::vector<Value*> &ArgMap) {
39 assert(OldFunc->aempty() || !NewFunc->aempty() &&
40 "Synthesization of arguments is not implemented yet!");
41 assert(OldFunc->asize() == ArgMap.size() &&
42 "Improper number of argument values to map specified!");
44 // Keep a mapping between the original function's values and the new
45 // duplicated code's values. This includes all of: Function arguments,
46 // instruction values, constant pool entries, and basic blocks.
48 std::map<const Value *, Value*> ValueMap;
50 // Add all of the function arguments to the mapping...
52 for (Function::const_aiterator I = OldFunc->abegin(), E = OldFunc->aend();
54 ValueMap[I] = ArgMap[i];
57 // Loop over all of the basic blocks in the function, cloning them as
60 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
62 const BasicBlock &BB = *BI;
63 assert(BB.getTerminator() && "BasicBlock doesn't have terminator!?!?");
65 // Create a new basic block to copy instructions into!
66 BasicBlock *CBB = new BasicBlock(BB.getName(), NewFunc);
67 ValueMap[&BB] = CBB; // Add basic block mapping.
69 // Loop over all instructions copying them over...
70 for (BasicBlock::const_iterator II = BB.begin(), IE = BB.end();
72 Instruction *NewInst = II->clone();
73 NewInst->setName(II->getName()); // Name is not cloned...
74 CBB->getInstList().push_back(NewInst);
75 ValueMap[II] = NewInst; // Add instruction map to value.
79 // Loop over all of the instructions in the function, fixing up operand
80 // references as we go. This uses ValueMap to do all the hard work.
82 for (Function::const_iterator BB = OldFunc->begin(), BE = OldFunc->end();
84 BasicBlock *NBB = cast<BasicBlock>(ValueMap[BB]);
86 // Loop over all instructions, fixing each one as we find it...
87 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); ++II)
88 RemapInstruction(II, ValueMap);