blob: 021f263a1ded5fd14c039b0c1803157b126bc36a [file] [log] [blame]
Chris Lattner6c2e2e52002-11-19 22:04:49 +00001//===- CloneFunction.cpp - Clone a function into another function ---------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6c2e2e52002-11-19 22:04:49 +00009//
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//===----------------------------------------------------------------------===//
Chris Lattnerfa703a42002-03-29 19:03:54 +000015
Chris Lattner309f1932002-11-19 20:59:41 +000016#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattnera4c29d22006-01-13 18:39:17 +000017#include "llvm/Constants.h"
Chris Lattner5a8932f2002-11-19 23:12:22 +000018#include "llvm/DerivedTypes.h"
Chris Lattnera4c29d22006-01-13 18:39:17 +000019#include "llvm/Instructions.h"
Devang Patelf66d7b52009-02-10 07:48:18 +000020#include "llvm/IntrinsicInst.h"
Nate Begeman4be30ac2008-04-25 06:37:06 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerfa703a42002-03-29 19:03:54 +000022#include "llvm/Function.h"
Devang Patel53bb5c92009-11-10 23:06:00 +000023#include "llvm/LLVMContext.h"
Chris Lattnerf0908a32009-12-31 03:02:08 +000024#include "llvm/Metadata.h"
Chris Lattner35033ef2006-06-01 19:19:23 +000025#include "llvm/Support/CFG.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000026#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthd54f9a42012-03-25 04:03:40 +000028#include "llvm/Analysis/InstructionSimplify.h"
Devang Patel517576d2009-04-15 00:17:06 +000029#include "llvm/Analysis/DebugInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000030#include "llvm/ADT/SmallVector.h"
Chris Lattner5e665f52007-02-03 00:08:31 +000031#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner17d145d2003-04-18 03:50:09 +000034// CloneBasicBlock - See comments in Cloning.h
Chris Lattnerf7703df2004-01-09 06:12:26 +000035BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Patel774cca72010-06-24 00:00:42 +000036 ValueToValueMapTy &VMap,
Benjamin Kramer5deb57c2010-01-27 19:58:47 +000037 const Twine &NameSuffix, Function *F,
Chris Lattnera4c29d22006-01-13 18:39:17 +000038 ClonedCodeInfo *CodeInfo) {
Owen Anderson1d0be152009-08-13 21:58:54 +000039 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattner17d145d2003-04-18 03:50:09 +000040 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
41
Chris Lattnera4c29d22006-01-13 18:39:17 +000042 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
43
44 // Loop over all instructions, and copy them over.
Chris Lattner17d145d2003-04-18 03:50:09 +000045 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
46 II != IE; ++II) {
Nick Lewycky67760642009-09-27 07:38:41 +000047 Instruction *NewInst = II->clone();
Chris Lattner17d145d2003-04-18 03:50:09 +000048 if (II->hasName())
49 NewInst->setName(II->getName()+NameSuffix);
50 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +000051 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattnera4c29d22006-01-13 18:39:17 +000052
Dale Johannesen8aa90fe2009-03-10 22:20:02 +000053 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattnera4c29d22006-01-13 18:39:17 +000054 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
55 if (isa<ConstantInt>(AI->getArraySize()))
56 hasStaticAllocas = true;
57 else
58 hasDynamicAllocas = true;
59 }
60 }
61
62 if (CodeInfo) {
63 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattnera4c29d22006-01-13 18:39:17 +000064 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
65 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmanecb7a772007-03-22 16:38:57 +000066 BB != &BB->getParent()->getEntryBlock();
Chris Lattner17d145d2003-04-18 03:50:09 +000067 }
68 return NewBB;
69}
70
Chris Lattnerfa703a42002-03-29 19:03:54 +000071// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohman6cb8c232010-08-26 15:41:53 +000072// VMap values.
Chris Lattnerfa703a42002-03-29 19:03:54 +000073//
Chris Lattnerf7703df2004-01-09 06:12:26 +000074void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +000075 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +000076 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +000077 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wangd24397a2011-12-23 02:18:32 +000078 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
79 ValueMapTypeRemapper *TypeMapper) {
Chris Lattnerdcd80402002-11-19 21:54:07 +000080 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanfd939082005-04-21 23:48:37 +000081
Chris Lattnerd1801552002-11-19 22:54:01 +000082#ifndef NDEBUG
Chris Lattnera4c29d22006-01-13 18:39:17 +000083 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
84 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000085 assert(VMap.count(I) && "No mapping from source argument specified!");
Chris Lattnerd1801552002-11-19 22:54:01 +000086#endif
Chris Lattnerfa703a42002-03-29 19:03:54 +000087
Duncan Sands28c3cff2008-05-26 19:58:59 +000088 // Clone any attributes.
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000089 if (NewFunc->arg_size() == OldFunc->arg_size())
90 NewFunc->copyAttributesFrom(OldFunc);
91 else {
Devang Patel29d3dd82010-06-23 23:55:51 +000092 //Some arguments were deleted with the VMap. Copy arguments one by one
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000093 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
94 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000095 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000096 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()));
104
105 }
Anton Korobeynikov9e49f1b2008-03-23 16:03:00 +0000106
Chris Lattnerfa703a42002-03-29 19:03:54 +0000107 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerdcd80402002-11-19 21:54:07 +0000108 // appropriate. Note that we save BE this way in order to handle cloning of
109 // recursive functions into themselves.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000110 //
111 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
112 BI != BE; ++BI) {
Chris Lattner18961502002-06-25 16:12:52 +0000113 const BasicBlock &BB = *BI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000114
Chris Lattner17d145d2003-04-18 03:50:09 +0000115 // Create a new basic block and copy instructions into it!
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000116 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000117
Eli Friedman4090e1c2011-10-21 20:45:19 +0000118 // Add basic block mapping.
119 VMap[&BB] = CBB;
120
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);
131 }
132
133 // Note return instructions for the caller.
Chris Lattnerdcd80402002-11-19 21:54:07 +0000134 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
135 Returns.push_back(RI);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000136 }
137
Misha Brukmanfd939082005-04-21 23:48:37 +0000138 // Loop over all of the instructions in the function, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000139 // references as we go. This uses VMap to do all the hard work.
Devang Patel29d3dd82010-06-23 23:55:51 +0000140 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
Nick Lewycky280a6e62008-04-25 16:53:59 +0000141 BE = NewFunc->end(); BB != BE; ++BB)
Chris Lattnerfa703a42002-03-29 19:03:54 +0000142 // Loop over all instructions, fixing each one as we find it...
Chris Lattnera33ceaa2004-02-04 21:44:26 +0000143 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000144 RemapInstruction(II, VMap,
Mon P Wangd24397a2011-12-23 02:18:32 +0000145 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
146 TypeMapper);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000147}
Chris Lattner5a8932f2002-11-19 23:12:22 +0000148
149/// CloneFunction - Return a copy of the specified function, but without
150/// embedding the function into another module. Also, any references specified
Devang Patel29d3dd82010-06-23 23:55:51 +0000151/// 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
Chris Lattner5a8932f2002-11-19 23:12:22 +0000154/// updated to include mappings from all of the instructions and basicblocks in
155/// the function from their old to new values.
156///
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000157Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000158 bool ModuleLevelChanges,
Chris Lattnera4c29d22006-01-13 18:39:17 +0000159 ClonedCodeInfo *CodeInfo) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000160 std::vector<Type*> ArgTypes;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000161
162 // The user might be deleting arguments to the function by specifying them in
Devang Patel29d3dd82010-06-23 23:55:51 +0000163 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattner5a8932f2002-11-19 23:12:22 +0000164 //
Chris Lattnera4c29d22006-01-13 18:39:17 +0000165 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
166 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000167 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000168 ArgTypes.push_back(I->getType());
169
170 // Create a new function type...
Owen Andersondebcb012009-07-29 22:17:13 +0000171 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattner5a8932f2002-11-19 23:12:22 +0000172 ArgTypes, F->getFunctionType()->isVarArg());
173
174 // Create the new function...
Gabor Greif051a9502008-04-06 20:25:17 +0000175 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
Misha Brukmanfd939082005-04-21 23:48:37 +0000176
Chris Lattner5a8932f2002-11-19 23:12:22 +0000177 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattnere4d5c442005-03-15 04:54:21 +0000178 Function::arg_iterator DestI = NewF->arg_begin();
Chris Lattnera4c29d22006-01-13 18:39:17 +0000179 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
180 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000181 if (VMap.count(I) == 0) { // Is this argument preserved?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000182 DestI->setName(I->getName()); // Copy the name over...
Devang Patel29d3dd82010-06-23 23:55:51 +0000183 VMap[I] = DestI++; // Add mapping to VMap
Chris Lattner5a8932f2002-11-19 23:12:22 +0000184 }
185
Chris Lattnerec1bea02009-08-27 04:02:30 +0000186 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000187 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
Misha Brukmanfd939082005-04-21 23:48:37 +0000188 return NewF;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000189}
Brian Gaeked0fde302003-11-11 22:41:34 +0000190
Chris Lattner83f03bf2006-05-27 01:22:24 +0000191
192
193namespace {
194 /// PruningFunctionCloner - This class is a private class used to implement
195 /// the CloneAndPruneFunctionInto method.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000196 struct PruningFunctionCloner {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000197 Function *NewFunc;
198 const Function *OldFunc;
Devang Patel774cca72010-06-24 00:00:42 +0000199 ValueToValueMapTy &VMap;
Dan Gohman6cb8c232010-08-26 15:41:53 +0000200 bool ModuleLevelChanges;
Chris Lattnerec1bea02009-08-27 04:02:30 +0000201 SmallVectorImpl<ReturnInst*> &Returns;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000202 const char *NameSuffix;
203 ClonedCodeInfo *CodeInfo;
Chris Lattner1dfdf822007-01-30 23:22:39 +0000204 const TargetData *TD;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000205 public:
206 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000207 ValueToValueMapTy &valueMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000208 bool moduleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000209 SmallVectorImpl<ReturnInst*> &returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000210 const char *nameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000211 ClonedCodeInfo *codeInfo,
212 const TargetData *td)
Dan Gohman6cb8c232010-08-26 15:41:53 +0000213 : NewFunc(newFunc), OldFunc(oldFunc),
214 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
215 Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000216 }
217
218 /// CloneBlock - The specified block is found to be reachable, clone it and
219 /// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000220 void CloneBlock(const BasicBlock *BB,
221 std::vector<const BasicBlock*> &ToClone);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000222 };
223}
224
225/// CloneBlock - The specified block is found to be reachable, clone it and
226/// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000227void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
228 std::vector<const BasicBlock*> &ToClone){
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000229 TrackingVH<Value> &BBEntry = VMap[BB];
Chris Lattner83f03bf2006-05-27 01:22:24 +0000230
231 // Have we already cloned this block?
232 if (BBEntry) return;
233
234 // Nope, clone it now.
235 BasicBlock *NewBB;
Owen Anderson1d0be152009-08-13 21:58:54 +0000236 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
Chris Lattner83f03bf2006-05-27 01:22:24 +0000237 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
238
Eli Friedman4090e1c2011-10-21 20:45:19 +0000239 // 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.)
245 //
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);
252 }
253
254
Chris Lattner83f03bf2006-05-27 01:22:24 +0000255 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
256
257 // Loop over all instructions, and copy them over, DCE'ing as we go. This
258 // loop doesn't include the terminator.
Chris Lattner35033ef2006-06-01 19:19:23 +0000259 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000260 II != IE; ++II) {
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000261 Instruction *NewInst = II->clone();
262
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);
268
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
271 // the basic block.
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))
276 V = MappedV;
277
278 VMap[II] = V;
279 delete NewInst;
280 continue;
281 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000282 }
Devang Patelf66d7b52009-02-10 07:48:18 +0000283
Chris Lattner83f03bf2006-05-27 01:22:24 +0000284 if (II->hasName())
285 NewInst->setName(II->getName()+NameSuffix);
Devang Patel29d3dd82010-06-23 23:55:51 +0000286 VMap[II] = NewInst; // Add instruction map to value.
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000287 NewBB->getInstList().push_back(NewInst);
Dale Johannesen8aa90fe2009-03-10 22:20:02 +0000288 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattner83f03bf2006-05-27 01:22:24 +0000289 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
290 if (isa<ConstantInt>(AI->getArraySize()))
291 hasStaticAllocas = true;
292 else
293 hasDynamicAllocas = true;
294 }
295 }
296
Chris Lattner35033ef2006-06-01 19:19:23 +0000297 // 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...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000303 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
304 // Or is a known constant in the caller...
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000305 if (Cond == 0) {
306 Value *V = VMap[BI->getCondition()];
307 Cond = dyn_cast_or_null<ConstantInt>(V);
308 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000309
310 // Constant fold to uncond branch!
311 if (Cond) {
Reid Spencer579dca12007-01-12 04:24:46 +0000312 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patel29d3dd82010-06-23 23:55:51 +0000313 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000314 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000315 TerminatorDone = true;
316 }
317 }
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());
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000321 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);
324 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000325 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000326 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
327 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patel29d3dd82010-06-23 23:55:51 +0000328 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000329 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000330 TerminatorDone = true;
331 }
332 }
333
334 if (!TerminatorDone) {
Nick Lewycky67760642009-09-27 07:38:41 +0000335 Instruction *NewInst = OldTI->clone();
Chris Lattner35033ef2006-06-01 19:19:23 +0000336 if (OldTI->hasName())
337 NewInst->setName(OldTI->getName()+NameSuffix);
338 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000339 VMap[OldTI] = NewInst; // Add instruction map to value.
Chris Lattner35033ef2006-06-01 19:19:23 +0000340
341 // Recursively clone any reachable successor blocks.
342 const TerminatorInst *TI = BB->getTerminator();
343 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner67ef2412007-03-02 03:11:20 +0000344 ToClone.push_back(TI->getSuccessor(i));
Chris Lattner35033ef2006-06-01 19:19:23 +0000345 }
346
Chris Lattner83f03bf2006-05-27 01:22:24 +0000347 if (CodeInfo) {
348 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000349 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
350 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
351 BB != &BB->getParent()->front();
352 }
353
354 if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
355 Returns.push_back(RI);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000356}
357
Chris Lattner83f03bf2006-05-27 01:22:24 +0000358/// 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
Duncan Sandsdc024672007-11-27 13:23:08 +0000363/// dead. Since this doesn't produce an exact copy of the input, it can't be
Chris Lattner83f03bf2006-05-27 01:22:24 +0000364/// used for things like CloneFunction or CloneModule.
365void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000366 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000367 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000368 SmallVectorImpl<ReturnInst*> &Returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000369 const char *NameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000370 ClonedCodeInfo *CodeInfo,
Devang Patel53bb5c92009-11-10 23:06:00 +0000371 const TargetData *TD,
372 Instruction *TheCall) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000373 assert(NameSuffix && "NameSuffix cannot be null!");
374
375#ifndef NDEBUG
Jeff Cohend41b30d2006-11-05 19:31:28 +0000376 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
377 E = OldFunc->arg_end(); II != E; ++II)
Devang Patel29d3dd82010-06-23 23:55:51 +0000378 assert(VMap.count(II) && "No mapping from source argument specified!");
Chris Lattner83f03bf2006-05-27 01:22:24 +0000379#endif
Duncan Sands28c3cff2008-05-26 19:58:59 +0000380
Dan Gohman6cb8c232010-08-26 15:41:53 +0000381 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
382 Returns, NameSuffix, CodeInfo, TD);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000383
384 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner67ef2412007-03-02 03:11:20 +0000385 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);
391 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000392
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.
396 //
Chris Lattner35033ef2006-06-01 19:19:23 +0000397 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000398 SmallVector<const PHINode*, 16> PHIToResolve;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000399 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
400 BI != BE; ++BI) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000401 Value *V = VMap[BI];
402 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000403 if (NewBB == 0) continue; // Dead block.
Chris Lattner35033ef2006-06-01 19:19:23 +0000404
Chris Lattner83f03bf2006-05-27 01:22:24 +0000405 // Add the new block to the new function.
406 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patel53bb5c92009-11-10 23:06:00 +0000407
Chris Lattner83f03bf2006-05-27 01:22:24 +0000408 // Handle PHI nodes specially, as we have to remove references to dead
409 // blocks.
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000410 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);
413 else
414 break;
415
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);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000420 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000421
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];
Chris Lattner35033ef2006-06-01 19:19:23 +0000426 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattner35033ef2006-06-01 19:19:23 +0000427 const BasicBlock *OldBB = OPN->getParent();
Devang Patel29d3dd82010-06-23 23:55:51 +0000428 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000429
430 // Map operands for blocks that are live and remove operands for blocks
431 // that are dead.
432 for (; phino != PHIToResolve.size() &&
433 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
434 OPN = PHIToResolve[phino];
Devang Patel29d3dd82010-06-23 23:55:51 +0000435 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000436 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000437 Value *V = VMap[PN->getIncomingBlock(pred)];
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000438 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Anderson0a205a42009-07-05 22:41:43 +0000439 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000440 VMap,
441 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner35033ef2006-06-01 19:19:23 +0000442 assert(InVal && "Unknown input value?");
443 PN->setIncomingValue(pred, InVal);
444 PN->setIncomingBlock(pred, MappedBlock);
445 } else {
446 PN->removeIncomingValue(pred, false);
447 --pred, --e; // Revisit the next entry.
448 }
449 }
450 }
451
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
456 // case.
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);
464 PI != E; ++PI)
465 --PredCount[*PI];
466
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)];
470
471 // At this point, the excess predecessor entries are positive in the
472 // map. Loop over all of the PHIs and remove excess predecessor
473 // entries.
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);
481 }
482 }
483 }
484
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++))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000493 Value *NV = UndefValue::get(PN->getType());
Chris Lattner35033ef2006-06-01 19:19:23 +0000494 PN->replaceAllUsesWith(NV);
Devang Patel29d3dd82010-06-23 23:55:51 +0000495 assert(VMap[OldI] == PN && "VMap mismatch");
496 VMap[OldI] = NV;
Chris Lattner35033ef2006-06-01 19:19:23 +0000497 PN->eraseFromParent();
498 ++OldI;
499 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000500 }
501 }
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000502
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
509 // node).
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);
513
Chris Lattnera4646b62006-09-13 21:27:00 +0000514 // 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.
Devang Patel29d3dd82010-06-23 23:55:51 +0000518 Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
Chris Lattnera4646b62006-09-13 21:27:00 +0000519 while (I != NewFunc->end()) {
520 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
521 if (!BI || BI->isConditional()) { ++I; continue; }
522
523 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000524 if (!Dest->getSinglePredecessor()) {
Chris Lattner8e8eda72007-02-01 18:48:38 +0000525 ++I; continue;
526 }
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000527
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()));
531
Chris Lattnera4646b62006-09-13 21:27:00 +0000532 // 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();
535
Eric Christophere59fbc02011-06-23 06:24:52 +0000536 // Make all PHI nodes that referred to Dest now refer to I as their source.
537 Dest->replaceAllUsesWith(I);
538
Jay Foad95c3e482011-06-23 09:09:15 +0000539 // Move all the instructions in the succ to the pred.
540 I->getInstList().splice(I->end(), Dest->getInstList());
541
Chris Lattnera4646b62006-09-13 21:27:00 +0000542 // Remove the dest block.
543 Dest->eraseFromParent();
544
545 // Do not increment I, iteratively merge all things this block branches to.
546 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000547}