blob: 7ecb103090b40f073b86c805e65aa2cf5cf025c9 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/ConstantFolding.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnera4c29d22006-01-13 18:39:17 +000020#include "llvm/Constants.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000021#include "llvm/DebugInfo.h"
Chris Lattner5a8932f2002-11-19 23:12:22 +000022#include "llvm/DerivedTypes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Function.h"
24#include "llvm/GlobalVariable.h"
Chris Lattnera4c29d22006-01-13 18:39:17 +000025#include "llvm/Instructions.h"
Devang Patelf66d7b52009-02-10 07:48:18 +000026#include "llvm/IntrinsicInst.h"
Devang Patel53bb5c92009-11-10 23:06:00 +000027#include "llvm/LLVMContext.h"
Chris Lattnerf0908a32009-12-31 03:02:08 +000028#include "llvm/Metadata.h"
Chris Lattner35033ef2006-06-01 19:19:23 +000029#include "llvm/Support/CFG.h"
Chandler Carruthafff3302012-03-28 08:38:27 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
31#include "llvm/Transforms/Utils/Local.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000032#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner5e665f52007-02-03 00:08:31 +000033#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattner17d145d2003-04-18 03:50:09 +000036// CloneBasicBlock - See comments in Cloning.h
Chris Lattnerf7703df2004-01-09 06:12:26 +000037BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Patel774cca72010-06-24 00:00:42 +000038 ValueToValueMapTy &VMap,
Benjamin Kramer5deb57c2010-01-27 19:58:47 +000039 const Twine &NameSuffix, Function *F,
Chris Lattnera4c29d22006-01-13 18:39:17 +000040 ClonedCodeInfo *CodeInfo) {
Owen Anderson1d0be152009-08-13 21:58:54 +000041 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattner17d145d2003-04-18 03:50:09 +000042 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
43
Chris Lattnera4c29d22006-01-13 18:39:17 +000044 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
45
46 // Loop over all instructions, and copy them over.
Chris Lattner17d145d2003-04-18 03:50:09 +000047 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
48 II != IE; ++II) {
Nick Lewycky67760642009-09-27 07:38:41 +000049 Instruction *NewInst = II->clone();
Chris Lattner17d145d2003-04-18 03:50:09 +000050 if (II->hasName())
51 NewInst->setName(II->getName()+NameSuffix);
52 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +000053 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattnera4c29d22006-01-13 18:39:17 +000054
Dale Johannesen8aa90fe2009-03-10 22:20:02 +000055 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattnera4c29d22006-01-13 18:39:17 +000056 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
57 if (isa<ConstantInt>(AI->getArraySize()))
58 hasStaticAllocas = true;
59 else
60 hasDynamicAllocas = true;
61 }
62 }
63
64 if (CodeInfo) {
65 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattnera4c29d22006-01-13 18:39:17 +000066 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
67 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmanecb7a772007-03-22 16:38:57 +000068 BB != &BB->getParent()->getEntryBlock();
Chris Lattner17d145d2003-04-18 03:50:09 +000069 }
70 return NewBB;
71}
72
Chris Lattnerfa703a42002-03-29 19:03:54 +000073// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohman6cb8c232010-08-26 15:41:53 +000074// VMap values.
Chris Lattnerfa703a42002-03-29 19:03:54 +000075//
Chris Lattnerf7703df2004-01-09 06:12:26 +000076void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +000077 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +000078 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +000079 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wangd24397a2011-12-23 02:18:32 +000080 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
81 ValueMapTypeRemapper *TypeMapper) {
Chris Lattnerdcd80402002-11-19 21:54:07 +000082 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanfd939082005-04-21 23:48:37 +000083
Chris Lattnerd1801552002-11-19 22:54:01 +000084#ifndef NDEBUG
Chris Lattnera4c29d22006-01-13 18:39:17 +000085 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
86 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000087 assert(VMap.count(I) && "No mapping from source argument specified!");
Chris Lattnerd1801552002-11-19 22:54:01 +000088#endif
Chris Lattnerfa703a42002-03-29 19:03:54 +000089
Duncan Sands28c3cff2008-05-26 19:58:59 +000090 // Clone any attributes.
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000091 if (NewFunc->arg_size() == OldFunc->arg_size())
92 NewFunc->copyAttributesFrom(OldFunc);
93 else {
Devang Patel29d3dd82010-06-23 23:55:51 +000094 //Some arguments were deleted with the VMap. Copy arguments one by one
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000095 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
96 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000097 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000098 Anew->addAttr( OldFunc->getAttributes()
99 .getParamAttributes(I->getArgNo() + 1));
100 NewFunc->setAttributes(NewFunc->getAttributes()
Bill Wendling07aae2e2012-10-15 07:29:08 +0000101 .addAttr(NewFunc->getContext(),
102 AttrListPtr::ReturnIndex,
Bill Wendlingc4167952012-10-14 07:35:59 +0000103 OldFunc->getAttributes()
Andrew Lenharth82cf32e2008-10-07 18:08:38 +0000104 .getRetAttributes()));
105 NewFunc->setAttributes(NewFunc->getAttributes()
Bill Wendling07aae2e2012-10-15 07:29:08 +0000106 .addAttr(NewFunc->getContext(),
107 AttrListPtr::FunctionIndex,
Bill Wendlingc4167952012-10-14 07:35:59 +0000108 OldFunc->getAttributes()
Andrew Lenharth82cf32e2008-10-07 18:08:38 +0000109 .getFnAttributes()));
110
111 }
Anton Korobeynikov9e49f1b2008-03-23 16:03:00 +0000112
Chris Lattnerfa703a42002-03-29 19:03:54 +0000113 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerdcd80402002-11-19 21:54:07 +0000114 // appropriate. Note that we save BE this way in order to handle cloning of
115 // recursive functions into themselves.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000116 //
117 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
118 BI != BE; ++BI) {
Chris Lattner18961502002-06-25 16:12:52 +0000119 const BasicBlock &BB = *BI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000120
Chris Lattner17d145d2003-04-18 03:50:09 +0000121 // Create a new basic block and copy instructions into it!
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000122 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000123
Eli Friedman4090e1c2011-10-21 20:45:19 +0000124 // Add basic block mapping.
125 VMap[&BB] = CBB;
126
127 // It is only legal to clone a function if a block address within that
128 // function is never referenced outside of the function. Given that, we
129 // want to map block addresses from the old function to block addresses in
130 // the clone. (This is different from the generic ValueMapper
131 // implementation, which generates an invalid blockaddress when
132 // cloning a function.)
133 if (BB.hasAddressTaken()) {
134 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
135 const_cast<BasicBlock*>(&BB));
136 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
137 }
138
139 // Note return instructions for the caller.
Chris Lattnerdcd80402002-11-19 21:54:07 +0000140 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
141 Returns.push_back(RI);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000142 }
143
Misha Brukmanfd939082005-04-21 23:48:37 +0000144 // Loop over all of the instructions in the function, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000145 // references as we go. This uses VMap to do all the hard work.
Devang Patel29d3dd82010-06-23 23:55:51 +0000146 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
Nick Lewycky280a6e62008-04-25 16:53:59 +0000147 BE = NewFunc->end(); BB != BE; ++BB)
Chris Lattnerfa703a42002-03-29 19:03:54 +0000148 // Loop over all instructions, fixing each one as we find it...
Chris Lattnera33ceaa2004-02-04 21:44:26 +0000149 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000150 RemapInstruction(II, VMap,
Mon P Wangd24397a2011-12-23 02:18:32 +0000151 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
152 TypeMapper);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000153}
Chris Lattner5a8932f2002-11-19 23:12:22 +0000154
155/// CloneFunction - Return a copy of the specified function, but without
156/// embedding the function into another module. Also, any references specified
Devang Patel29d3dd82010-06-23 23:55:51 +0000157/// in the VMap are changed to refer to their mapped value instead of the
158/// original one. If any of the arguments to the function are in the VMap,
159/// the arguments are deleted from the resultant function. The VMap is
Chris Lattner5a8932f2002-11-19 23:12:22 +0000160/// updated to include mappings from all of the instructions and basicblocks in
161/// the function from their old to new values.
162///
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000163Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000164 bool ModuleLevelChanges,
Chris Lattnera4c29d22006-01-13 18:39:17 +0000165 ClonedCodeInfo *CodeInfo) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000166 std::vector<Type*> ArgTypes;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000167
168 // The user might be deleting arguments to the function by specifying them in
Devang Patel29d3dd82010-06-23 23:55:51 +0000169 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattner5a8932f2002-11-19 23:12:22 +0000170 //
Chris Lattnera4c29d22006-01-13 18:39:17 +0000171 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
172 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000173 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000174 ArgTypes.push_back(I->getType());
175
176 // Create a new function type...
Owen Andersondebcb012009-07-29 22:17:13 +0000177 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattner5a8932f2002-11-19 23:12:22 +0000178 ArgTypes, F->getFunctionType()->isVarArg());
179
180 // Create the new function...
Gabor Greif051a9502008-04-06 20:25:17 +0000181 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
Misha Brukmanfd939082005-04-21 23:48:37 +0000182
Chris Lattner5a8932f2002-11-19 23:12:22 +0000183 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattnere4d5c442005-03-15 04:54:21 +0000184 Function::arg_iterator DestI = NewF->arg_begin();
Chris Lattnera4c29d22006-01-13 18:39:17 +0000185 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
186 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000187 if (VMap.count(I) == 0) { // Is this argument preserved?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000188 DestI->setName(I->getName()); // Copy the name over...
Devang Patel29d3dd82010-06-23 23:55:51 +0000189 VMap[I] = DestI++; // Add mapping to VMap
Chris Lattner5a8932f2002-11-19 23:12:22 +0000190 }
191
Chris Lattnerec1bea02009-08-27 04:02:30 +0000192 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000193 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
Misha Brukmanfd939082005-04-21 23:48:37 +0000194 return NewF;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000195}
Brian Gaeked0fde302003-11-11 22:41:34 +0000196
Chris Lattner83f03bf2006-05-27 01:22:24 +0000197
198
199namespace {
200 /// PruningFunctionCloner - This class is a private class used to implement
201 /// the CloneAndPruneFunctionInto method.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000202 struct PruningFunctionCloner {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000203 Function *NewFunc;
204 const Function *OldFunc;
Devang Patel774cca72010-06-24 00:00:42 +0000205 ValueToValueMapTy &VMap;
Dan Gohman6cb8c232010-08-26 15:41:53 +0000206 bool ModuleLevelChanges;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000207 const char *NameSuffix;
208 ClonedCodeInfo *CodeInfo;
Micah Villmow3574eca2012-10-08 16:38:25 +0000209 const DataLayout *TD;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000210 public:
211 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000212 ValueToValueMapTy &valueMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000213 bool moduleLevelChanges,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000214 const char *nameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000215 ClonedCodeInfo *codeInfo,
Micah Villmow3574eca2012-10-08 16:38:25 +0000216 const DataLayout *td)
Dan Gohman6cb8c232010-08-26 15:41:53 +0000217 : NewFunc(newFunc), OldFunc(oldFunc),
218 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
Chandler Carruth6bbab862012-04-06 01:11:52 +0000219 NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000220 }
221
222 /// CloneBlock - The specified block is found to be reachable, clone it and
223 /// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000224 void CloneBlock(const BasicBlock *BB,
225 std::vector<const BasicBlock*> &ToClone);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000226 };
227}
228
229/// CloneBlock - The specified block is found to be reachable, clone it and
230/// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000231void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
232 std::vector<const BasicBlock*> &ToClone){
Chandler Carruthafff3302012-03-28 08:38:27 +0000233 WeakVH &BBEntry = VMap[BB];
Chris Lattner83f03bf2006-05-27 01:22:24 +0000234
235 // Have we already cloned this block?
236 if (BBEntry) return;
237
238 // Nope, clone it now.
239 BasicBlock *NewBB;
Owen Anderson1d0be152009-08-13 21:58:54 +0000240 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
Chris Lattner83f03bf2006-05-27 01:22:24 +0000241 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
242
Eli Friedman4090e1c2011-10-21 20:45:19 +0000243 // 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.)
249 //
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);
256 }
257
258
Chris Lattner83f03bf2006-05-27 01:22:24 +0000259 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
260
261 // Loop over all instructions, and copy them over, DCE'ing as we go. This
262 // loop doesn't include the terminator.
Chris Lattner35033ef2006-06-01 19:19:23 +0000263 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000264 II != IE; ++II) {
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000265 Instruction *NewInst = II->clone();
266
267 // Eagerly remap operands to the newly cloned instruction, except for PHI
268 // nodes for which we defer processing until we update the CFG.
269 if (!isa<PHINode>(NewInst)) {
270 RemapInstruction(NewInst, VMap,
271 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
272
273 // If we can simplify this instruction to some other value, simply add
274 // a mapping to that value rather than inserting a new instruction into
275 // the basic block.
276 if (Value *V = SimplifyInstruction(NewInst, TD)) {
277 // On the off-chance that this simplifies to an instruction in the old
278 // function, map it back into the new function.
279 if (Value *MappedV = VMap.lookup(V))
280 V = MappedV;
281
282 VMap[II] = V;
283 delete NewInst;
284 continue;
285 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000286 }
Devang Patelf66d7b52009-02-10 07:48:18 +0000287
Chris Lattner83f03bf2006-05-27 01:22:24 +0000288 if (II->hasName())
289 NewInst->setName(II->getName()+NameSuffix);
Devang Patel29d3dd82010-06-23 23:55:51 +0000290 VMap[II] = NewInst; // Add instruction map to value.
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000291 NewBB->getInstList().push_back(NewInst);
Dale Johannesen8aa90fe2009-03-10 22:20:02 +0000292 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattner83f03bf2006-05-27 01:22:24 +0000293 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
294 if (isa<ConstantInt>(AI->getArraySize()))
295 hasStaticAllocas = true;
296 else
297 hasDynamicAllocas = true;
298 }
299 }
300
Chris Lattner35033ef2006-06-01 19:19:23 +0000301 // Finally, clone over the terminator.
302 const TerminatorInst *OldTI = BB->getTerminator();
303 bool TerminatorDone = false;
304 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
305 if (BI->isConditional()) {
306 // If the condition was a known constant in the callee...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000307 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
308 // Or is a known constant in the caller...
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000309 if (Cond == 0) {
310 Value *V = VMap[BI->getCondition()];
311 Cond = dyn_cast_or_null<ConstantInt>(V);
312 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000313
314 // Constant fold to uncond branch!
315 if (Cond) {
Reid Spencer579dca12007-01-12 04:24:46 +0000316 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patel29d3dd82010-06-23 23:55:51 +0000317 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000318 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000319 TerminatorDone = true;
320 }
321 }
322 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
323 // If switching on a value known constant in the caller.
324 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000325 if (Cond == 0) { // Or known constant after constant prop in the callee...
326 Value *V = VMap[SI->getCondition()];
327 Cond = dyn_cast_or_null<ConstantInt>(V);
328 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000329 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000330 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
331 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patel29d3dd82010-06-23 23:55:51 +0000332 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000333 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000334 TerminatorDone = true;
335 }
336 }
337
338 if (!TerminatorDone) {
Nick Lewycky67760642009-09-27 07:38:41 +0000339 Instruction *NewInst = OldTI->clone();
Chris Lattner35033ef2006-06-01 19:19:23 +0000340 if (OldTI->hasName())
341 NewInst->setName(OldTI->getName()+NameSuffix);
342 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000343 VMap[OldTI] = NewInst; // Add instruction map to value.
Chris Lattner35033ef2006-06-01 19:19:23 +0000344
345 // Recursively clone any reachable successor blocks.
346 const TerminatorInst *TI = BB->getTerminator();
347 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner67ef2412007-03-02 03:11:20 +0000348 ToClone.push_back(TI->getSuccessor(i));
Chris Lattner35033ef2006-06-01 19:19:23 +0000349 }
350
Chris Lattner83f03bf2006-05-27 01:22:24 +0000351 if (CodeInfo) {
352 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000353 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
354 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
355 BB != &BB->getParent()->front();
356 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000357}
358
Chris Lattner83f03bf2006-05-27 01:22:24 +0000359/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
360/// except that it does some simple constant prop and DCE on the fly. The
361/// effect of this is to copy significantly less code in cases where (for
362/// example) a function call with constant arguments is inlined, and those
363/// constant arguments cause a significant amount of code in the callee to be
Duncan Sandsdc024672007-11-27 13:23:08 +0000364/// dead. Since this doesn't produce an exact copy of the input, it can't be
Chris Lattner83f03bf2006-05-27 01:22:24 +0000365/// used for things like CloneFunction or CloneModule.
366void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000367 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000368 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000369 SmallVectorImpl<ReturnInst*> &Returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000370 const char *NameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000371 ClonedCodeInfo *CodeInfo,
Micah Villmow3574eca2012-10-08 16:38:25 +0000372 const DataLayout *TD,
Devang Patel53bb5c92009-11-10 23:06:00 +0000373 Instruction *TheCall) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000374 assert(NameSuffix && "NameSuffix cannot be null!");
375
376#ifndef NDEBUG
Jeff Cohend41b30d2006-11-05 19:31:28 +0000377 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
378 E = OldFunc->arg_end(); II != E; ++II)
Devang Patel29d3dd82010-06-23 23:55:51 +0000379 assert(VMap.count(II) && "No mapping from source argument specified!");
Chris Lattner83f03bf2006-05-27 01:22:24 +0000380#endif
Duncan Sands28c3cff2008-05-26 19:58:59 +0000381
Dan Gohman6cb8c232010-08-26 15:41:53 +0000382 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
Chandler Carruth6bbab862012-04-06 01:11:52 +0000383 NameSuffix, CodeInfo, TD);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000384
385 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner67ef2412007-03-02 03:11:20 +0000386 std::vector<const BasicBlock*> CloneWorklist;
387 CloneWorklist.push_back(&OldFunc->getEntryBlock());
388 while (!CloneWorklist.empty()) {
389 const BasicBlock *BB = CloneWorklist.back();
390 CloneWorklist.pop_back();
391 PFC.CloneBlock(BB, CloneWorklist);
392 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000393
394 // Loop over all of the basic blocks in the old function. If the block was
395 // reachable, we have cloned it and the old block is now in the value map:
396 // insert it into the new function in the right order. If not, ignore it.
397 //
Chris Lattner35033ef2006-06-01 19:19:23 +0000398 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000399 SmallVector<const PHINode*, 16> PHIToResolve;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000400 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
401 BI != BE; ++BI) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000402 Value *V = VMap[BI];
403 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000404 if (NewBB == 0) continue; // Dead block.
Chris Lattner35033ef2006-06-01 19:19:23 +0000405
Chris Lattner83f03bf2006-05-27 01:22:24 +0000406 // Add the new block to the new function.
407 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patel53bb5c92009-11-10 23:06:00 +0000408
Chris Lattner83f03bf2006-05-27 01:22:24 +0000409 // Handle PHI nodes specially, as we have to remove references to dead
410 // blocks.
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000411 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
412 if (const PHINode *PN = dyn_cast<PHINode>(I))
413 PHIToResolve.push_back(PN);
414 else
415 break;
416
417 // Finally, remap the terminator instructions, as those can't be remapped
418 // until all BBs are mapped.
419 RemapInstruction(NewBB->getTerminator(), VMap,
420 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000421 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000422
423 // Defer PHI resolution until rest of function is resolved, PHI resolution
424 // requires the CFG to be up-to-date.
425 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
426 const PHINode *OPN = PHIToResolve[phino];
Chris Lattner35033ef2006-06-01 19:19:23 +0000427 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattner35033ef2006-06-01 19:19:23 +0000428 const BasicBlock *OldBB = OPN->getParent();
Devang Patel29d3dd82010-06-23 23:55:51 +0000429 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000430
431 // Map operands for blocks that are live and remove operands for blocks
432 // that are dead.
433 for (; phino != PHIToResolve.size() &&
434 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
435 OPN = PHIToResolve[phino];
Devang Patel29d3dd82010-06-23 23:55:51 +0000436 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000437 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000438 Value *V = VMap[PN->getIncomingBlock(pred)];
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000439 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Anderson0a205a42009-07-05 22:41:43 +0000440 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000441 VMap,
442 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner35033ef2006-06-01 19:19:23 +0000443 assert(InVal && "Unknown input value?");
444 PN->setIncomingValue(pred, InVal);
445 PN->setIncomingBlock(pred, MappedBlock);
446 } else {
447 PN->removeIncomingValue(pred, false);
448 --pred, --e; // Revisit the next entry.
449 }
450 }
451 }
452
453 // The loop above has removed PHI entries for those blocks that are dead
454 // and has updated others. However, if a block is live (i.e. copied over)
455 // but its terminator has been changed to not go to this block, then our
456 // phi nodes will have invalid entries. Update the PHI nodes in this
457 // case.
458 PHINode *PN = cast<PHINode>(NewBB->begin());
459 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
460 if (NumPreds != PN->getNumIncomingValues()) {
461 assert(NumPreds < PN->getNumIncomingValues());
462 // Count how many times each predecessor comes to this block.
463 std::map<BasicBlock*, unsigned> PredCount;
464 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
465 PI != E; ++PI)
466 --PredCount[*PI];
467
468 // Figure out how many entries to remove from each PHI.
469 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
470 ++PredCount[PN->getIncomingBlock(i)];
471
472 // At this point, the excess predecessor entries are positive in the
473 // map. Loop over all of the PHIs and remove excess predecessor
474 // entries.
475 BasicBlock::iterator I = NewBB->begin();
476 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
477 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
478 E = PredCount.end(); PCI != E; ++PCI) {
479 BasicBlock *Pred = PCI->first;
480 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
481 PN->removeIncomingValue(Pred, false);
482 }
483 }
484 }
485
486 // If the loops above have made these phi nodes have 0 or 1 operand,
487 // replace them with undef or the input value. We must do this for
488 // correctness, because 0-operand phis are not valid.
489 PN = cast<PHINode>(NewBB->begin());
490 if (PN->getNumIncomingValues() == 0) {
491 BasicBlock::iterator I = NewBB->begin();
492 BasicBlock::const_iterator OldI = OldBB->begin();
493 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000494 Value *NV = UndefValue::get(PN->getType());
Chris Lattner35033ef2006-06-01 19:19:23 +0000495 PN->replaceAllUsesWith(NV);
Devang Patel29d3dd82010-06-23 23:55:51 +0000496 assert(VMap[OldI] == PN && "VMap mismatch");
497 VMap[OldI] = NV;
Chris Lattner35033ef2006-06-01 19:19:23 +0000498 PN->eraseFromParent();
499 ++OldI;
500 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000501 }
502 }
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000503
504 // Make a second pass over the PHINodes now that all of them have been
505 // remapped into the new function, simplifying the PHINode and performing any
506 // recursive simplifications exposed. This will transparently update the
Chandler Carruthafff3302012-03-28 08:38:27 +0000507 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000508 // two PHINodes, the iteration over the old PHIs remains valid, and the
509 // mapping will just map us to the new node (which may not even be a PHI
510 // node).
511 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
512 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
513 recursivelySimplifyInstruction(PN, TD);
514
Chris Lattnera4646b62006-09-13 21:27:00 +0000515 // Now that the inlined function body has been fully constructed, go through
516 // and zap unconditional fall-through branches. This happen all the time when
517 // specializing code: code specialization turns conditional branches into
518 // uncond branches, and this code folds them.
Chandler Carruthafff3302012-03-28 08:38:27 +0000519 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
520 Function::iterator I = Begin;
Chris Lattnera4646b62006-09-13 21:27:00 +0000521 while (I != NewFunc->end()) {
Chandler Carruthafff3302012-03-28 08:38:27 +0000522 // Check if this block has become dead during inlining or other
523 // simplifications. Note that the first block will appear dead, as it has
524 // not yet been wired up properly.
525 if (I != Begin && (pred_begin(I) == pred_end(I) ||
526 I->getSinglePredecessor() == I)) {
527 BasicBlock *DeadBB = I++;
528 DeleteDeadBlock(DeadBB);
529 continue;
530 }
531
532 // We need to simplify conditional branches and switches with a constant
533 // operand. We try to prune these out when cloning, but if the
534 // simplification required looking through PHI nodes, those are only
535 // available after forming the full basic block. That may leave some here,
536 // and we still want to prune the dead code as early as possible.
537 ConstantFoldTerminator(I);
538
Chris Lattnera4646b62006-09-13 21:27:00 +0000539 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
540 if (!BI || BI->isConditional()) { ++I; continue; }
541
542 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000543 if (!Dest->getSinglePredecessor()) {
Chris Lattner8e8eda72007-02-01 18:48:38 +0000544 ++I; continue;
545 }
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000546
547 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
548 // above should have zapped all of them..
549 assert(!isa<PHINode>(Dest->begin()));
550
Chris Lattnera4646b62006-09-13 21:27:00 +0000551 // We know all single-entry PHI nodes in the inlined function have been
552 // removed, so we just need to splice the blocks.
553 BI->eraseFromParent();
554
Eric Christophere59fbc02011-06-23 06:24:52 +0000555 // Make all PHI nodes that referred to Dest now refer to I as their source.
556 Dest->replaceAllUsesWith(I);
557
Jay Foad95c3e482011-06-23 09:09:15 +0000558 // Move all the instructions in the succ to the pred.
559 I->getInstList().splice(I->end(), Dest->getInstList());
560
Chris Lattnera4646b62006-09-13 21:27:00 +0000561 // Remove the dest block.
562 Dest->eraseFromParent();
563
564 // Do not increment I, iteratively merge all things this block branches to.
565 }
Chandler Carruth9ceebb72012-04-06 17:21:31 +0000566
567 // Make a final pass over the basic blocks from theh old function to gather
568 // any return instructions which survived folding. We have to do this here
569 // because we can iteratively remove and merge returns above.
570 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
571 E = NewFunc->end();
572 I != E; ++I)
573 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
574 Returns.push_back(RI);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000575}