blob: 4aa26fd14fee3dada6307f4afc8379c38b3ed994 [file] [log] [blame]
Chris Lattner8bce9882002-11-19 22:04:49 +00001//===- CloneFunction.cpp - Clone a function into another function ---------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8bce9882002-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 Lattner16bfdb52002-03-29 19:03:54 +000015
Chris Lattner16667512002-11-19 20:59:41 +000016#include "llvm/Transforms/Utils/Cloning.h"
David Majnemer909793f2016-08-04 04:24:02 +000017#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Analysis/InstructionSimplify.h"
Adam Nemet1a689182015-07-10 18:55:09 +000021#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000024#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
Alon Mishne07d949f2014-03-12 14:42:51 +000032#include "llvm/IR/Module.h"
Chandler Carruth772c88b2012-03-28 08:38:27 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
34#include "llvm/Transforms/Utils/Local.h"
Dan Gohmana2095032010-08-24 18:50:07 +000035#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner1bfc7ab2007-02-03 00:08:31 +000036#include <map>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Sanjay Patelabf70232015-03-10 18:41:22 +000039/// See comments in Cloning.h.
Chris Lattnerdf3c3422004-01-09 06:12:26 +000040BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Pateld8dedee2010-06-24 00:00:42 +000041 ValueToValueMapTy &VMap,
Benjamin Kramer1266d462010-01-27 19:58:47 +000042 const Twine &NameSuffix, Function *F,
Chris Lattneredad1282006-01-13 18:39:17 +000043 ClonedCodeInfo *CodeInfo) {
Adrian Prantlc10d0e52017-05-09 19:47:37 +000044 DenseMap<const MDNode *, MDNode *> Cache;
Owen Anderson55f1c092009-08-13 21:58:54 +000045 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattnere9f42322003-04-18 03:50:09 +000046 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
47
Chris Lattneredad1282006-01-13 18:39:17 +000048 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
49
50 // Loop over all instructions, and copy them over.
Chris Lattnere9f42322003-04-18 03:50:09 +000051 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
52 II != IE; ++II) {
Nick Lewycky42fb7452009-09-27 07:38:41 +000053 Instruction *NewInst = II->clone();
Adrian Prantlc10d0e52017-05-09 19:47:37 +000054 if (F && F->getSubprogram())
55 DebugLoc::reparentDebugInfo(*NewInst, BB->getParent()->getSubprogram(),
56 F->getSubprogram(), Cache);
Chris Lattnere9f42322003-04-18 03:50:09 +000057 if (II->hasName())
58 NewInst->setName(II->getName()+NameSuffix);
59 NewBB->getInstList().push_back(NewInst);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +000060 VMap[&*II] = NewInst; // Add instruction map to value.
61
Dale Johannesen900aaa32009-03-10 22:20:02 +000062 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattneredad1282006-01-13 18:39:17 +000063 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
64 if (isa<ConstantInt>(AI->getArraySize()))
65 hasStaticAllocas = true;
66 else
67 hasDynamicAllocas = true;
68 }
69 }
70
71 if (CodeInfo) {
72 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattneredad1282006-01-13 18:39:17 +000073 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
74 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmandcb291f2007-03-22 16:38:57 +000075 BB != &BB->getParent()->getEntryBlock();
Chris Lattnere9f42322003-04-18 03:50:09 +000076 }
77 return NewBB;
78}
79
Chris Lattner16bfdb52002-03-29 19:03:54 +000080// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohmanca26f792010-08-26 15:41:53 +000081// VMap values.
Chris Lattner16bfdb52002-03-29 19:03:54 +000082//
Chris Lattnerdf3c3422004-01-09 06:12:26 +000083void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Pateld8dedee2010-06-24 00:00:42 +000084 ValueToValueMapTy &VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +000085 bool ModuleLevelChanges,
Chris Lattnerd84dbb32009-08-27 04:02:30 +000086 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wang5d44a432011-12-23 02:18:32 +000087 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
James Molloyf6f121e2013-05-28 15:17:05 +000088 ValueMapTypeRemapper *TypeMapper,
89 ValueMaterializer *Materializer) {
Chris Lattnerb1120052002-11-19 21:54:07 +000090 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanb1c93172005-04-21 23:48:37 +000091
Chris Lattnerc3626182002-11-19 22:54:01 +000092#ifndef NDEBUG
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +000093 for (const Argument &I : OldFunc->args())
94 assert(VMap.count(&I) && "No mapping from source argument specified!");
Chris Lattnerc3626182002-11-19 22:54:01 +000095#endif
Chris Lattner16bfdb52002-03-29 19:03:54 +000096
Reid Klecknerb5180542017-03-21 16:57:19 +000097 // Copy all attributes other than those stored in the AttributeList. We need
98 // to remap the parameter indices of the AttributeList.
99 AttributeList NewAttrs = NewFunc->getAttributes();
Reid Kleckner23798a92014-03-26 22:26:35 +0000100 NewFunc->copyAttributesFrom(OldFunc);
101 NewFunc->setAttributes(NewAttrs);
102
Keno Fischer2ac0c272015-11-16 05:13:30 +0000103 // Fix up the personality function that got copied over.
104 if (OldFunc->hasPersonalityFn())
105 NewFunc->setPersonalityFn(
106 MapValue(OldFunc->getPersonalityFn(), VMap,
107 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
108 TypeMapper, Materializer));
109
Reid Kleckner7f720332017-04-13 00:58:09 +0000110 SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
Reid Klecknerb5180542017-03-21 16:57:19 +0000111 AttributeList OldAttrs = OldFunc->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000112
Joey Gouly81259292013-04-10 10:37:38 +0000113 // Clone any argument attributes that are present in the VMap.
Reid Kleckner7f720332017-04-13 00:58:09 +0000114 for (const Argument &OldArg : OldFunc->args()) {
Reid Kleckner23798a92014-03-26 22:26:35 +0000115 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
Reid Kleckner7f720332017-04-13 00:58:09 +0000116 NewArgAttrs[NewArg->getArgNo()] =
Reid Klecknerf021fab2017-04-13 23:12:13 +0000117 OldAttrs.getParamAttributes(OldArg.getArgNo());
Joey Gouly81259292013-04-10 10:37:38 +0000118 }
Reid Kleckner7f720332017-04-13 00:58:09 +0000119 }
Andrew Lenharth5aa1cc42008-10-07 18:08:38 +0000120
Reid Kleckner7f720332017-04-13 00:58:09 +0000121 NewFunc->setAttributes(
122 AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttributes(),
123 OldAttrs.getRetAttributes(), NewArgAttrs));
Anton Korobeynikovd38b3fb2008-03-23 16:03:00 +0000124
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000125 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
126 OldFunc->getAllMetadata(MDs);
Adrian Prantlc10d0e52017-05-09 19:47:37 +0000127 for (auto MD : MDs) {
128 MDNode *NewMD;
129 bool MustCloneSP =
130 (MD.first == LLVMContext::MD_dbg && OldFunc->getParent() &&
131 OldFunc->getParent() == NewFunc->getParent());
132 if (MustCloneSP) {
133 auto *SP = cast<DISubprogram>(MD.second);
134 NewMD = DISubprogram::getDistinct(
135 NewFunc->getContext(), SP->getScope(), SP->getName(),
136 NewFunc->getName(), SP->getFile(), SP->getLine(), SP->getType(),
137 SP->isLocalToUnit(), SP->isDefinition(), SP->getScopeLine(),
138 SP->getContainingType(), SP->getVirtuality(), SP->getVirtualIndex(),
139 SP->getThisAdjustment(), SP->getFlags(), SP->isOptimized(),
140 SP->getUnit(), SP->getTemplateParams(), SP->getDeclaration(),
141 SP->getVariables(), SP->getThrownTypes());
142 } else
143 NewMD =
144 MapMetadata(MD.second, VMap,
145 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
146 TypeMapper, Materializer);
147 NewFunc->addMetadata(MD.first, *NewMD);
148 }
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000149
Chris Lattner16bfdb52002-03-29 19:03:54 +0000150 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerb1120052002-11-19 21:54:07 +0000151 // appropriate. Note that we save BE this way in order to handle cloning of
152 // recursive functions into themselves.
Chris Lattner16bfdb52002-03-29 19:03:54 +0000153 //
154 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
155 BI != BE; ++BI) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000156 const BasicBlock &BB = *BI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000157
Chris Lattnere9f42322003-04-18 03:50:09 +0000158 // Create a new basic block and copy instructions into it!
Chris Lattner43f8d162011-01-08 08:15:20 +0000159 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000160
Eli Friedman688db1d2011-10-21 20:45:19 +0000161 // Add basic block mapping.
162 VMap[&BB] = CBB;
163
164 // It is only legal to clone a function if a block address within that
165 // function is never referenced outside of the function. Given that, we
166 // want to map block addresses from the old function to block addresses in
167 // the clone. (This is different from the generic ValueMapper
168 // implementation, which generates an invalid blockaddress when
169 // cloning a function.)
170 if (BB.hasAddressTaken()) {
171 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
172 const_cast<BasicBlock*>(&BB));
Sanjoy Das1f8fd882015-12-09 20:33:45 +0000173 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
Eli Friedman688db1d2011-10-21 20:45:19 +0000174 }
175
176 // Note return instructions for the caller.
Chris Lattnerb1120052002-11-19 21:54:07 +0000177 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
178 Returns.push_back(RI);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000179 }
180
Misha Brukmanb1c93172005-04-21 23:48:37 +0000181 // Loop over all of the instructions in the function, fixing up operand
Devang Patelb8f11de2010-06-23 23:55:51 +0000182 // references as we go. This uses VMap to do all the hard work.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000183 for (Function::iterator BB =
184 cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
185 BE = NewFunc->end();
186 BB != BE; ++BB)
Chris Lattner16bfdb52002-03-29 19:03:54 +0000187 // Loop over all instructions, fixing each one as we find it...
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000188 for (Instruction &II : *BB)
189 RemapInstruction(&II, VMap,
Mon P Wang5d44a432011-12-23 02:18:32 +0000190 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
James Molloyf6f121e2013-05-28 15:17:05 +0000191 TypeMapper, Materializer);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000192}
Chris Lattnerfb311d22002-11-19 23:12:22 +0000193
Peter Collingbournedba99562016-05-10 20:23:24 +0000194/// Return a copy of the specified function and add it to that function's
195/// module. Also, any references specified in the VMap are changed to refer to
196/// their mapped value instead of the original one. If any of the arguments to
197/// the function are in the VMap, the arguments are deleted from the resultant
198/// function. The VMap is updated to include mappings from all of the
199/// instructions and basicblocks in the function from their old to new values.
Chris Lattnerfb311d22002-11-19 23:12:22 +0000200///
Peter Collingbournedba99562016-05-10 20:23:24 +0000201Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
Chris Lattneredad1282006-01-13 18:39:17 +0000202 ClonedCodeInfo *CodeInfo) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000203 std::vector<Type*> ArgTypes;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000204
205 // The user might be deleting arguments to the function by specifying them in
Devang Patelb8f11de2010-06-23 23:55:51 +0000206 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattnerfb311d22002-11-19 23:12:22 +0000207 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000208 for (const Argument &I : F->args())
209 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
210 ArgTypes.push_back(I.getType());
Chris Lattnerfb311d22002-11-19 23:12:22 +0000211
212 // Create a new function type...
Owen Anderson4056ca92009-07-29 22:17:13 +0000213 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattnerfb311d22002-11-19 23:12:22 +0000214 ArgTypes, F->getFunctionType()->isVarArg());
215
216 // Create the new function...
Peter Collingbournedba99562016-05-10 20:23:24 +0000217 Function *NewF =
218 Function::Create(FTy, F->getLinkage(), F->getName(), F->getParent());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000219
Chris Lattnerfb311d22002-11-19 23:12:22 +0000220 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattner531f9e92005-03-15 04:54:21 +0000221 Function::arg_iterator DestI = NewF->arg_begin();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000222 for (const Argument & I : F->args())
223 if (VMap.count(&I) == 0) { // Is this argument preserved?
224 DestI->setName(I.getName()); // Copy the name over...
225 VMap[&I] = &*DestI++; // Add mapping to VMap
Chris Lattnerfb311d22002-11-19 23:12:22 +0000226 }
227
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000228 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Peter Collingbournedba99562016-05-10 20:23:24 +0000229 CloneFunctionInto(NewF, F, VMap, /*ModuleLevelChanges=*/false, Returns, "",
230 CodeInfo);
231
Misha Brukmanb1c93172005-04-21 23:48:37 +0000232 return NewF;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000233}
Brian Gaeke960707c2003-11-11 22:41:34 +0000234
Chris Lattner3df13f42006-05-27 01:22:24 +0000235
236
237namespace {
Sanjay Patelabf70232015-03-10 18:41:22 +0000238 /// This is a private class used to implement CloneAndPruneFunctionInto.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000239 struct PruningFunctionCloner {
Chris Lattner3df13f42006-05-27 01:22:24 +0000240 Function *NewFunc;
241 const Function *OldFunc;
Devang Pateld8dedee2010-06-24 00:00:42 +0000242 ValueToValueMapTy &VMap;
Dan Gohmanca26f792010-08-26 15:41:53 +0000243 bool ModuleLevelChanges;
Chris Lattner3df13f42006-05-27 01:22:24 +0000244 const char *NameSuffix;
245 ClonedCodeInfo *CodeInfo;
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000246
Chris Lattner3df13f42006-05-27 01:22:24 +0000247 public:
248 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 ValueToValueMapTy &valueMap, bool moduleLevelChanges,
Easwaran Raman7f187292016-01-08 18:23:17 +0000250 const char *nameSuffix, ClonedCodeInfo *codeInfo)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000251 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
252 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
Easwaran Raman7f187292016-01-08 18:23:17 +0000253 CodeInfo(codeInfo) {}
Chris Lattner3df13f42006-05-27 01:22:24 +0000254
Sanjay Patelabf70232015-03-10 18:41:22 +0000255 /// The specified block is found to be reachable, clone it and
Eric Christophera5ec9252014-05-19 16:04:10 +0000256 /// anything that it can reach.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000257 void CloneBlock(const BasicBlock *BB,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000258 BasicBlock::const_iterator StartingInst,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000259 std::vector<const BasicBlock*> &ToClone);
Chris Lattner3df13f42006-05-27 01:22:24 +0000260 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000261}
Chris Lattner3df13f42006-05-27 01:22:24 +0000262
Sanjay Patelabf70232015-03-10 18:41:22 +0000263/// The specified block is found to be reachable, clone it and
Eric Christophera5ec9252014-05-19 16:04:10 +0000264/// anything that it can reach.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000265void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000266 BasicBlock::const_iterator StartingInst,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000267 std::vector<const BasicBlock*> &ToClone){
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000268 WeakTrackingVH &BBEntry = VMap[BB];
Gerolf Hoflehner1da7cbd2014-04-26 05:43:41 +0000269
Eric Christophera5ec9252014-05-19 16:04:10 +0000270 // Have we already cloned this block?
271 if (BBEntry) return;
272
Gerolf Hoflehner3282af12014-04-30 22:05:02 +0000273 // Nope, clone it now.
Eric Christophera5ec9252014-05-19 16:04:10 +0000274 BasicBlock *NewBB;
275 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
276 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
277
278 // It is only legal to clone a function if a block address within that
279 // function is never referenced outside of the function. Given that, we
280 // want to map block addresses from the old function to block addresses in
281 // the clone. (This is different from the generic ValueMapper
282 // implementation, which generates an invalid blockaddress when
283 // cloning a function.)
284 //
285 // Note that we don't need to fix the mapping for unreachable blocks;
286 // the default mapping there is safe.
287 if (BB->hasAddressTaken()) {
288 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
289 const_cast<BasicBlock*>(BB));
290 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
291 }
Eli Friedman688db1d2011-10-21 20:45:19 +0000292
Chris Lattner3df13f42006-05-27 01:22:24 +0000293 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000294
Chris Lattner3df13f42006-05-27 01:22:24 +0000295 // Loop over all instructions, and copy them over, DCE'ing as we go. This
296 // loop doesn't include the terminator.
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000297 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
Chris Lattner3df13f42006-05-27 01:22:24 +0000298 II != IE; ++II) {
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000299
Chandler Carruth21211992012-03-25 04:03:40 +0000300 Instruction *NewInst = II->clone();
301
302 // Eagerly remap operands to the newly cloned instruction, except for PHI
303 // nodes for which we defer processing until we update the CFG.
304 if (!isa<PHINode>(NewInst)) {
305 RemapInstruction(NewInst, VMap,
Easwaran Raman7f187292016-01-08 18:23:17 +0000306 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chandler Carruth21211992012-03-25 04:03:40 +0000307
308 // If we can simplify this instruction to some other value, simply add
309 // a mapping to that value rather than inserting a new instruction into
310 // the basic block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000311 if (Value *V =
312 SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
Chandler Carruth21211992012-03-25 04:03:40 +0000313 // On the off-chance that this simplifies to an instruction in the old
314 // function, map it back into the new function.
315 if (Value *MappedV = VMap.lookup(V))
316 V = MappedV;
317
David Majnemerb8da3a22016-06-25 00:04:10 +0000318 if (!NewInst->mayHaveSideEffects()) {
319 VMap[&*II] = V;
320 delete NewInst;
321 continue;
322 }
Chandler Carruth21211992012-03-25 04:03:40 +0000323 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000324 }
Devang Patel4bed3562009-02-10 07:48:18 +0000325
Chris Lattner3df13f42006-05-27 01:22:24 +0000326 if (II->hasName())
327 NewInst->setName(II->getName()+NameSuffix);
Nico Weberae2ef4c2016-06-24 22:52:39 +0000328 VMap[&*II] = NewInst; // Add instruction map to value.
Chandler Carruth21211992012-03-25 04:03:40 +0000329 NewBB->getInstList().push_back(NewInst);
Dale Johannesen900aaa32009-03-10 22:20:02 +0000330 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Sanjoy Das2d161452015-11-18 06:23:38 +0000331
332 if (CodeInfo)
333 if (auto CS = ImmutableCallSite(&*II))
334 if (CS.hasOperandBundles())
335 CodeInfo->OperandBundleCallSites.push_back(NewInst);
336
Chris Lattner3df13f42006-05-27 01:22:24 +0000337 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
338 if (isa<ConstantInt>(AI->getArraySize()))
339 hasStaticAllocas = true;
340 else
341 hasDynamicAllocas = true;
342 }
343 }
344
Chris Lattnercc340c02006-06-01 19:19:23 +0000345 // Finally, clone over the terminator.
346 const TerminatorInst *OldTI = BB->getTerminator();
347 bool TerminatorDone = false;
348 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
349 if (BI->isConditional()) {
350 // If the condition was a known constant in the callee...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000351 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
352 // Or is a known constant in the caller...
Craig Topperf40110f2014-04-25 05:29:35 +0000353 if (!Cond) {
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000354 Value *V = VMap.lookup(BI->getCondition());
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000355 Cond = dyn_cast_or_null<ConstantInt>(V);
356 }
Zhou Sheng75b871f2007-01-11 12:24:14 +0000357
358 // Constant fold to uncond branch!
359 if (Cond) {
Reid Spencercddc9df2007-01-12 04:24:46 +0000360 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patelb8f11de2010-06-23 23:55:51 +0000361 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000362 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000363 TerminatorDone = true;
364 }
365 }
366 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
367 // If switching on a value known constant in the caller.
368 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +0000369 if (!Cond) { // Or known constant after constant prop in the callee...
Duncan P. N. Exon Smith724c5032016-04-17 20:11:09 +0000370 Value *V = VMap.lookup(SI->getCondition());
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000371 Cond = dyn_cast_or_null<ConstantInt>(V);
372 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000373 if (Cond) { // Constant fold to uncond branch!
Chandler Carruth927d8e62017-04-12 07:27:28 +0000374 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000375 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patelb8f11de2010-06-23 23:55:51 +0000376 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000377 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000378 TerminatorDone = true;
379 }
380 }
381
382 if (!TerminatorDone) {
Nick Lewycky42fb7452009-09-27 07:38:41 +0000383 Instruction *NewInst = OldTI->clone();
Chris Lattnercc340c02006-06-01 19:19:23 +0000384 if (OldTI->hasName())
385 NewInst->setName(OldTI->getName()+NameSuffix);
386 NewBB->getInstList().push_back(NewInst);
Devang Patelb8f11de2010-06-23 23:55:51 +0000387 VMap[OldTI] = NewInst; // Add instruction map to value.
Sanjoy Das2d161452015-11-18 06:23:38 +0000388
389 if (CodeInfo)
390 if (auto CS = ImmutableCallSite(OldTI))
391 if (CS.hasOperandBundles())
392 CodeInfo->OperandBundleCallSites.push_back(NewInst);
393
Chris Lattnercc340c02006-06-01 19:19:23 +0000394 // Recursively clone any reachable successor blocks.
395 const TerminatorInst *TI = BB->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000396 for (const BasicBlock *Succ : TI->successors())
397 ToClone.push_back(Succ);
Chris Lattnercc340c02006-06-01 19:19:23 +0000398 }
399
Chris Lattner3df13f42006-05-27 01:22:24 +0000400 if (CodeInfo) {
401 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner3df13f42006-05-27 01:22:24 +0000402 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
403 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
404 BB != &BB->getParent()->front();
405 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000406}
407
Sanjay Patelabf70232015-03-10 18:41:22 +0000408/// This works like CloneAndPruneFunctionInto, except that it does not clone the
409/// entire function. Instead it starts at an instruction provided by the caller
410/// and copies (and prunes) only the code reachable from that instruction.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000411void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
412 const Instruction *StartingInst,
413 ValueToValueMapTy &VMap,
414 bool ModuleLevelChanges,
415 SmallVectorImpl<ReturnInst *> &Returns,
416 const char *NameSuffix,
417 ClonedCodeInfo *CodeInfo) {
Chris Lattner3df13f42006-05-27 01:22:24 +0000418 assert(NameSuffix && "NameSuffix cannot be null!");
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000419
Andrew Kaylorf22fe4a2015-02-23 20:01:56 +0000420 ValueMapTypeRemapper *TypeMapper = nullptr;
421 ValueMaterializer *Materializer = nullptr;
422
Chris Lattner3df13f42006-05-27 01:22:24 +0000423#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000424 // If the cloning starts at the beginning of the function, verify that
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000425 // the function arguments are mapped.
426 if (!StartingInst)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000427 for (const Argument &II : OldFunc->args())
428 assert(VMap.count(&II) && "No mapping from source argument specified!");
Chris Lattner3df13f42006-05-27 01:22:24 +0000429#endif
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000430
Dan Gohmanca26f792010-08-26 15:41:53 +0000431 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
Easwaran Raman7f187292016-01-08 18:23:17 +0000432 NameSuffix, CodeInfo);
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000433 const BasicBlock *StartingBB;
434 if (StartingInst)
435 StartingBB = StartingInst->getParent();
436 else {
437 StartingBB = &OldFunc->getEntryBlock();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000438 StartingInst = &StartingBB->front();
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000439 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000440
Eric Christophera5ec9252014-05-19 16:04:10 +0000441 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000442 std::vector<const BasicBlock*> CloneWorklist;
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000443 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000444 while (!CloneWorklist.empty()) {
445 const BasicBlock *BB = CloneWorklist.back();
446 CloneWorklist.pop_back();
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000447 PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000448 }
Eric Christophera5ec9252014-05-19 16:04:10 +0000449
Chris Lattner3df13f42006-05-27 01:22:24 +0000450 // Loop over all of the basic blocks in the old function. If the block was
451 // reachable, we have cloned it and the old block is now in the value map:
452 // insert it into the new function in the right order. If not, ignore it.
453 //
Chris Lattnercc340c02006-06-01 19:19:23 +0000454 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000455 SmallVector<const PHINode*, 16> PHIToResolve;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000456 for (const BasicBlock &BI : *OldFunc) {
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000457 Value *V = VMap.lookup(&BI);
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000458 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Eric Christophera5ec9252014-05-19 16:04:10 +0000459 if (!NewBB) continue; // Dead block.
Chris Lattnercc340c02006-06-01 19:19:23 +0000460
Chris Lattner3df13f42006-05-27 01:22:24 +0000461 // Add the new block to the new function.
462 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patelf6eeaeb2009-11-10 23:06:00 +0000463
Chris Lattner3df13f42006-05-27 01:22:24 +0000464 // Handle PHI nodes specially, as we have to remove references to dead
465 // blocks.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000466 for (BasicBlock::const_iterator I = BI.begin(), E = BI.end(); I != E; ++I) {
Andrew Kaylor3170e562015-03-20 21:42:54 +0000467 // PHI nodes may have been remapped to non-PHI nodes by the caller or
468 // during the cloning process.
469 if (const PHINode *PN = dyn_cast<PHINode>(I)) {
470 if (isa<PHINode>(VMap[PN]))
471 PHIToResolve.push_back(PN);
472 else
473 break;
474 } else {
Chandler Carruth21211992012-03-25 04:03:40 +0000475 break;
Andrew Kaylor3170e562015-03-20 21:42:54 +0000476 }
477 }
Chandler Carruth21211992012-03-25 04:03:40 +0000478
479 // Finally, remap the terminator instructions, as those can't be remapped
480 // until all BBs are mapped.
481 RemapInstruction(NewBB->getTerminator(), VMap,
Andrew Kaylorf22fe4a2015-02-23 20:01:56 +0000482 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
483 TypeMapper, Materializer);
Chris Lattner3df13f42006-05-27 01:22:24 +0000484 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000485
486 // Defer PHI resolution until rest of function is resolved, PHI resolution
487 // requires the CFG to be up-to-date.
488 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
489 const PHINode *OPN = PHIToResolve[phino];
Chris Lattnercc340c02006-06-01 19:19:23 +0000490 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattnercc340c02006-06-01 19:19:23 +0000491 const BasicBlock *OldBB = OPN->getParent();
Devang Patelb8f11de2010-06-23 23:55:51 +0000492 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000493
494 // Map operands for blocks that are live and remove operands for blocks
495 // that are dead.
496 for (; phino != PHIToResolve.size() &&
497 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
498 OPN = PHIToResolve[phino];
Devang Patelb8f11de2010-06-23 23:55:51 +0000499 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000500 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Duncan P. N. Exon Smith724c5032016-04-17 20:11:09 +0000501 Value *V = VMap.lookup(PN->getIncomingBlock(pred));
Chris Lattner43f8d162011-01-08 08:15:20 +0000502 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000503 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattner43f8d162011-01-08 08:15:20 +0000504 VMap,
505 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattnercc340c02006-06-01 19:19:23 +0000506 assert(InVal && "Unknown input value?");
507 PN->setIncomingValue(pred, InVal);
508 PN->setIncomingBlock(pred, MappedBlock);
509 } else {
510 PN->removeIncomingValue(pred, false);
Richard Trieu7a083812016-02-18 22:09:30 +0000511 --pred; // Revisit the next entry.
512 --e;
Chris Lattnercc340c02006-06-01 19:19:23 +0000513 }
514 }
515 }
516
517 // The loop above has removed PHI entries for those blocks that are dead
518 // and has updated others. However, if a block is live (i.e. copied over)
519 // but its terminator has been changed to not go to this block, then our
520 // phi nodes will have invalid entries. Update the PHI nodes in this
521 // case.
522 PHINode *PN = cast<PHINode>(NewBB->begin());
523 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
524 if (NumPreds != PN->getNumIncomingValues()) {
525 assert(NumPreds < PN->getNumIncomingValues());
526 // Count how many times each predecessor comes to this block.
527 std::map<BasicBlock*, unsigned> PredCount;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000528 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
529 PI != E; ++PI)
530 --PredCount[*PI];
Chris Lattnercc340c02006-06-01 19:19:23 +0000531
532 // Figure out how many entries to remove from each PHI.
533 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
534 ++PredCount[PN->getIncomingBlock(i)];
535
536 // At this point, the excess predecessor entries are positive in the
537 // map. Loop over all of the PHIs and remove excess predecessor
538 // entries.
539 BasicBlock::iterator I = NewBB->begin();
540 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000541 for (const auto &PCI : PredCount) {
542 BasicBlock *Pred = PCI.first;
543 for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
Chris Lattnercc340c02006-06-01 19:19:23 +0000544 PN->removeIncomingValue(Pred, false);
545 }
546 }
547 }
548
549 // If the loops above have made these phi nodes have 0 or 1 operand,
550 // replace them with undef or the input value. We must do this for
551 // correctness, because 0-operand phis are not valid.
552 PN = cast<PHINode>(NewBB->begin());
553 if (PN->getNumIncomingValues() == 0) {
554 BasicBlock::iterator I = NewBB->begin();
555 BasicBlock::const_iterator OldI = OldBB->begin();
556 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Andersonb292b8c2009-07-30 23:03:37 +0000557 Value *NV = UndefValue::get(PN->getType());
Chris Lattnercc340c02006-06-01 19:19:23 +0000558 PN->replaceAllUsesWith(NV);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000559 assert(VMap[&*OldI] == PN && "VMap mismatch");
560 VMap[&*OldI] = NV;
Chris Lattnercc340c02006-06-01 19:19:23 +0000561 PN->eraseFromParent();
562 ++OldI;
563 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000564 }
565 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000566
567 // Make a second pass over the PHINodes now that all of them have been
568 // remapped into the new function, simplifying the PHINode and performing any
569 // recursive simplifications exposed. This will transparently update the
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000570 // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce
Chandler Carruthef82cf52012-03-25 10:34:54 +0000571 // two PHINodes, the iteration over the old PHIs remains valid, and the
572 // mapping will just map us to the new node (which may not even be a PHI
573 // node).
David Majnemer909793f2016-08-04 04:24:02 +0000574 const DataLayout &DL = NewFunc->getParent()->getDataLayout();
575 SmallSetVector<const Value *, 8> Worklist;
Chandler Carruthef82cf52012-03-25 10:34:54 +0000576 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
David Majnemer909793f2016-08-04 04:24:02 +0000577 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
578 Worklist.insert(PHIToResolve[Idx]);
579
580 // Note that we must test the size on each iteration, the worklist can grow.
581 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
582 const Value *OrigV = Worklist[Idx];
David Majnemer4eefd6b2016-08-04 04:47:18 +0000583 auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
David Majnemer909793f2016-08-04 04:24:02 +0000584 if (!I)
585 continue;
586
David Majnemer5554eda2016-08-19 16:37:40 +0000587 // Skip over non-intrinsic callsites, we don't want to remove any nodes from
588 // the CGSCC.
589 CallSite CS = CallSite(I);
590 if (CS && CS.getCalledFunction() && !CS.getCalledFunction()->isIntrinsic())
591 continue;
592
David Majnemer909793f2016-08-04 04:24:02 +0000593 // See if this instruction simplifies.
594 Value *SimpleV = SimplifyInstruction(I, DL);
595 if (!SimpleV)
596 continue;
597
598 // Stash away all the uses of the old instruction so we can check them for
599 // recursive simplifications after a RAUW. This is cheaper than checking all
600 // uses of To on the recursive step in most cases.
601 for (const User *U : OrigV->users())
602 Worklist.insert(cast<Instruction>(U));
603
604 // Replace the instruction with its simplified value.
605 I->replaceAllUsesWith(SimpleV);
606
607 // If the original instruction had no side effects, remove it.
608 if (isInstructionTriviallyDead(I))
609 I->eraseFromParent();
610 else
611 VMap[OrigV] = I;
612 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000613
Chris Lattner237ccf22006-09-13 21:27:00 +0000614 // Now that the inlined function body has been fully constructed, go through
Sanjay Patel51bd9422015-03-10 18:37:05 +0000615 // and zap unconditional fall-through branches. This happens all the time when
Chris Lattner237ccf22006-09-13 21:27:00 +0000616 // specializing code: code specialization turns conditional branches into
617 // uncond branches, and this code folds them.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000618 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
Chandler Carruth772c88b2012-03-28 08:38:27 +0000619 Function::iterator I = Begin;
Chris Lattner237ccf22006-09-13 21:27:00 +0000620 while (I != NewFunc->end()) {
Chandler Carruth772c88b2012-03-28 08:38:27 +0000621 // Check if this block has become dead during inlining or other
622 // simplifications. Note that the first block will appear dead, as it has
623 // not yet been wired up properly.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000624 if (I != Begin && (pred_begin(&*I) == pred_end(&*I) ||
625 I->getSinglePredecessor() == &*I)) {
626 BasicBlock *DeadBB = &*I++;
Chandler Carruth772c88b2012-03-28 08:38:27 +0000627 DeleteDeadBlock(DeadBB);
628 continue;
629 }
630
631 // We need to simplify conditional branches and switches with a constant
632 // operand. We try to prune these out when cloning, but if the
633 // simplification required looking through PHI nodes, those are only
634 // available after forming the full basic block. That may leave some here,
635 // and we still want to prune the dead code as early as possible.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000636 ConstantFoldTerminator(&*I);
Chandler Carruth772c88b2012-03-28 08:38:27 +0000637
Chris Lattner237ccf22006-09-13 21:27:00 +0000638 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
639 if (!BI || BI->isConditional()) { ++I; continue; }
640
641 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthef82cf52012-03-25 10:34:54 +0000642 if (!Dest->getSinglePredecessor()) {
Chris Lattnerce494222007-02-01 18:48:38 +0000643 ++I; continue;
644 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000645
646 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
647 // above should have zapped all of them..
648 assert(!isa<PHINode>(Dest->begin()));
649
Chris Lattner237ccf22006-09-13 21:27:00 +0000650 // We know all single-entry PHI nodes in the inlined function have been
651 // removed, so we just need to splice the blocks.
652 BI->eraseFromParent();
653
Eric Christopher96513122011-06-23 06:24:52 +0000654 // Make all PHI nodes that referred to Dest now refer to I as their source.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000655 Dest->replaceAllUsesWith(&*I);
Eric Christopher96513122011-06-23 06:24:52 +0000656
Jay Foad61ea0e42011-06-23 09:09:15 +0000657 // Move all the instructions in the succ to the pred.
658 I->getInstList().splice(I->end(), Dest->getInstList());
659
Chris Lattner237ccf22006-09-13 21:27:00 +0000660 // Remove the dest block.
661 Dest->eraseFromParent();
662
663 // Do not increment I, iteratively merge all things this block branches to.
664 }
Chandler Carruth49da9332012-04-06 17:21:31 +0000665
Sanjay Patel51bd9422015-03-10 18:37:05 +0000666 // Make a final pass over the basic blocks from the old function to gather
Chandler Carruth49da9332012-04-06 17:21:31 +0000667 // any return instructions which survived folding. We have to do this here
668 // because we can iteratively remove and merge returns above.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000669 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
Chandler Carruth49da9332012-04-06 17:21:31 +0000670 E = NewFunc->end();
671 I != E; ++I)
672 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
673 Returns.push_back(RI);
Chris Lattner3df13f42006-05-27 01:22:24 +0000674}
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000675
676
Sanjay Patelabf70232015-03-10 18:41:22 +0000677/// This works exactly like CloneFunctionInto,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000678/// except that it does some simple constant prop and DCE on the fly. The
679/// effect of this is to copy significantly less code in cases where (for
680/// example) a function call with constant arguments is inlined, and those
681/// constant arguments cause a significant amount of code in the callee to be
682/// dead. Since this doesn't produce an exact copy of the input, it can't be
683/// used for things like CloneFunction or CloneModule.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000684void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
685 ValueToValueMapTy &VMap,
686 bool ModuleLevelChanges,
687 SmallVectorImpl<ReturnInst*> &Returns,
688 const char *NameSuffix,
689 ClonedCodeInfo *CodeInfo,
690 Instruction *TheCall) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000691 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000692 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000693}
Adam Nemet1a689182015-07-10 18:55:09 +0000694
695/// \brief Remaps instructions in \p Blocks using the mapping in \p VMap.
696void llvm::remapInstructionsInBlocks(
697 const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
698 // Rewrite the code to refer to itself.
699 for (auto *BB : Blocks)
700 for (auto &Inst : *BB)
701 RemapInstruction(&Inst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000702 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Adam Nemet1a689182015-07-10 18:55:09 +0000703}
704
705/// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
706/// Blocks.
707///
708/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
709/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
710Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
711 Loop *OrigLoop, ValueToValueMapTy &VMap,
712 const Twine &NameSuffix, LoopInfo *LI,
713 DominatorTree *DT,
714 SmallVectorImpl<BasicBlock *> &Blocks) {
Vaivaswatha Nagaraj08efb0e2016-04-27 05:25:09 +0000715 assert(OrigLoop->getSubLoops().empty() &&
716 "Loop to be cloned cannot have inner loop");
Adam Nemet1a689182015-07-10 18:55:09 +0000717 Function *F = OrigLoop->getHeader()->getParent();
718 Loop *ParentLoop = OrigLoop->getParentLoop();
719
720 Loop *NewLoop = new Loop();
721 if (ParentLoop)
722 ParentLoop->addChildLoop(NewLoop);
723 else
724 LI->addTopLevelLoop(NewLoop);
725
726 BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
727 assert(OrigPH && "No preheader");
728 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
729 // To rename the loop PHIs.
730 VMap[OrigPH] = NewPH;
731 Blocks.push_back(NewPH);
732
733 // Update LoopInfo.
734 if (ParentLoop)
735 ParentLoop->addBasicBlockToLoop(NewPH, *LI);
736
737 // Update DominatorTree.
738 DT->addNewBlock(NewPH, LoopDomBB);
739
740 for (BasicBlock *BB : OrigLoop->getBlocks()) {
741 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
742 VMap[BB] = NewBB;
743
744 // Update LoopInfo.
745 NewLoop->addBasicBlockToLoop(NewBB, *LI);
746
Vikram TVc702b8b2016-06-11 16:41:10 +0000747 // Add DominatorTree node. After seeing all blocks, update to correct IDom.
748 DT->addNewBlock(NewBB, NewPH);
Adam Nemet1a689182015-07-10 18:55:09 +0000749
750 Blocks.push_back(NewBB);
751 }
752
Vikram TVc702b8b2016-06-11 16:41:10 +0000753 for (BasicBlock *BB : OrigLoop->getBlocks()) {
754 // Update DominatorTree.
755 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
756 DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
757 cast<BasicBlock>(VMap[IDomBB]));
758 }
759
Adam Nemet1a689182015-07-10 18:55:09 +0000760 // Move them physically from the end of the block list.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000761 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
762 NewPH);
763 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
764 NewLoop->getHeader()->getIterator(), F->end());
Adam Nemet1a689182015-07-10 18:55:09 +0000765
766 return NewLoop;
767}
Sanjoy Das8b859c22017-02-17 04:21:14 +0000768
769/// \brief Duplicate non-Phi instructions from the beginning of block up to
770/// StopAt instruction into a split block between BB and its predecessor.
771BasicBlock *
772llvm::DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB,
773 Instruction *StopAt,
774 ValueToValueMapTy &ValueMapping) {
775 // We are going to have to map operands from the original BB block to the new
776 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
777 // account for entry from PredBB.
778 BasicBlock::iterator BI = BB->begin();
779 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
780 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
781
782 BasicBlock *NewBB = SplitEdge(PredBB, BB);
783 NewBB->setName(PredBB->getName() + ".split");
784 Instruction *NewTerm = NewBB->getTerminator();
785
786 // Clone the non-phi instructions of BB into NewBB, keeping track of the
787 // mapping and using it to remap operands in the cloned instructions.
788 for (; StopAt != &*BI; ++BI) {
789 Instruction *New = BI->clone();
790 New->setName(BI->getName());
791 New->insertBefore(NewTerm);
792 ValueMapping[&*BI] = New;
793
794 // Remap operands to patch up intra-block references.
795 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
796 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
797 auto I = ValueMapping.find(Inst);
798 if (I != ValueMapping.end())
799 New->setOperand(i, I->second);
800 }
801 }
802
803 return NewBB;
804}