Factor code to copy global value attributes like
[oota-llvm.git] / lib / Transforms / Utils / CloneFunction.cpp
1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/Function.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Transforms/Utils/ValueMapper.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include <map>
28 using namespace llvm;
29
30 // CloneBasicBlock - See comments in Cloning.h
31 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
32                                   DenseMap<const Value*, Value*> &ValueMap,
33                                   const char *NameSuffix, Function *F,
34                                   ClonedCodeInfo *CodeInfo) {
35   BasicBlock *NewBB = BasicBlock::Create("", F);
36   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
37
38   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
39   
40   // Loop over all instructions, and copy them over.
41   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
42        II != IE; ++II) {
43     Instruction *NewInst = II->clone();
44     if (II->hasName())
45       NewInst->setName(II->getName()+NameSuffix);
46     NewBB->getInstList().push_back(NewInst);
47     ValueMap[II] = NewInst;                // Add instruction map to value.
48     
49     hasCalls |= isa<CallInst>(II);
50     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
51       if (isa<ConstantInt>(AI->getArraySize()))
52         hasStaticAllocas = true;
53       else
54         hasDynamicAllocas = true;
55     }
56   }
57   
58   if (CodeInfo) {
59     CodeInfo->ContainsCalls          |= hasCalls;
60     CodeInfo->ContainsUnwinds        |= isa<UnwindInst>(BB->getTerminator());
61     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
62     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 
63                                         BB != &BB->getParent()->getEntryBlock();
64   }
65   return NewBB;
66 }
67
68 // Clone OldFunc into NewFunc, transforming the old arguments into references to
69 // ArgMap values.
70 //
71 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
72                              DenseMap<const Value*, Value*> &ValueMap,
73                              std::vector<ReturnInst*> &Returns,
74                              const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
75   assert(NameSuffix && "NameSuffix cannot be null!");
76
77 #ifndef NDEBUG
78   for (Function::const_arg_iterator I = OldFunc->arg_begin(), 
79        E = OldFunc->arg_end(); I != E; ++I)
80     assert(ValueMap.count(I) && "No mapping from source argument specified!");
81 #endif
82
83   // Clone any attributes.
84   NewFunc->copyAttributesFrom(OldFunc);
85
86   // Loop over all of the basic blocks in the function, cloning them as
87   // appropriate.  Note that we save BE this way in order to handle cloning of
88   // recursive functions into themselves.
89   //
90   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
91        BI != BE; ++BI) {
92     const BasicBlock &BB = *BI;
93
94     // Create a new basic block and copy instructions into it!
95     BasicBlock *CBB = CloneBasicBlock(&BB, ValueMap, NameSuffix, NewFunc,
96                                       CodeInfo);
97     ValueMap[&BB] = CBB;                       // Add basic block mapping.
98
99     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
100       Returns.push_back(RI);
101   }
102
103   // Loop over all of the instructions in the function, fixing up operand
104   // references as we go.  This uses ValueMap to do all the hard work.
105   //
106   for (Function::iterator BB = cast<BasicBlock>(ValueMap[OldFunc->begin()]),
107          BE = NewFunc->end(); BB != BE; ++BB)
108     // Loop over all instructions, fixing each one as we find it...
109     for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
110       RemapInstruction(II, ValueMap);
111 }
112
113 /// CloneFunction - Return a copy of the specified function, but without
114 /// embedding the function into another module.  Also, any references specified
115 /// in the ValueMap are changed to refer to their mapped value instead of the
116 /// original one.  If any of the arguments to the function are in the ValueMap,
117 /// the arguments are deleted from the resultant function.  The ValueMap is
118 /// updated to include mappings from all of the instructions and basicblocks in
119 /// the function from their old to new values.
120 ///
121 Function *llvm::CloneFunction(const Function *F,
122                               DenseMap<const Value*, Value*> &ValueMap,
123                               ClonedCodeInfo *CodeInfo) {
124   std::vector<const Type*> ArgTypes;
125
126   // The user might be deleting arguments to the function by specifying them in
127   // the ValueMap.  If so, we need to not add the arguments to the arg ty vector
128   //
129   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
130        I != E; ++I)
131     if (ValueMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
132       ArgTypes.push_back(I->getType());
133
134   // Create a new function type...
135   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
136                                     ArgTypes, F->getFunctionType()->isVarArg());
137
138   // Create the new function...
139   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
140
141   // Loop over the arguments, copying the names of the mapped arguments over...
142   Function::arg_iterator DestI = NewF->arg_begin();
143   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
144        I != E; ++I)
145     if (ValueMap.count(I) == 0) {   // Is this argument preserved?
146       DestI->setName(I->getName()); // Copy the name over...
147       ValueMap[I] = DestI++;        // Add mapping to ValueMap
148     }
149
150   std::vector<ReturnInst*> Returns;  // Ignore returns cloned...
151   CloneFunctionInto(NewF, F, ValueMap, Returns, "", CodeInfo);
152   return NewF;
153 }
154
155
156
157 namespace {
158   /// PruningFunctionCloner - This class is a private class used to implement
159   /// the CloneAndPruneFunctionInto method.
160   struct VISIBILITY_HIDDEN PruningFunctionCloner {
161     Function *NewFunc;
162     const Function *OldFunc;
163     DenseMap<const Value*, Value*> &ValueMap;
164     std::vector<ReturnInst*> &Returns;
165     const char *NameSuffix;
166     ClonedCodeInfo *CodeInfo;
167     const TargetData *TD;
168
169   public:
170     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
171                           DenseMap<const Value*, Value*> &valueMap,
172                           std::vector<ReturnInst*> &returns,
173                           const char *nameSuffix, 
174                           ClonedCodeInfo *codeInfo,
175                           const TargetData *td)
176     : NewFunc(newFunc), OldFunc(oldFunc), ValueMap(valueMap), Returns(returns),
177       NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
178     }
179
180     /// CloneBlock - The specified block is found to be reachable, clone it and
181     /// anything that it can reach.
182     void CloneBlock(const BasicBlock *BB,
183                     std::vector<const BasicBlock*> &ToClone);
184     
185   public:
186     /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
187     /// mapping its operands through ValueMap if they are available.
188     Constant *ConstantFoldMappedInstruction(const Instruction *I);
189   };
190 }
191
192 /// CloneBlock - The specified block is found to be reachable, clone it and
193 /// anything that it can reach.
194 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
195                                        std::vector<const BasicBlock*> &ToClone){
196   Value *&BBEntry = ValueMap[BB];
197
198   // Have we already cloned this block?
199   if (BBEntry) return;
200   
201   // Nope, clone it now.
202   BasicBlock *NewBB;
203   BBEntry = NewBB = BasicBlock::Create();
204   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
205
206   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
207   
208   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
209   // loop doesn't include the terminator.
210   for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
211        II != IE; ++II) {
212     // If this instruction constant folds, don't bother cloning the instruction,
213     // instead, just add the constant to the value map.
214     if (Constant *C = ConstantFoldMappedInstruction(II)) {
215       ValueMap[II] = C;
216       continue;
217     }
218     
219     Instruction *NewInst = II->clone();
220     if (II->hasName())
221       NewInst->setName(II->getName()+NameSuffix);
222     NewBB->getInstList().push_back(NewInst);
223     ValueMap[II] = NewInst;                // Add instruction map to value.
224     
225     hasCalls |= isa<CallInst>(II);
226     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
227       if (isa<ConstantInt>(AI->getArraySize()))
228         hasStaticAllocas = true;
229       else
230         hasDynamicAllocas = true;
231     }
232   }
233   
234   // Finally, clone over the terminator.
235   const TerminatorInst *OldTI = BB->getTerminator();
236   bool TerminatorDone = false;
237   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
238     if (BI->isConditional()) {
239       // If the condition was a known constant in the callee...
240       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
241       // Or is a known constant in the caller...
242       if (Cond == 0)  
243         Cond = dyn_cast_or_null<ConstantInt>(ValueMap[BI->getCondition()]);
244
245       // Constant fold to uncond branch!
246       if (Cond) {
247         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
248         ValueMap[OldTI] = BranchInst::Create(Dest, NewBB);
249         ToClone.push_back(Dest);
250         TerminatorDone = true;
251       }
252     }
253   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
254     // If switching on a value known constant in the caller.
255     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
256     if (Cond == 0)  // Or known constant after constant prop in the callee...
257       Cond = dyn_cast_or_null<ConstantInt>(ValueMap[SI->getCondition()]);
258     if (Cond) {     // Constant fold to uncond branch!
259       BasicBlock *Dest = SI->getSuccessor(SI->findCaseValue(Cond));
260       ValueMap[OldTI] = BranchInst::Create(Dest, NewBB);
261       ToClone.push_back(Dest);
262       TerminatorDone = true;
263     }
264   }
265   
266   if (!TerminatorDone) {
267     Instruction *NewInst = OldTI->clone();
268     if (OldTI->hasName())
269       NewInst->setName(OldTI->getName()+NameSuffix);
270     NewBB->getInstList().push_back(NewInst);
271     ValueMap[OldTI] = NewInst;             // Add instruction map to value.
272     
273     // Recursively clone any reachable successor blocks.
274     const TerminatorInst *TI = BB->getTerminator();
275     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
276       ToClone.push_back(TI->getSuccessor(i));
277   }
278   
279   if (CodeInfo) {
280     CodeInfo->ContainsCalls          |= hasCalls;
281     CodeInfo->ContainsUnwinds        |= isa<UnwindInst>(OldTI);
282     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
283     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 
284       BB != &BB->getParent()->front();
285   }
286   
287   if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
288     Returns.push_back(RI);
289 }
290
291 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
292 /// mapping its operands through ValueMap if they are available.
293 Constant *PruningFunctionCloner::
294 ConstantFoldMappedInstruction(const Instruction *I) {
295   SmallVector<Constant*, 8> Ops;
296   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
297     if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
298                                                            ValueMap)))
299       Ops.push_back(Op);
300     else
301       return 0;  // All operands not constant!
302
303   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
304     return ConstantFoldCompareInstOperands(CI->getPredicate(),
305                                            &Ops[0], Ops.size(), TD);
306
307   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
308     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
309       if (!LI->isVolatile() && CE->getOpcode() == Instruction::GetElementPtr)
310         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
311           if (GV->isConstant() && !GV->isDeclaration())
312             return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(),
313                                                           CE);
314
315   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), &Ops[0],
316                                   Ops.size(), TD);
317 }
318
319 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
320 /// except that it does some simple constant prop and DCE on the fly.  The
321 /// effect of this is to copy significantly less code in cases where (for
322 /// example) a function call with constant arguments is inlined, and those
323 /// constant arguments cause a significant amount of code in the callee to be
324 /// dead.  Since this doesn't produce an exact copy of the input, it can't be
325 /// used for things like CloneFunction or CloneModule.
326 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
327                                      DenseMap<const Value*, Value*> &ValueMap,
328                                      std::vector<ReturnInst*> &Returns,
329                                      const char *NameSuffix, 
330                                      ClonedCodeInfo *CodeInfo,
331                                      const TargetData *TD) {
332   assert(NameSuffix && "NameSuffix cannot be null!");
333   
334 #ifndef NDEBUG
335   for (Function::const_arg_iterator II = OldFunc->arg_begin(), 
336        E = OldFunc->arg_end(); II != E; ++II)
337     assert(ValueMap.count(II) && "No mapping from source argument specified!");
338 #endif
339
340   PruningFunctionCloner PFC(NewFunc, OldFunc, ValueMap, Returns,
341                             NameSuffix, CodeInfo, TD);
342
343   // Clone the entry block, and anything recursively reachable from it.
344   std::vector<const BasicBlock*> CloneWorklist;
345   CloneWorklist.push_back(&OldFunc->getEntryBlock());
346   while (!CloneWorklist.empty()) {
347     const BasicBlock *BB = CloneWorklist.back();
348     CloneWorklist.pop_back();
349     PFC.CloneBlock(BB, CloneWorklist);
350   }
351   
352   // Loop over all of the basic blocks in the old function.  If the block was
353   // reachable, we have cloned it and the old block is now in the value map:
354   // insert it into the new function in the right order.  If not, ignore it.
355   //
356   // Defer PHI resolution until rest of function is resolved.
357   std::vector<const PHINode*> PHIToResolve;
358   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
359        BI != BE; ++BI) {
360     BasicBlock *NewBB = cast_or_null<BasicBlock>(ValueMap[BI]);
361     if (NewBB == 0) continue;  // Dead block.
362
363     // Add the new block to the new function.
364     NewFunc->getBasicBlockList().push_back(NewBB);
365     
366     // Loop over all of the instructions in the block, fixing up operand
367     // references as we go.  This uses ValueMap to do all the hard work.
368     //
369     BasicBlock::iterator I = NewBB->begin();
370     
371     // Handle PHI nodes specially, as we have to remove references to dead
372     // blocks.
373     if (PHINode *PN = dyn_cast<PHINode>(I)) {
374       // Skip over all PHI nodes, remembering them for later.
375       BasicBlock::const_iterator OldI = BI->begin();
376       for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI)
377         PHIToResolve.push_back(cast<PHINode>(OldI));
378     }
379     
380     // Otherwise, remap the rest of the instructions normally.
381     for (; I != NewBB->end(); ++I)
382       RemapInstruction(I, ValueMap);
383   }
384   
385   // Defer PHI resolution until rest of function is resolved, PHI resolution
386   // requires the CFG to be up-to-date.
387   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
388     const PHINode *OPN = PHIToResolve[phino];
389     unsigned NumPreds = OPN->getNumIncomingValues();
390     const BasicBlock *OldBB = OPN->getParent();
391     BasicBlock *NewBB = cast<BasicBlock>(ValueMap[OldBB]);
392
393     // Map operands for blocks that are live and remove operands for blocks
394     // that are dead.
395     for (; phino != PHIToResolve.size() &&
396          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
397       OPN = PHIToResolve[phino];
398       PHINode *PN = cast<PHINode>(ValueMap[OPN]);
399       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
400         if (BasicBlock *MappedBlock = 
401             cast_or_null<BasicBlock>(ValueMap[PN->getIncomingBlock(pred)])) {
402           Value *InVal = MapValue(PN->getIncomingValue(pred), ValueMap);
403           assert(InVal && "Unknown input value?");
404           PN->setIncomingValue(pred, InVal);
405           PN->setIncomingBlock(pred, MappedBlock);
406         } else {
407           PN->removeIncomingValue(pred, false);
408           --pred, --e;  // Revisit the next entry.
409         }
410       } 
411     }
412     
413     // The loop above has removed PHI entries for those blocks that are dead
414     // and has updated others.  However, if a block is live (i.e. copied over)
415     // but its terminator has been changed to not go to this block, then our
416     // phi nodes will have invalid entries.  Update the PHI nodes in this
417     // case.
418     PHINode *PN = cast<PHINode>(NewBB->begin());
419     NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
420     if (NumPreds != PN->getNumIncomingValues()) {
421       assert(NumPreds < PN->getNumIncomingValues());
422       // Count how many times each predecessor comes to this block.
423       std::map<BasicBlock*, unsigned> PredCount;
424       for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
425            PI != E; ++PI)
426         --PredCount[*PI];
427       
428       // Figure out how many entries to remove from each PHI.
429       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
430         ++PredCount[PN->getIncomingBlock(i)];
431       
432       // At this point, the excess predecessor entries are positive in the
433       // map.  Loop over all of the PHIs and remove excess predecessor
434       // entries.
435       BasicBlock::iterator I = NewBB->begin();
436       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
437         for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
438              E = PredCount.end(); PCI != E; ++PCI) {
439           BasicBlock *Pred     = PCI->first;
440           for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
441             PN->removeIncomingValue(Pred, false);
442         }
443       }
444     }
445     
446     // If the loops above have made these phi nodes have 0 or 1 operand,
447     // replace them with undef or the input value.  We must do this for
448     // correctness, because 0-operand phis are not valid.
449     PN = cast<PHINode>(NewBB->begin());
450     if (PN->getNumIncomingValues() == 0) {
451       BasicBlock::iterator I = NewBB->begin();
452       BasicBlock::const_iterator OldI = OldBB->begin();
453       while ((PN = dyn_cast<PHINode>(I++))) {
454         Value *NV = UndefValue::get(PN->getType());
455         PN->replaceAllUsesWith(NV);
456         assert(ValueMap[OldI] == PN && "ValueMap mismatch");
457         ValueMap[OldI] = NV;
458         PN->eraseFromParent();
459         ++OldI;
460       }
461     }
462     // NOTE: We cannot eliminate single entry phi nodes here, because of
463     // ValueMap.  Single entry phi nodes can have multiple ValueMap entries
464     // pointing at them.  Thus, deleting one would require scanning the ValueMap
465     // to update any entries in it that would require that.  This would be
466     // really slow.
467   }
468   
469   // Now that the inlined function body has been fully constructed, go through
470   // and zap unconditional fall-through branches.  This happen all the time when
471   // specializing code: code specialization turns conditional branches into
472   // uncond branches, and this code folds them.
473   Function::iterator I = cast<BasicBlock>(ValueMap[&OldFunc->getEntryBlock()]);
474   while (I != NewFunc->end()) {
475     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
476     if (!BI || BI->isConditional()) { ++I; continue; }
477     
478     // Note that we can't eliminate uncond branches if the destination has
479     // single-entry PHI nodes.  Eliminating the single-entry phi nodes would
480     // require scanning the ValueMap to update any entries that point to the phi
481     // node.
482     BasicBlock *Dest = BI->getSuccessor(0);
483     if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
484       ++I; continue;
485     }
486     
487     // We know all single-entry PHI nodes in the inlined function have been
488     // removed, so we just need to splice the blocks.
489     BI->eraseFromParent();
490     
491     // Move all the instructions in the succ to the pred.
492     I->getInstList().splice(I->end(), Dest->getInstList());
493     
494     // Make all PHI nodes that referred to Dest now refer to I as their source.
495     Dest->replaceAllUsesWith(I);
496
497     // Remove the dest block.
498     Dest->eraseFromParent();
499     
500     // Do not increment I, iteratively merge all things this block branches to.
501   }
502 }