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