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/InstructionSimplify.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/ADT/SmallVector.h"
34 // CloneBasicBlock - See comments in Cloning.h
35 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
36 ValueToValueMapTy &VMap,
37 const Twine &NameSuffix, Function *F,
38 ClonedCodeInfo *CodeInfo) {
39 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
40 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
42 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
44 // Loop over all instructions, and copy them over.
45 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
47 Instruction *NewInst = II->clone();
49 NewInst->setName(II->getName()+NameSuffix);
50 NewBB->getInstList().push_back(NewInst);
51 VMap[II] = NewInst; // Add instruction map to value.
53 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
54 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
55 if (isa<ConstantInt>(AI->getArraySize()))
56 hasStaticAllocas = true;
58 hasDynamicAllocas = true;
63 CodeInfo->ContainsCalls |= hasCalls;
64 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
65 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
66 BB != &BB->getParent()->getEntryBlock();
71 // Clone OldFunc into NewFunc, transforming the old arguments into references to
74 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
75 ValueToValueMapTy &VMap,
76 bool ModuleLevelChanges,
77 SmallVectorImpl<ReturnInst*> &Returns,
78 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
79 ValueMapTypeRemapper *TypeMapper) {
80 assert(NameSuffix && "NameSuffix cannot be null!");
83 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
84 E = OldFunc->arg_end(); I != E; ++I)
85 assert(VMap.count(I) && "No mapping from source argument specified!");
88 // Clone any attributes.
89 if (NewFunc->arg_size() == OldFunc->arg_size())
90 NewFunc->copyAttributesFrom(OldFunc);
92 //Some arguments were deleted with the VMap. Copy arguments one by one
93 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
94 E = OldFunc->arg_end(); I != E; ++I)
95 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
96 Anew->addAttr( OldFunc->getAttributes()
97 .getParamAttributes(I->getArgNo() + 1));
98 NewFunc->setAttributes(NewFunc->getAttributes()
99 .addAttr(0, OldFunc->getAttributes()
100 .getRetAttributes()));
101 NewFunc->setAttributes(NewFunc->getAttributes()
102 .addAttr(~0, OldFunc->getAttributes()
103 .getFnAttributes()));
107 // Loop over all of the basic blocks in the function, cloning them as
108 // appropriate. Note that we save BE this way in order to handle cloning of
109 // recursive functions into themselves.
111 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
113 const BasicBlock &BB = *BI;
115 // Create a new basic block and copy instructions into it!
116 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
118 // Add basic block mapping.
121 // It is only legal to clone a function if a block address within that
122 // function is never referenced outside of the function. Given that, we
123 // want to map block addresses from the old function to block addresses in
124 // the clone. (This is different from the generic ValueMapper
125 // implementation, which generates an invalid blockaddress when
126 // cloning a function.)
127 if (BB.hasAddressTaken()) {
128 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
129 const_cast<BasicBlock*>(&BB));
130 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
133 // Note return instructions for the caller.
134 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
135 Returns.push_back(RI);
138 // Loop over all of the instructions in the function, fixing up operand
139 // references as we go. This uses VMap to do all the hard work.
140 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
141 BE = NewFunc->end(); BB != BE; ++BB)
142 // Loop over all instructions, fixing each one as we find it...
143 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
144 RemapInstruction(II, VMap,
145 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
149 /// CloneFunction - Return a copy of the specified function, but without
150 /// embedding the function into another module. Also, any references specified
151 /// in the VMap are changed to refer to their mapped value instead of the
152 /// original one. If any of the arguments to the function are in the VMap,
153 /// the arguments are deleted from the resultant function. The VMap is
154 /// updated to include mappings from all of the instructions and basicblocks in
155 /// the function from their old to new values.
157 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
158 bool ModuleLevelChanges,
159 ClonedCodeInfo *CodeInfo) {
160 std::vector<Type*> ArgTypes;
162 // The user might be deleting arguments to the function by specifying them in
163 // the VMap. If so, we need to not add the arguments to the arg ty vector
165 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
167 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
168 ArgTypes.push_back(I->getType());
170 // Create a new function type...
171 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
172 ArgTypes, F->getFunctionType()->isVarArg());
174 // Create the new function...
175 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
177 // Loop over the arguments, copying the names of the mapped arguments over...
178 Function::arg_iterator DestI = NewF->arg_begin();
179 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
181 if (VMap.count(I) == 0) { // Is this argument preserved?
182 DestI->setName(I->getName()); // Copy the name over...
183 VMap[I] = DestI++; // Add mapping to VMap
186 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
187 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
194 /// PruningFunctionCloner - This class is a private class used to implement
195 /// the CloneAndPruneFunctionInto method.
196 struct PruningFunctionCloner {
198 const Function *OldFunc;
199 ValueToValueMapTy &VMap;
200 bool ModuleLevelChanges;
201 SmallVectorImpl<ReturnInst*> &Returns;
202 const char *NameSuffix;
203 ClonedCodeInfo *CodeInfo;
204 const TargetData *TD;
206 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
207 ValueToValueMapTy &valueMap,
208 bool moduleLevelChanges,
209 SmallVectorImpl<ReturnInst*> &returns,
210 const char *nameSuffix,
211 ClonedCodeInfo *codeInfo,
212 const TargetData *td)
213 : NewFunc(newFunc), OldFunc(oldFunc),
214 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
215 Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
218 /// CloneBlock - The specified block is found to be reachable, clone it and
219 /// anything that it can reach.
220 void CloneBlock(const BasicBlock *BB,
221 std::vector<const BasicBlock*> &ToClone);
225 /// CloneBlock - The specified block is found to be reachable, clone it and
226 /// anything that it can reach.
227 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
228 std::vector<const BasicBlock*> &ToClone){
229 TrackingVH<Value> &BBEntry = VMap[BB];
231 // Have we already cloned this block?
234 // Nope, clone it now.
236 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
237 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
239 // It is only legal to clone a function if a block address within that
240 // function is never referenced outside of the function. Given that, we
241 // want to map block addresses from the old function to block addresses in
242 // the clone. (This is different from the generic ValueMapper
243 // implementation, which generates an invalid blockaddress when
244 // cloning a function.)
246 // Note that we don't need to fix the mapping for unreachable blocks;
247 // the default mapping there is safe.
248 if (BB->hasAddressTaken()) {
249 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
250 const_cast<BasicBlock*>(BB));
251 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
255 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
257 // Loop over all instructions, and copy them over, DCE'ing as we go. This
258 // loop doesn't include the terminator.
259 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
261 Instruction *NewInst = II->clone();
263 // Eagerly remap operands to the newly cloned instruction, except for PHI
264 // nodes for which we defer processing until we update the CFG.
265 if (!isa<PHINode>(NewInst)) {
266 RemapInstruction(NewInst, VMap,
267 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
269 // If we can simplify this instruction to some other value, simply add
270 // a mapping to that value rather than inserting a new instruction into
272 if (Value *V = SimplifyInstruction(NewInst, TD)) {
273 // On the off-chance that this simplifies to an instruction in the old
274 // function, map it back into the new function.
275 if (Value *MappedV = VMap.lookup(V))
285 NewInst->setName(II->getName()+NameSuffix);
286 VMap[II] = NewInst; // Add instruction map to value.
287 NewBB->getInstList().push_back(NewInst);
288 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
289 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
290 if (isa<ConstantInt>(AI->getArraySize()))
291 hasStaticAllocas = true;
293 hasDynamicAllocas = true;
297 // Finally, clone over the terminator.
298 const TerminatorInst *OldTI = BB->getTerminator();
299 bool TerminatorDone = false;
300 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
301 if (BI->isConditional()) {
302 // If the condition was a known constant in the callee...
303 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
304 // Or is a known constant in the caller...
306 Value *V = VMap[BI->getCondition()];
307 Cond = dyn_cast_or_null<ConstantInt>(V);
310 // Constant fold to uncond branch!
312 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
313 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
314 ToClone.push_back(Dest);
315 TerminatorDone = true;
318 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
319 // If switching on a value known constant in the caller.
320 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
321 if (Cond == 0) { // Or known constant after constant prop in the callee...
322 Value *V = VMap[SI->getCondition()];
323 Cond = dyn_cast_or_null<ConstantInt>(V);
325 if (Cond) { // Constant fold to uncond branch!
326 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
327 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
328 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
329 ToClone.push_back(Dest);
330 TerminatorDone = true;
334 if (!TerminatorDone) {
335 Instruction *NewInst = OldTI->clone();
336 if (OldTI->hasName())
337 NewInst->setName(OldTI->getName()+NameSuffix);
338 NewBB->getInstList().push_back(NewInst);
339 VMap[OldTI] = NewInst; // Add instruction map to value.
341 // Recursively clone any reachable successor blocks.
342 const TerminatorInst *TI = BB->getTerminator();
343 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
344 ToClone.push_back(TI->getSuccessor(i));
348 CodeInfo->ContainsCalls |= hasCalls;
349 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
350 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
351 BB != &BB->getParent()->front();
354 if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
355 Returns.push_back(RI);
358 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
359 /// except that it does some simple constant prop and DCE on the fly. The
360 /// effect of this is to copy significantly less code in cases where (for
361 /// example) a function call with constant arguments is inlined, and those
362 /// constant arguments cause a significant amount of code in the callee to be
363 /// dead. Since this doesn't produce an exact copy of the input, it can't be
364 /// used for things like CloneFunction or CloneModule.
365 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
366 ValueToValueMapTy &VMap,
367 bool ModuleLevelChanges,
368 SmallVectorImpl<ReturnInst*> &Returns,
369 const char *NameSuffix,
370 ClonedCodeInfo *CodeInfo,
371 const TargetData *TD,
372 Instruction *TheCall) {
373 assert(NameSuffix && "NameSuffix cannot be null!");
376 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
377 E = OldFunc->arg_end(); II != E; ++II)
378 assert(VMap.count(II) && "No mapping from source argument specified!");
381 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
382 Returns, NameSuffix, CodeInfo, TD);
384 // Clone the entry block, and anything recursively reachable from it.
385 std::vector<const BasicBlock*> CloneWorklist;
386 CloneWorklist.push_back(&OldFunc->getEntryBlock());
387 while (!CloneWorklist.empty()) {
388 const BasicBlock *BB = CloneWorklist.back();
389 CloneWorklist.pop_back();
390 PFC.CloneBlock(BB, CloneWorklist);
393 // Loop over all of the basic blocks in the old function. If the block was
394 // reachable, we have cloned it and the old block is now in the value map:
395 // insert it into the new function in the right order. If not, ignore it.
397 // Defer PHI resolution until rest of function is resolved.
398 SmallVector<const PHINode*, 16> PHIToResolve;
399 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
402 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
403 if (NewBB == 0) continue; // Dead block.
405 // Add the new block to the new function.
406 NewFunc->getBasicBlockList().push_back(NewBB);
408 // Handle PHI nodes specially, as we have to remove references to dead
410 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
411 if (const PHINode *PN = dyn_cast<PHINode>(I))
412 PHIToResolve.push_back(PN);
416 // Finally, remap the terminator instructions, as those can't be remapped
417 // until all BBs are mapped.
418 RemapInstruction(NewBB->getTerminator(), VMap,
419 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
422 // Defer PHI resolution until rest of function is resolved, PHI resolution
423 // requires the CFG to be up-to-date.
424 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
425 const PHINode *OPN = PHIToResolve[phino];
426 unsigned NumPreds = OPN->getNumIncomingValues();
427 const BasicBlock *OldBB = OPN->getParent();
428 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
430 // Map operands for blocks that are live and remove operands for blocks
432 for (; phino != PHIToResolve.size() &&
433 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
434 OPN = PHIToResolve[phino];
435 PHINode *PN = cast<PHINode>(VMap[OPN]);
436 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
437 Value *V = VMap[PN->getIncomingBlock(pred)];
438 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
439 Value *InVal = MapValue(PN->getIncomingValue(pred),
441 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
442 assert(InVal && "Unknown input value?");
443 PN->setIncomingValue(pred, InVal);
444 PN->setIncomingBlock(pred, MappedBlock);
446 PN->removeIncomingValue(pred, false);
447 --pred, --e; // Revisit the next entry.
452 // The loop above has removed PHI entries for those blocks that are dead
453 // and has updated others. However, if a block is live (i.e. copied over)
454 // but its terminator has been changed to not go to this block, then our
455 // phi nodes will have invalid entries. Update the PHI nodes in this
457 PHINode *PN = cast<PHINode>(NewBB->begin());
458 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
459 if (NumPreds != PN->getNumIncomingValues()) {
460 assert(NumPreds < PN->getNumIncomingValues());
461 // Count how many times each predecessor comes to this block.
462 std::map<BasicBlock*, unsigned> PredCount;
463 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
467 // Figure out how many entries to remove from each PHI.
468 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
469 ++PredCount[PN->getIncomingBlock(i)];
471 // At this point, the excess predecessor entries are positive in the
472 // map. Loop over all of the PHIs and remove excess predecessor
474 BasicBlock::iterator I = NewBB->begin();
475 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
476 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
477 E = PredCount.end(); PCI != E; ++PCI) {
478 BasicBlock *Pred = PCI->first;
479 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
480 PN->removeIncomingValue(Pred, false);
485 // If the loops above have made these phi nodes have 0 or 1 operand,
486 // replace them with undef or the input value. We must do this for
487 // correctness, because 0-operand phis are not valid.
488 PN = cast<PHINode>(NewBB->begin());
489 if (PN->getNumIncomingValues() == 0) {
490 BasicBlock::iterator I = NewBB->begin();
491 BasicBlock::const_iterator OldI = OldBB->begin();
492 while ((PN = dyn_cast<PHINode>(I++))) {
493 Value *NV = UndefValue::get(PN->getType());
494 PN->replaceAllUsesWith(NV);
495 assert(VMap[OldI] == PN && "VMap mismatch");
497 PN->eraseFromParent();
503 // Make a second pass over the PHINodes now that all of them have been
504 // remapped into the new function, simplifying the PHINode and performing any
505 // recursive simplifications exposed. This will transparently update the
506 // TrackingVH in the VMap. Notably, we rely on that so that if we coalesce
507 // two PHINodes, the iteration over the old PHIs remains valid, and the
508 // mapping will just map us to the new node (which may not even be a PHI
510 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
511 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
512 recursivelySimplifyInstruction(PN, TD);
514 // Now that the inlined function body has been fully constructed, go through
515 // and zap unconditional fall-through branches. This happen all the time when
516 // specializing code: code specialization turns conditional branches into
517 // uncond branches, and this code folds them.
518 Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
519 while (I != NewFunc->end()) {
520 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
521 if (!BI || BI->isConditional()) { ++I; continue; }
523 BasicBlock *Dest = BI->getSuccessor(0);
524 if (!Dest->getSinglePredecessor()) {
528 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
529 // above should have zapped all of them..
530 assert(!isa<PHINode>(Dest->begin()));
532 // We know all single-entry PHI nodes in the inlined function have been
533 // removed, so we just need to splice the blocks.
534 BI->eraseFromParent();
536 // Make all PHI nodes that referred to Dest now refer to I as their source.
537 Dest->replaceAllUsesWith(I);
539 // Move all the instructions in the succ to the pred.
540 I->getInstList().splice(I->end(), Dest->getInstList());
542 // Remove the dest block.
543 Dest->eraseFromParent();
545 // Do not increment I, iteratively merge all things this block branches to.