1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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/IntrinsicInst.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Function.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Metadata.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Transforms/Utils/ValueMapper.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/DebugInfo.h"
29 #include "llvm/ADT/SmallVector.h"
33 // CloneBasicBlock - See comments in Cloning.h
34 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
35 ValueToValueMapTy &VMap,
36 const Twine &NameSuffix, Function *F,
37 ClonedCodeInfo *CodeInfo) {
38 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
39 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
41 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
43 // Loop over all instructions, and copy them over.
44 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
46 Instruction *NewInst = II->clone();
48 NewInst->setName(II->getName()+NameSuffix);
49 NewBB->getInstList().push_back(NewInst);
50 VMap[II] = NewInst; // Add instruction map to value.
52 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
53 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
54 if (isa<ConstantInt>(AI->getArraySize()))
55 hasStaticAllocas = true;
57 hasDynamicAllocas = true;
62 CodeInfo->ContainsCalls |= hasCalls;
63 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
64 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
65 BB != &BB->getParent()->getEntryBlock();
70 // Clone OldFunc into NewFunc, transforming the old arguments into references to
73 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
74 ValueToValueMapTy &VMap,
75 bool ModuleLevelChanges,
76 SmallVectorImpl<ReturnInst*> &Returns,
77 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
78 ValueMapTypeRemapper *TypeMapper) {
79 assert(NameSuffix && "NameSuffix cannot be null!");
82 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
83 E = OldFunc->arg_end(); I != E; ++I)
84 assert(VMap.count(I) && "No mapping from source argument specified!");
87 // Clone any attributes.
88 if (NewFunc->arg_size() == OldFunc->arg_size())
89 NewFunc->copyAttributesFrom(OldFunc);
91 //Some arguments were deleted with the VMap. Copy arguments one by one
92 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
93 E = OldFunc->arg_end(); I != E; ++I)
94 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
95 Anew->addAttr( OldFunc->getAttributes()
96 .getParamAttributes(I->getArgNo() + 1));
97 NewFunc->setAttributes(NewFunc->getAttributes()
98 .addAttr(0, OldFunc->getAttributes()
99 .getRetAttributes()));
100 NewFunc->setAttributes(NewFunc->getAttributes()
101 .addAttr(~0, OldFunc->getAttributes()
102 .getFnAttributes()));
106 // Loop over all of the basic blocks in the function, cloning them as
107 // appropriate. Note that we save BE this way in order to handle cloning of
108 // recursive functions into themselves.
110 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
112 const BasicBlock &BB = *BI;
114 // Create a new basic block and copy instructions into it!
115 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
117 // Add basic block mapping.
120 // It is only legal to clone a function if a block address within that
121 // function is never referenced outside of the function. Given that, we
122 // want to map block addresses from the old function to block addresses in
123 // the clone. (This is different from the generic ValueMapper
124 // implementation, which generates an invalid blockaddress when
125 // cloning a function.)
126 if (BB.hasAddressTaken()) {
127 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
128 const_cast<BasicBlock*>(&BB));
129 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
132 // Note return instructions for the caller.
133 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
134 Returns.push_back(RI);
137 // Loop over all of the instructions in the function, fixing up operand
138 // references as we go. This uses VMap to do all the hard work.
139 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
140 BE = NewFunc->end(); BB != BE; ++BB)
141 // Loop over all instructions, fixing each one as we find it...
142 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
143 RemapInstruction(II, VMap,
144 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
148 /// CloneFunction - Return a copy of the specified function, but without
149 /// embedding the function into another module. Also, any references specified
150 /// in the VMap are changed to refer to their mapped value instead of the
151 /// original one. If any of the arguments to the function are in the VMap,
152 /// the arguments are deleted from the resultant function. The VMap is
153 /// updated to include mappings from all of the instructions and basicblocks in
154 /// the function from their old to new values.
156 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
157 bool ModuleLevelChanges,
158 ClonedCodeInfo *CodeInfo) {
159 std::vector<Type*> ArgTypes;
161 // The user might be deleting arguments to the function by specifying them in
162 // the VMap. If so, we need to not add the arguments to the arg ty vector
164 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
166 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
167 ArgTypes.push_back(I->getType());
169 // Create a new function type...
170 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
171 ArgTypes, F->getFunctionType()->isVarArg());
173 // Create the new function...
174 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
176 // Loop over the arguments, copying the names of the mapped arguments over...
177 Function::arg_iterator DestI = NewF->arg_begin();
178 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
180 if (VMap.count(I) == 0) { // Is this argument preserved?
181 DestI->setName(I->getName()); // Copy the name over...
182 VMap[I] = DestI++; // Add mapping to VMap
185 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
186 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
193 /// PruningFunctionCloner - This class is a private class used to implement
194 /// the CloneAndPruneFunctionInto method.
195 struct PruningFunctionCloner {
197 const Function *OldFunc;
198 ValueToValueMapTy &VMap;
199 bool ModuleLevelChanges;
200 SmallVectorImpl<ReturnInst*> &Returns;
201 const char *NameSuffix;
202 ClonedCodeInfo *CodeInfo;
203 const TargetData *TD;
205 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
206 ValueToValueMapTy &valueMap,
207 bool moduleLevelChanges,
208 SmallVectorImpl<ReturnInst*> &returns,
209 const char *nameSuffix,
210 ClonedCodeInfo *codeInfo,
211 const TargetData *td)
212 : NewFunc(newFunc), OldFunc(oldFunc),
213 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
214 Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
217 /// CloneBlock - The specified block is found to be reachable, clone it and
218 /// anything that it can reach.
219 void CloneBlock(const BasicBlock *BB,
220 std::vector<const BasicBlock*> &ToClone);
223 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
224 /// mapping its operands through VMap if they are available.
225 Constant *ConstantFoldMappedInstruction(const Instruction *I);
229 /// CloneBlock - The specified block is found to be reachable, clone it and
230 /// anything that it can reach.
231 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
232 std::vector<const BasicBlock*> &ToClone){
233 TrackingVH<Value> &BBEntry = VMap[BB];
235 // Have we already cloned this block?
238 // Nope, clone it now.
240 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
241 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
243 // It is only legal to clone a function if a block address within that
244 // function is never referenced outside of the function. Given that, we
245 // want to map block addresses from the old function to block addresses in
246 // the clone. (This is different from the generic ValueMapper
247 // implementation, which generates an invalid blockaddress when
248 // cloning a function.)
250 // Note that we don't need to fix the mapping for unreachable blocks;
251 // the default mapping there is safe.
252 if (BB->hasAddressTaken()) {
253 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
254 const_cast<BasicBlock*>(BB));
255 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
259 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
261 // Loop over all instructions, and copy them over, DCE'ing as we go. This
262 // loop doesn't include the terminator.
263 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
265 // If this instruction constant folds, don't bother cloning the instruction,
266 // instead, just add the constant to the value map.
267 if (Constant *C = ConstantFoldMappedInstruction(II)) {
272 Instruction *NewInst = II->clone();
274 NewInst->setName(II->getName()+NameSuffix);
275 NewBB->getInstList().push_back(NewInst);
276 VMap[II] = NewInst; // Add instruction map to value.
278 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
279 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
280 if (isa<ConstantInt>(AI->getArraySize()))
281 hasStaticAllocas = true;
283 hasDynamicAllocas = true;
287 // Finally, clone over the terminator.
288 const TerminatorInst *OldTI = BB->getTerminator();
289 bool TerminatorDone = false;
290 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
291 if (BI->isConditional()) {
292 // If the condition was a known constant in the callee...
293 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
294 // Or is a known constant in the caller...
296 Value *V = VMap[BI->getCondition()];
297 Cond = dyn_cast_or_null<ConstantInt>(V);
300 // Constant fold to uncond branch!
302 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
303 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
304 ToClone.push_back(Dest);
305 TerminatorDone = true;
308 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
309 // If switching on a value known constant in the caller.
310 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
311 if (Cond == 0) { // Or known constant after constant prop in the callee...
312 Value *V = VMap[SI->getCondition()];
313 Cond = dyn_cast_or_null<ConstantInt>(V);
315 if (Cond) { // Constant fold to uncond branch!
316 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
317 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
318 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
319 ToClone.push_back(Dest);
320 TerminatorDone = true;
324 if (!TerminatorDone) {
325 Instruction *NewInst = OldTI->clone();
326 if (OldTI->hasName())
327 NewInst->setName(OldTI->getName()+NameSuffix);
328 NewBB->getInstList().push_back(NewInst);
329 VMap[OldTI] = NewInst; // Add instruction map to value.
331 // Recursively clone any reachable successor blocks.
332 const TerminatorInst *TI = BB->getTerminator();
333 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
334 ToClone.push_back(TI->getSuccessor(i));
338 CodeInfo->ContainsCalls |= hasCalls;
339 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
340 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
341 BB != &BB->getParent()->front();
344 if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
345 Returns.push_back(RI);
348 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
349 /// mapping its operands through VMap if they are available.
350 Constant *PruningFunctionCloner::
351 ConstantFoldMappedInstruction(const Instruction *I) {
352 SmallVector<Constant*, 8> Ops;
353 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
354 if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
356 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges)))
359 return 0; // All operands not constant!
361 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
362 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
365 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
366 if (!LI->isVolatile())
367 return ConstantFoldLoadFromConstPtr(Ops[0], TD);
369 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
372 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
373 /// except that it does some simple constant prop and DCE on the fly. The
374 /// effect of this is to copy significantly less code in cases where (for
375 /// example) a function call with constant arguments is inlined, and those
376 /// constant arguments cause a significant amount of code in the callee to be
377 /// dead. Since this doesn't produce an exact copy of the input, it can't be
378 /// used for things like CloneFunction or CloneModule.
379 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
380 ValueToValueMapTy &VMap,
381 bool ModuleLevelChanges,
382 SmallVectorImpl<ReturnInst*> &Returns,
383 const char *NameSuffix,
384 ClonedCodeInfo *CodeInfo,
385 const TargetData *TD,
386 Instruction *TheCall) {
387 assert(NameSuffix && "NameSuffix cannot be null!");
390 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
391 E = OldFunc->arg_end(); II != E; ++II)
392 assert(VMap.count(II) && "No mapping from source argument specified!");
395 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
396 Returns, NameSuffix, CodeInfo, TD);
398 // Clone the entry block, and anything recursively reachable from it.
399 std::vector<const BasicBlock*> CloneWorklist;
400 CloneWorklist.push_back(&OldFunc->getEntryBlock());
401 while (!CloneWorklist.empty()) {
402 const BasicBlock *BB = CloneWorklist.back();
403 CloneWorklist.pop_back();
404 PFC.CloneBlock(BB, CloneWorklist);
407 // Loop over all of the basic blocks in the old function. If the block was
408 // reachable, we have cloned it and the old block is now in the value map:
409 // insert it into the new function in the right order. If not, ignore it.
411 // Defer PHI resolution until rest of function is resolved.
412 SmallVector<const PHINode*, 16> PHIToResolve;
413 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
416 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
417 if (NewBB == 0) continue; // Dead block.
419 // Add the new block to the new function.
420 NewFunc->getBasicBlockList().push_back(NewBB);
422 // Loop over all of the instructions in the block, fixing up operand
423 // references as we go. This uses VMap to do all the hard work.
425 BasicBlock::iterator I = NewBB->begin();
427 // Handle PHI nodes specially, as we have to remove references to dead
429 if (PHINode *PN = dyn_cast<PHINode>(I)) {
430 // Skip over all PHI nodes, remembering them for later.
431 BasicBlock::const_iterator OldI = BI->begin();
432 for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI)
433 PHIToResolve.push_back(cast<PHINode>(OldI));
436 // Otherwise, remap the rest of the instructions normally.
437 for (; I != NewBB->end(); ++I)
438 RemapInstruction(I, VMap,
439 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
442 // Defer PHI resolution until rest of function is resolved, PHI resolution
443 // requires the CFG to be up-to-date.
444 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
445 const PHINode *OPN = PHIToResolve[phino];
446 unsigned NumPreds = OPN->getNumIncomingValues();
447 const BasicBlock *OldBB = OPN->getParent();
448 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
450 // Map operands for blocks that are live and remove operands for blocks
452 for (; phino != PHIToResolve.size() &&
453 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
454 OPN = PHIToResolve[phino];
455 PHINode *PN = cast<PHINode>(VMap[OPN]);
456 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
457 Value *V = VMap[PN->getIncomingBlock(pred)];
458 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
459 Value *InVal = MapValue(PN->getIncomingValue(pred),
461 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
462 assert(InVal && "Unknown input value?");
463 PN->setIncomingValue(pred, InVal);
464 PN->setIncomingBlock(pred, MappedBlock);
466 PN->removeIncomingValue(pred, false);
467 --pred, --e; // Revisit the next entry.
472 // The loop above has removed PHI entries for those blocks that are dead
473 // and has updated others. However, if a block is live (i.e. copied over)
474 // but its terminator has been changed to not go to this block, then our
475 // phi nodes will have invalid entries. Update the PHI nodes in this
477 PHINode *PN = cast<PHINode>(NewBB->begin());
478 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
479 if (NumPreds != PN->getNumIncomingValues()) {
480 assert(NumPreds < PN->getNumIncomingValues());
481 // Count how many times each predecessor comes to this block.
482 std::map<BasicBlock*, unsigned> PredCount;
483 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
487 // Figure out how many entries to remove from each PHI.
488 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
489 ++PredCount[PN->getIncomingBlock(i)];
491 // At this point, the excess predecessor entries are positive in the
492 // map. Loop over all of the PHIs and remove excess predecessor
494 BasicBlock::iterator I = NewBB->begin();
495 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
496 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
497 E = PredCount.end(); PCI != E; ++PCI) {
498 BasicBlock *Pred = PCI->first;
499 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
500 PN->removeIncomingValue(Pred, false);
505 // If the loops above have made these phi nodes have 0 or 1 operand,
506 // replace them with undef or the input value. We must do this for
507 // correctness, because 0-operand phis are not valid.
508 PN = cast<PHINode>(NewBB->begin());
509 if (PN->getNumIncomingValues() == 0) {
510 BasicBlock::iterator I = NewBB->begin();
511 BasicBlock::const_iterator OldI = OldBB->begin();
512 while ((PN = dyn_cast<PHINode>(I++))) {
513 Value *NV = UndefValue::get(PN->getType());
514 PN->replaceAllUsesWith(NV);
515 assert(VMap[OldI] == PN && "VMap mismatch");
517 PN->eraseFromParent();
521 // NOTE: We cannot eliminate single entry phi nodes here, because of
522 // VMap. Single entry phi nodes can have multiple VMap entries
523 // pointing at them. Thus, deleting one would require scanning the VMap
524 // to update any entries in it that would require that. This would be
528 // Now that the inlined function body has been fully constructed, go through
529 // and zap unconditional fall-through branches. This happen all the time when
530 // specializing code: code specialization turns conditional branches into
531 // uncond branches, and this code folds them.
532 Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
533 while (I != NewFunc->end()) {
534 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
535 if (!BI || BI->isConditional()) { ++I; continue; }
537 // Note that we can't eliminate uncond branches if the destination has
538 // single-entry PHI nodes. Eliminating the single-entry phi nodes would
539 // require scanning the VMap to update any entries that point to the phi
541 BasicBlock *Dest = BI->getSuccessor(0);
542 if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
546 // We know all single-entry PHI nodes in the inlined function have been
547 // removed, so we just need to splice the blocks.
548 BI->eraseFromParent();
550 // Make all PHI nodes that referred to Dest now refer to I as their source.
551 Dest->replaceAllUsesWith(I);
553 // Move all the instructions in the succ to the pred.
554 I->getInstList().splice(I->end(), Dest->getInstList());
556 // Remove the dest block.
557 Dest->eraseFromParent();
559 // Do not increment I, iteratively merge all things this block branches to.