787e0d3c8b662a24dbc02333d68bad3a3b2ee9ad
[oota-llvm.git] / lib / Transforms / Utils / CloneFunction.cpp
1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
2 //
3 // This file implements the CloneFunctionInto interface, which is used as the
4 // low-level function cloner.  This is used by the CloneFunction and function
5 // inliner to do the dirty work of copying the body of a function around.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Transforms/Utils/Cloning.h"
10 #include "llvm/iTerminators.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Function.h"
13 #include <map>
14
15 // RemapInstruction - Convert the instruction operands from referencing the 
16 // current values into those specified by ValueMap.
17 //
18 static inline void RemapInstruction(Instruction *I, 
19                                     std::map<const Value *, Value*> &ValueMap) {
20   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
21     const Value *Op = I->getOperand(op);
22     Value *V = ValueMap[Op];
23     if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
24       continue;  // Globals and constants don't get relocated
25
26 #ifndef NDEBUG
27     if (!V) {
28       std::cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
29       std::cerr << "\nInst = " << I;
30     }
31 #endif
32     assert(V && "Referenced value not in value map!");
33     I->setOperand(op, V);
34   }
35 }
36
37 // Clone OldFunc into NewFunc, transforming the old arguments into references to
38 // ArgMap values.
39 //
40 void CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
41                        std::map<const Value*, Value*> &ValueMap,
42                        std::vector<ReturnInst*> &Returns,
43                        const char *NameSuffix) {
44   assert(NameSuffix && "NameSuffix cannot be null!");
45   
46 #ifndef NDEBUG
47   for (Function::const_aiterator I = OldFunc->abegin(), E = OldFunc->aend();
48        I != E; ++I)
49     assert(ValueMap.count(I) && "No mapping from source argument specified!");
50 #endif
51
52   // Loop over all of the basic blocks in the function, cloning them as
53   // appropriate.  Note that we save BE this way in order to handle cloning of
54   // recursive functions into themselves.
55   //
56   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
57        BI != BE; ++BI) {
58     const BasicBlock &BB = *BI;
59     
60     // Create a new basic block to copy instructions into!
61     BasicBlock *CBB = new BasicBlock("", NewFunc);
62     if (BB.hasName()) CBB->setName(BB.getName()+NameSuffix);
63     ValueMap[&BB] = CBB;                       // Add basic block mapping.
64
65     // Loop over all instructions copying them over...
66     for (BasicBlock::const_iterator II = BB.begin(), IE = BB.end();
67          II != IE; ++II) {
68       Instruction *NewInst = II->clone();
69       if (II->hasName())
70         NewInst->setName(II->getName()+NameSuffix);     // Name is not cloned...
71       CBB->getInstList().push_back(NewInst);
72       ValueMap[II] = NewInst;                // Add instruction map to value.
73     }
74
75     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
76       Returns.push_back(RI);
77   }
78
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.
81   //
82   for (Function::const_iterator BB = OldFunc->begin(), BE = OldFunc->end();
83        BB != BE; ++BB) {
84     BasicBlock *NBB = cast<BasicBlock>(ValueMap[BB]);
85     
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);
89   }
90 }
91
92 /// CloneFunction - Return a copy of the specified function, but without
93 /// embedding the function into another module.  Also, any references specified
94 /// in the ValueMap are changed to refer to their mapped value instead of the
95 /// original one.  If any of the arguments to the function are in the ValueMap,
96 /// the arguments are deleted from the resultant function.  The ValueMap is
97 /// updated to include mappings from all of the instructions and basicblocks in
98 /// the function from their old to new values.
99 ///
100 Function *CloneFunction(const Function *F,
101                         std::map<const Value*, Value*> &ValueMap) {
102   std::vector<const Type*> ArgTypes;
103
104   // The user might be deleting arguments to the function by specifying them in
105   // the ValueMap.  If so, we need to not add the arguments to the arg ty vector
106   //
107   for (Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
108     if (ValueMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
109       ArgTypes.push_back(I->getType());
110
111   // Create a new function type...
112   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
113                                     ArgTypes, F->getFunctionType()->isVarArg());
114
115   // Create the new function...
116   Function *NewF = new Function(FTy, F->hasInternalLinkage(), F->getName());
117   
118   // Loop over the arguments, copying the names of the mapped arguments over...
119   Function::aiterator DestI = NewF->abegin();
120   for (Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
121     if (ValueMap.count(I)) {        // Is this argument preserved?
122       DestI->setName(I->getName()); // Copy the name over...
123       ValueMap[I] = DestI;          // Add mapping to ValueMap
124     }
125
126   std::vector<ReturnInst*> Returns;  // Ignore returns cloned...
127   CloneFunctionInto(NewF, F, ValueMap, Returns);
128   return NewF;                    
129 }