blob: f43186edae435c2415a2f9ce99b9bf9232b0d746 [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"
Devang Patel517576d2009-04-15 00:17:06 +000028#include "llvm/Analysis/DebugInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattner5e665f52007-02-03 00:08:31 +000030#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner17d145d2003-04-18 03:50:09 +000033// CloneBasicBlock - See comments in Cloning.h
Chris Lattnerf7703df2004-01-09 06:12:26 +000034BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Patel774cca72010-06-24 00:00:42 +000035 ValueToValueMapTy &VMap,
Benjamin Kramer5deb57c2010-01-27 19:58:47 +000036 const Twine &NameSuffix, Function *F,
Chris Lattnera4c29d22006-01-13 18:39:17 +000037 ClonedCodeInfo *CodeInfo) {
Owen Anderson1d0be152009-08-13 21:58:54 +000038 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattner17d145d2003-04-18 03:50:09 +000039 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
40
Chris Lattnera4c29d22006-01-13 18:39:17 +000041 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
42
43 // Loop over all instructions, and copy them over.
Chris Lattner17d145d2003-04-18 03:50:09 +000044 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
45 II != IE; ++II) {
Nick Lewycky67760642009-09-27 07:38:41 +000046 Instruction *NewInst = II->clone();
Chris Lattner17d145d2003-04-18 03:50:09 +000047 if (II->hasName())
48 NewInst->setName(II->getName()+NameSuffix);
49 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +000050 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattnera4c29d22006-01-13 18:39:17 +000051
Dale Johannesen8aa90fe2009-03-10 22:20:02 +000052 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattnera4c29d22006-01-13 18:39:17 +000053 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
54 if (isa<ConstantInt>(AI->getArraySize()))
55 hasStaticAllocas = true;
56 else
57 hasDynamicAllocas = true;
58 }
59 }
60
61 if (CodeInfo) {
62 CodeInfo->ContainsCalls |= hasCalls;
63 CodeInfo->ContainsUnwinds |= isa<UnwindInst>(BB->getTerminator());
64 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,
Chris Lattnera4c29d22006-01-13 18:39:17 +000078 const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
Chris Lattnerdcd80402002-11-19 21:54:07 +000079 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanfd939082005-04-21 23:48:37 +000080
Chris Lattnerd1801552002-11-19 22:54:01 +000081#ifndef NDEBUG
Chris Lattnera4c29d22006-01-13 18:39:17 +000082 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
83 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000084 assert(VMap.count(I) && "No mapping from source argument specified!");
Chris Lattnerd1801552002-11-19 22:54:01 +000085#endif
Chris Lattnerfa703a42002-03-29 19:03:54 +000086
Duncan Sands28c3cff2008-05-26 19:58:59 +000087 // Clone any attributes.
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000088 if (NewFunc->arg_size() == OldFunc->arg_size())
89 NewFunc->copyAttributesFrom(OldFunc);
90 else {
Devang Patel29d3dd82010-06-23 23:55:51 +000091 //Some arguments were deleted with the VMap. Copy arguments one by one
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000092 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
93 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000094 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000095 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()));
103
104 }
Anton Korobeynikov9e49f1b2008-03-23 16:03:00 +0000105
Chris Lattnerfa703a42002-03-29 19:03:54 +0000106 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerdcd80402002-11-19 21:54:07 +0000107 // appropriate. Note that we save BE this way in order to handle cloning of
108 // recursive functions into themselves.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000109 //
110 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
111 BI != BE; ++BI) {
Chris Lattner18961502002-06-25 16:12:52 +0000112 const BasicBlock &BB = *BI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000113
Chris Lattner17d145d2003-04-18 03:50:09 +0000114 // Create a new basic block and copy instructions into it!
Devang Patel29d3dd82010-06-23 23:55:51 +0000115 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc,
Chris Lattnera4c29d22006-01-13 18:39:17 +0000116 CodeInfo);
Devang Patel29d3dd82010-06-23 23:55:51 +0000117 VMap[&BB] = CBB; // Add basic block mapping.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000118
Chris Lattnerdcd80402002-11-19 21:54:07 +0000119 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
120 Returns.push_back(RI);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000121 }
122
Misha Brukmanfd939082005-04-21 23:48:37 +0000123 // Loop over all of the instructions in the function, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000124 // references as we go. This uses VMap to do all the hard work.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000125 //
Devang Patel29d3dd82010-06-23 23:55:51 +0000126 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
Nick Lewycky280a6e62008-04-25 16:53:59 +0000127 BE = NewFunc->end(); BB != BE; ++BB)
Chris Lattnerfa703a42002-03-29 19:03:54 +0000128 // Loop over all instructions, fixing each one as we find it...
Chris Lattnera33ceaa2004-02-04 21:44:26 +0000129 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
Dan Gohman6cb8c232010-08-26 15:41:53 +0000130 RemapInstruction(II, VMap, ModuleLevelChanges);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000131}
Chris Lattner5a8932f2002-11-19 23:12:22 +0000132
133/// CloneFunction - Return a copy of the specified function, but without
134/// embedding the function into another module. Also, any references specified
Devang Patel29d3dd82010-06-23 23:55:51 +0000135/// in the VMap are changed to refer to their mapped value instead of the
136/// original one. If any of the arguments to the function are in the VMap,
137/// the arguments are deleted from the resultant function. The VMap is
Chris Lattner5a8932f2002-11-19 23:12:22 +0000138/// updated to include mappings from all of the instructions and basicblocks in
139/// the function from their old to new values.
140///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000141Function *llvm::CloneFunction(const Function *F,
Devang Patel774cca72010-06-24 00:00:42 +0000142 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000143 bool ModuleLevelChanges,
Chris Lattnera4c29d22006-01-13 18:39:17 +0000144 ClonedCodeInfo *CodeInfo) {
Chris Lattner5a8932f2002-11-19 23:12:22 +0000145 std::vector<const Type*> ArgTypes;
146
147 // The user might be deleting arguments to the function by specifying them in
Devang Patel29d3dd82010-06-23 23:55:51 +0000148 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattner5a8932f2002-11-19 23:12:22 +0000149 //
Chris Lattnera4c29d22006-01-13 18:39:17 +0000150 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
151 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000152 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000153 ArgTypes.push_back(I->getType());
154
155 // Create a new function type...
Owen Andersondebcb012009-07-29 22:17:13 +0000156 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattner5a8932f2002-11-19 23:12:22 +0000157 ArgTypes, F->getFunctionType()->isVarArg());
158
159 // Create the new function...
Gabor Greif051a9502008-04-06 20:25:17 +0000160 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
Misha Brukmanfd939082005-04-21 23:48:37 +0000161
Chris Lattner5a8932f2002-11-19 23:12:22 +0000162 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattnere4d5c442005-03-15 04:54:21 +0000163 Function::arg_iterator DestI = NewF->arg_begin();
Chris Lattnera4c29d22006-01-13 18:39:17 +0000164 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
165 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000166 if (VMap.count(I) == 0) { // Is this argument preserved?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000167 DestI->setName(I->getName()); // Copy the name over...
Devang Patel29d3dd82010-06-23 23:55:51 +0000168 VMap[I] = DestI++; // Add mapping to VMap
Chris Lattner5a8932f2002-11-19 23:12:22 +0000169 }
170
Chris Lattnerec1bea02009-08-27 04:02:30 +0000171 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000172 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
Misha Brukmanfd939082005-04-21 23:48:37 +0000173 return NewF;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000174}
Brian Gaeked0fde302003-11-11 22:41:34 +0000175
Chris Lattner83f03bf2006-05-27 01:22:24 +0000176
177
178namespace {
179 /// PruningFunctionCloner - This class is a private class used to implement
180 /// the CloneAndPruneFunctionInto method.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000181 struct PruningFunctionCloner {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000182 Function *NewFunc;
183 const Function *OldFunc;
Devang Patel774cca72010-06-24 00:00:42 +0000184 ValueToValueMapTy &VMap;
Dan Gohman6cb8c232010-08-26 15:41:53 +0000185 bool ModuleLevelChanges;
Chris Lattnerec1bea02009-08-27 04:02:30 +0000186 SmallVectorImpl<ReturnInst*> &Returns;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000187 const char *NameSuffix;
188 ClonedCodeInfo *CodeInfo;
Chris Lattner1dfdf822007-01-30 23:22:39 +0000189 const TargetData *TD;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000190 public:
191 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000192 ValueToValueMapTy &valueMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000193 bool moduleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000194 SmallVectorImpl<ReturnInst*> &returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000195 const char *nameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000196 ClonedCodeInfo *codeInfo,
197 const TargetData *td)
Dan Gohman6cb8c232010-08-26 15:41:53 +0000198 : NewFunc(newFunc), OldFunc(oldFunc),
199 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
200 Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000201 }
202
203 /// CloneBlock - The specified block is found to be reachable, clone it and
204 /// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000205 void CloneBlock(const BasicBlock *BB,
206 std::vector<const BasicBlock*> &ToClone);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000207
208 public:
209 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
Devang Patel29d3dd82010-06-23 23:55:51 +0000210 /// mapping its operands through VMap if they are available.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000211 Constant *ConstantFoldMappedInstruction(const Instruction *I);
212 };
213}
214
215/// CloneBlock - The specified block is found to be reachable, clone it and
216/// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000217void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
218 std::vector<const BasicBlock*> &ToClone){
Devang Patel29d3dd82010-06-23 23:55:51 +0000219 Value *&BBEntry = VMap[BB];
Chris Lattner83f03bf2006-05-27 01:22:24 +0000220
221 // Have we already cloned this block?
222 if (BBEntry) return;
223
224 // Nope, clone it now.
225 BasicBlock *NewBB;
Owen Anderson1d0be152009-08-13 21:58:54 +0000226 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
Chris Lattner83f03bf2006-05-27 01:22:24 +0000227 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
228
229 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
230
231 // Loop over all instructions, and copy them over, DCE'ing as we go. This
232 // loop doesn't include the terminator.
Chris Lattner35033ef2006-06-01 19:19:23 +0000233 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000234 II != IE; ++II) {
235 // If this instruction constant folds, don't bother cloning the instruction,
236 // instead, just add the constant to the value map.
237 if (Constant *C = ConstantFoldMappedInstruction(II)) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000238 VMap[II] = C;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000239 continue;
240 }
Devang Patelf66d7b52009-02-10 07:48:18 +0000241
Nick Lewycky67760642009-09-27 07:38:41 +0000242 Instruction *NewInst = II->clone();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000243 if (II->hasName())
244 NewInst->setName(II->getName()+NameSuffix);
245 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000246 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000247
Dale Johannesen8aa90fe2009-03-10 22:20:02 +0000248 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattner83f03bf2006-05-27 01:22:24 +0000249 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
250 if (isa<ConstantInt>(AI->getArraySize()))
251 hasStaticAllocas = true;
252 else
253 hasDynamicAllocas = true;
254 }
255 }
256
Chris Lattner35033ef2006-06-01 19:19:23 +0000257 // Finally, clone over the terminator.
258 const TerminatorInst *OldTI = BB->getTerminator();
259 bool TerminatorDone = false;
260 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
261 if (BI->isConditional()) {
262 // If the condition was a known constant in the callee...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000263 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
264 // Or is a known constant in the caller...
265 if (Cond == 0)
Devang Patel29d3dd82010-06-23 23:55:51 +0000266 Cond = dyn_cast_or_null<ConstantInt>(VMap[BI->getCondition()]);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000267
268 // Constant fold to uncond branch!
269 if (Cond) {
Reid Spencer579dca12007-01-12 04:24:46 +0000270 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patel29d3dd82010-06-23 23:55:51 +0000271 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000272 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000273 TerminatorDone = true;
274 }
275 }
276 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
277 // If switching on a value known constant in the caller.
278 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
279 if (Cond == 0) // Or known constant after constant prop in the callee...
Devang Patel29d3dd82010-06-23 23:55:51 +0000280 Cond = dyn_cast_or_null<ConstantInt>(VMap[SI->getCondition()]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000281 if (Cond) { // Constant fold to uncond branch!
282 BasicBlock *Dest = SI->getSuccessor(SI->findCaseValue(Cond));
Devang Patel29d3dd82010-06-23 23:55:51 +0000283 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000284 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000285 TerminatorDone = true;
286 }
287 }
288
289 if (!TerminatorDone) {
Nick Lewycky67760642009-09-27 07:38:41 +0000290 Instruction *NewInst = OldTI->clone();
Chris Lattner35033ef2006-06-01 19:19:23 +0000291 if (OldTI->hasName())
292 NewInst->setName(OldTI->getName()+NameSuffix);
293 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000294 VMap[OldTI] = NewInst; // Add instruction map to value.
Chris Lattner35033ef2006-06-01 19:19:23 +0000295
296 // Recursively clone any reachable successor blocks.
297 const TerminatorInst *TI = BB->getTerminator();
298 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner67ef2412007-03-02 03:11:20 +0000299 ToClone.push_back(TI->getSuccessor(i));
Chris Lattner35033ef2006-06-01 19:19:23 +0000300 }
301
Chris Lattner83f03bf2006-05-27 01:22:24 +0000302 if (CodeInfo) {
303 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner35033ef2006-06-01 19:19:23 +0000304 CodeInfo->ContainsUnwinds |= isa<UnwindInst>(OldTI);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000305 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
306 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
307 BB != &BB->getParent()->front();
308 }
309
310 if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
311 Returns.push_back(RI);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000312}
313
314/// ConstantFoldMappedInstruction - Constant fold the specified instruction,
Devang Patel29d3dd82010-06-23 23:55:51 +0000315/// mapping its operands through VMap if they are available.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000316Constant *PruningFunctionCloner::
317ConstantFoldMappedInstruction(const Instruction *I) {
Chris Lattner9fa038d2007-01-30 23:13:49 +0000318 SmallVector<Constant*, 8> Ops;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000319 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
320 if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
Dan Gohman6cb8c232010-08-26 15:41:53 +0000321 VMap, ModuleLevelChanges)))
Chris Lattner83f03bf2006-05-27 01:22:24 +0000322 Ops.push_back(Op);
323 else
324 return 0; // All operands not constant!
325
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000326 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +0000327 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
328 TD);
Nate Begeman4be30ac2008-04-25 06:37:06 +0000329
Nate Begeman4182db42008-04-25 17:45:52 +0000330 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
Nate Begeman4be30ac2008-04-25 06:37:06 +0000332 if (!LI->isVolatile() && CE->getOpcode() == Instruction::GetElementPtr)
333 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +0000334 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Nate Begeman4be30ac2008-04-25 06:37:06 +0000335 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(),
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000336 CE);
Nate Begeman4be30ac2008-04-25 06:37:06 +0000337
338 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), &Ops[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000339 Ops.size(), TD);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000340}
341
Dan Gohman333a9472010-07-20 23:49:05 +0000342static DebugLoc
343UpdateInlinedAtInfo(const DebugLoc &InsnDL, const DebugLoc &TheCallDL,
344 LLVMContext &Ctx) {
345 DebugLoc NewLoc = TheCallDL;
346 if (MDNode *IA = InsnDL.getInlinedAt(Ctx))
347 NewLoc = UpdateInlinedAtInfo(DebugLoc::getFromDILocation(IA), TheCallDL,
348 Ctx);
Devang Patel53bb5c92009-11-10 23:06:00 +0000349
Dan Gohman333a9472010-07-20 23:49:05 +0000350 return DebugLoc::get(InsnDL.getLine(), InsnDL.getCol(),
351 InsnDL.getScope(Ctx), NewLoc.getAsMDNode(Ctx));
Devang Patel53bb5c92009-11-10 23:06:00 +0000352}
353
Chris Lattner83f03bf2006-05-27 01:22:24 +0000354/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
355/// except that it does some simple constant prop and DCE on the fly. The
356/// effect of this is to copy significantly less code in cases where (for
357/// example) a function call with constant arguments is inlined, and those
358/// constant arguments cause a significant amount of code in the callee to be
Duncan Sandsdc024672007-11-27 13:23:08 +0000359/// dead. Since this doesn't produce an exact copy of the input, it can't be
Chris Lattner83f03bf2006-05-27 01:22:24 +0000360/// used for things like CloneFunction or CloneModule.
361void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000362 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000363 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000364 SmallVectorImpl<ReturnInst*> &Returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000365 const char *NameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000366 ClonedCodeInfo *CodeInfo,
Devang Patel53bb5c92009-11-10 23:06:00 +0000367 const TargetData *TD,
368 Instruction *TheCall) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000369 assert(NameSuffix && "NameSuffix cannot be null!");
370
371#ifndef NDEBUG
Jeff Cohend41b30d2006-11-05 19:31:28 +0000372 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
373 E = OldFunc->arg_end(); II != E; ++II)
Devang Patel29d3dd82010-06-23 23:55:51 +0000374 assert(VMap.count(II) && "No mapping from source argument specified!");
Chris Lattner83f03bf2006-05-27 01:22:24 +0000375#endif
Duncan Sands28c3cff2008-05-26 19:58:59 +0000376
Dan Gohman6cb8c232010-08-26 15:41:53 +0000377 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
378 Returns, NameSuffix, CodeInfo, TD);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000379
380 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner67ef2412007-03-02 03:11:20 +0000381 std::vector<const BasicBlock*> CloneWorklist;
382 CloneWorklist.push_back(&OldFunc->getEntryBlock());
383 while (!CloneWorklist.empty()) {
384 const BasicBlock *BB = CloneWorklist.back();
385 CloneWorklist.pop_back();
386 PFC.CloneBlock(BB, CloneWorklist);
387 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000388
389 // Loop over all of the basic blocks in the old function. If the block was
390 // reachable, we have cloned it and the old block is now in the value map:
391 // insert it into the new function in the right order. If not, ignore it.
392 //
Chris Lattner35033ef2006-06-01 19:19:23 +0000393 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000394 SmallVector<const PHINode*, 16> PHIToResolve;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000395 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
396 BI != BE; ++BI) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000397 BasicBlock *NewBB = cast_or_null<BasicBlock>(VMap[BI]);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000398 if (NewBB == 0) continue; // Dead block.
Chris Lattner35033ef2006-06-01 19:19:23 +0000399
Chris Lattner83f03bf2006-05-27 01:22:24 +0000400 // Add the new block to the new function.
401 NewFunc->getBasicBlockList().push_back(NewBB);
402
403 // Loop over all of the instructions in the block, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000404 // references as we go. This uses VMap to do all the hard work.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000405 //
406 BasicBlock::iterator I = NewBB->begin();
Devang Patel53bb5c92009-11-10 23:06:00 +0000407
Dan Gohman333a9472010-07-20 23:49:05 +0000408 DebugLoc TheCallDL;
409 if (TheCall)
410 TheCallDL = TheCall->getDebugLoc();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000411
412 // Handle PHI nodes specially, as we have to remove references to dead
413 // blocks.
414 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner35033ef2006-06-01 19:19:23 +0000415 // Skip over all PHI nodes, remembering them for later.
416 BasicBlock::const_iterator OldI = BI->begin();
Devang Patel53bb5c92009-11-10 23:06:00 +0000417 for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI) {
Daniel Dunbardfa92612009-11-12 02:52:56 +0000418 if (I->hasMetadata()) {
Dan Gohman333a9472010-07-20 23:49:05 +0000419 if (!TheCallDL.isUnknown()) {
420 DebugLoc IDL = I->getDebugLoc();
421 if (!IDL.isUnknown()) {
422 DebugLoc NewDL = UpdateInlinedAtInfo(IDL, TheCallDL,
423 I->getContext());
424 I->setDebugLoc(NewDL);
Devang Patel53bb5c92009-11-10 23:06:00 +0000425 }
Daniel Dunbardfa92612009-11-12 02:52:56 +0000426 } else {
Devang Patel53bb5c92009-11-10 23:06:00 +0000427 // The cloned instruction has dbg info but the call instruction
428 // does not have dbg info. Remove dbg info from cloned instruction.
Dan Gohman333a9472010-07-20 23:49:05 +0000429 I->setDebugLoc(DebugLoc());
Daniel Dunbardfa92612009-11-12 02:52:56 +0000430 }
431 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000432 PHIToResolve.push_back(cast<PHINode>(OldI));
Devang Patel53bb5c92009-11-10 23:06:00 +0000433 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000434 }
435
Chris Lattner3990b122009-12-28 23:41:32 +0000436 // FIXME:
437 // FIXME:
438 // FIXME: Unclone all this metadata stuff.
439 // FIXME:
440 // FIXME:
441
Chris Lattner83f03bf2006-05-27 01:22:24 +0000442 // Otherwise, remap the rest of the instructions normally.
Devang Patel53bb5c92009-11-10 23:06:00 +0000443 for (; I != NewBB->end(); ++I) {
Daniel Dunbardfa92612009-11-12 02:52:56 +0000444 if (I->hasMetadata()) {
Dan Gohman333a9472010-07-20 23:49:05 +0000445 if (!TheCallDL.isUnknown()) {
446 DebugLoc IDL = I->getDebugLoc();
447 if (!IDL.isUnknown()) {
448 DebugLoc NewDL = UpdateInlinedAtInfo(IDL, TheCallDL,
449 I->getContext());
450 I->setDebugLoc(NewDL);
Devang Patel53bb5c92009-11-10 23:06:00 +0000451 }
Daniel Dunbardfa92612009-11-12 02:52:56 +0000452 } else {
Devang Patel53bb5c92009-11-10 23:06:00 +0000453 // The cloned instruction has dbg info but the call instruction
454 // does not have dbg info. Remove dbg info from cloned instruction.
Dan Gohman333a9472010-07-20 23:49:05 +0000455 I->setDebugLoc(DebugLoc());
Daniel Dunbardfa92612009-11-12 02:52:56 +0000456 }
457 }
Dan Gohman6cb8c232010-08-26 15:41:53 +0000458 RemapInstruction(I, VMap, ModuleLevelChanges);
Devang Patel53bb5c92009-11-10 23:06:00 +0000459 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000460 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000461
462 // Defer PHI resolution until rest of function is resolved, PHI resolution
463 // requires the CFG to be up-to-date.
464 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
465 const PHINode *OPN = PHIToResolve[phino];
Chris Lattner35033ef2006-06-01 19:19:23 +0000466 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattner35033ef2006-06-01 19:19:23 +0000467 const BasicBlock *OldBB = OPN->getParent();
Devang Patel29d3dd82010-06-23 23:55:51 +0000468 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000469
470 // Map operands for blocks that are live and remove operands for blocks
471 // that are dead.
472 for (; phino != PHIToResolve.size() &&
473 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
474 OPN = PHIToResolve[phino];
Devang Patel29d3dd82010-06-23 23:55:51 +0000475 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000476 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
477 if (BasicBlock *MappedBlock =
Devang Patel29d3dd82010-06-23 23:55:51 +0000478 cast_or_null<BasicBlock>(VMap[PN->getIncomingBlock(pred)])) {
Owen Anderson0a205a42009-07-05 22:41:43 +0000479 Value *InVal = MapValue(PN->getIncomingValue(pred),
Dan Gohman6cb8c232010-08-26 15:41:53 +0000480 VMap, ModuleLevelChanges);
Chris Lattner35033ef2006-06-01 19:19:23 +0000481 assert(InVal && "Unknown input value?");
482 PN->setIncomingValue(pred, InVal);
483 PN->setIncomingBlock(pred, MappedBlock);
484 } else {
485 PN->removeIncomingValue(pred, false);
486 --pred, --e; // Revisit the next entry.
487 }
488 }
489 }
490
491 // The loop above has removed PHI entries for those blocks that are dead
492 // and has updated others. However, if a block is live (i.e. copied over)
493 // but its terminator has been changed to not go to this block, then our
494 // phi nodes will have invalid entries. Update the PHI nodes in this
495 // case.
496 PHINode *PN = cast<PHINode>(NewBB->begin());
497 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
498 if (NumPreds != PN->getNumIncomingValues()) {
499 assert(NumPreds < PN->getNumIncomingValues());
500 // Count how many times each predecessor comes to this block.
501 std::map<BasicBlock*, unsigned> PredCount;
502 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
503 PI != E; ++PI)
504 --PredCount[*PI];
505
506 // Figure out how many entries to remove from each PHI.
507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
508 ++PredCount[PN->getIncomingBlock(i)];
509
510 // At this point, the excess predecessor entries are positive in the
511 // map. Loop over all of the PHIs and remove excess predecessor
512 // entries.
513 BasicBlock::iterator I = NewBB->begin();
514 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
515 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
516 E = PredCount.end(); PCI != E; ++PCI) {
517 BasicBlock *Pred = PCI->first;
518 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
519 PN->removeIncomingValue(Pred, false);
520 }
521 }
522 }
523
524 // If the loops above have made these phi nodes have 0 or 1 operand,
525 // replace them with undef or the input value. We must do this for
526 // correctness, because 0-operand phis are not valid.
527 PN = cast<PHINode>(NewBB->begin());
528 if (PN->getNumIncomingValues() == 0) {
529 BasicBlock::iterator I = NewBB->begin();
530 BasicBlock::const_iterator OldI = OldBB->begin();
531 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000532 Value *NV = UndefValue::get(PN->getType());
Chris Lattner35033ef2006-06-01 19:19:23 +0000533 PN->replaceAllUsesWith(NV);
Devang Patel29d3dd82010-06-23 23:55:51 +0000534 assert(VMap[OldI] == PN && "VMap mismatch");
535 VMap[OldI] = NV;
Chris Lattner35033ef2006-06-01 19:19:23 +0000536 PN->eraseFromParent();
537 ++OldI;
538 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000539 }
Chris Lattner8e8eda72007-02-01 18:48:38 +0000540 // NOTE: We cannot eliminate single entry phi nodes here, because of
Devang Patel29d3dd82010-06-23 23:55:51 +0000541 // VMap. Single entry phi nodes can have multiple VMap entries
542 // pointing at them. Thus, deleting one would require scanning the VMap
Chris Lattner8e8eda72007-02-01 18:48:38 +0000543 // to update any entries in it that would require that. This would be
544 // really slow.
Chris Lattner35033ef2006-06-01 19:19:23 +0000545 }
Chris Lattnera4646b62006-09-13 21:27:00 +0000546
547 // Now that the inlined function body has been fully constructed, go through
548 // and zap unconditional fall-through branches. This happen all the time when
549 // specializing code: code specialization turns conditional branches into
550 // uncond branches, and this code folds them.
Devang Patel29d3dd82010-06-23 23:55:51 +0000551 Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
Chris Lattnera4646b62006-09-13 21:27:00 +0000552 while (I != NewFunc->end()) {
553 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
554 if (!BI || BI->isConditional()) { ++I; continue; }
555
Chris Lattner8e8eda72007-02-01 18:48:38 +0000556 // Note that we can't eliminate uncond branches if the destination has
557 // single-entry PHI nodes. Eliminating the single-entry phi nodes would
Devang Patel29d3dd82010-06-23 23:55:51 +0000558 // require scanning the VMap to update any entries that point to the phi
Chris Lattner8e8eda72007-02-01 18:48:38 +0000559 // node.
Chris Lattnera4646b62006-09-13 21:27:00 +0000560 BasicBlock *Dest = BI->getSuccessor(0);
Chris Lattner8e8eda72007-02-01 18:48:38 +0000561 if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
562 ++I; continue;
563 }
Chris Lattnera4646b62006-09-13 21:27:00 +0000564
565 // We know all single-entry PHI nodes in the inlined function have been
566 // removed, so we just need to splice the blocks.
567 BI->eraseFromParent();
568
569 // Move all the instructions in the succ to the pred.
570 I->getInstList().splice(I->end(), Dest->getInstList());
571
572 // Make all PHI nodes that referred to Dest now refer to I as their source.
573 Dest->replaceAllUsesWith(I);
574
575 // Remove the dest block.
576 Dest->eraseFromParent();
577
578 // Do not increment I, iteratively merge all things this block branches to.
579 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000580}