1f22ef01cSRoman Divacky //===- CloneFunction.cpp - Clone a function into another function ---------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the CloneFunctionInto interface, which is used as the
11f22ef01cSRoman Divacky // low-level function cloner.  This is used by the CloneFunction and function
12f22ef01cSRoman Divacky // inliner to do the dirty work of copying the body of a function around.
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
15f22ef01cSRoman Divacky 
166c4bc1bdSDimitry Andric #include "llvm/ADT/SetVector.h"
17139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h"
18139f7f9bSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
19139f7f9bSDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
20875ed548SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
2191bc56edSDimitry Andric #include "llvm/IR/CFG.h"
22139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
2391bc56edSDimitry Andric #include "llvm/IR/DebugInfo.h"
24139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
25*b5893f02SDimitry Andric #include "llvm/IR/DomTreeUpdater.h"
26139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
27139f7f9bSDimitry Andric #include "llvm/IR/GlobalVariable.h"
28139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
29139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
30139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Metadata.h"
3291bc56edSDimitry Andric #include "llvm/IR/Module.h"
33dff0c46cSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34db17bf38SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
35*b5893f02SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
36e580952dSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
37f22ef01cSRoman Divacky #include <map>
38f22ef01cSRoman Divacky using namespace llvm;
39f22ef01cSRoman Divacky 
40ff0cc061SDimitry Andric /// See comments in Cloning.h.
CloneBasicBlock(const BasicBlock * BB,ValueToValueMapTy & VMap,const Twine & NameSuffix,Function * F,ClonedCodeInfo * CodeInfo,DebugInfoFinder * DIFinder)416d97bb29SDimitry Andric BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
42f22ef01cSRoman Divacky                                   const Twine &NameSuffix, Function *F,
436d97bb29SDimitry Andric                                   ClonedCodeInfo *CodeInfo,
446d97bb29SDimitry Andric                                   DebugInfoFinder *DIFinder) {
455517e702SDimitry Andric   DenseMap<const MDNode *, MDNode *> Cache;
46f22ef01cSRoman Divacky   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
474ba319b5SDimitry Andric   if (BB->hasName())
484ba319b5SDimitry Andric     NewBB->setName(BB->getName() + NameSuffix);
49f22ef01cSRoman Divacky 
50f22ef01cSRoman Divacky   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
51c4394386SDimitry Andric   Module *TheModule = F ? F->getParent() : nullptr;
52f22ef01cSRoman Divacky 
53f22ef01cSRoman Divacky   // Loop over all instructions, and copy them over.
544ba319b5SDimitry Andric   for (const Instruction &I : *BB) {
554ba319b5SDimitry Andric     if (DIFinder && TheModule)
564ba319b5SDimitry Andric       DIFinder->processInstruction(*TheModule, I);
576d97bb29SDimitry Andric 
584ba319b5SDimitry Andric     Instruction *NewInst = I.clone();
594ba319b5SDimitry Andric     if (I.hasName())
604ba319b5SDimitry Andric       NewInst->setName(I.getName() + NameSuffix);
61f22ef01cSRoman Divacky     NewBB->getInstList().push_back(NewInst);
624ba319b5SDimitry Andric     VMap[&I] = NewInst; // Add instruction map to value.
63f22ef01cSRoman Divacky 
644ba319b5SDimitry Andric     hasCalls |= (isa<CallInst>(I) && !isa<DbgInfoIntrinsic>(I));
654ba319b5SDimitry Andric     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
66f22ef01cSRoman Divacky       if (isa<ConstantInt>(AI->getArraySize()))
67f22ef01cSRoman Divacky         hasStaticAllocas = true;
68f22ef01cSRoman Divacky       else
69f22ef01cSRoman Divacky         hasDynamicAllocas = true;
70f22ef01cSRoman Divacky     }
71f22ef01cSRoman Divacky   }
72f22ef01cSRoman Divacky 
73f22ef01cSRoman Divacky   if (CodeInfo) {
74f22ef01cSRoman Divacky     CodeInfo->ContainsCalls          |= hasCalls;
75f22ef01cSRoman Divacky     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
76f22ef01cSRoman Divacky     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
77f22ef01cSRoman Divacky                                         BB != &BB->getParent()->getEntryBlock();
78f22ef01cSRoman Divacky   }
79f22ef01cSRoman Divacky   return NewBB;
80f22ef01cSRoman Divacky }
81f22ef01cSRoman Divacky 
82f22ef01cSRoman Divacky // Clone OldFunc into NewFunc, transforming the old arguments into references to
83e580952dSDimitry Andric // VMap values.
84f22ef01cSRoman Divacky //
CloneFunctionInto(Function * NewFunc,const Function * OldFunc,ValueToValueMapTy & VMap,bool ModuleLevelChanges,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo,ValueMapTypeRemapper * TypeMapper,ValueMaterializer * Materializer)85f22ef01cSRoman Divacky void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
86ffd1746dSEd Schouten                              ValueToValueMapTy &VMap,
87e580952dSDimitry Andric                              bool ModuleLevelChanges,
88f22ef01cSRoman Divacky                              SmallVectorImpl<ReturnInst*> &Returns,
89dff0c46cSDimitry Andric                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
90f785676fSDimitry Andric                              ValueMapTypeRemapper *TypeMapper,
91f785676fSDimitry Andric                              ValueMaterializer *Materializer) {
92f22ef01cSRoman Divacky   assert(NameSuffix && "NameSuffix cannot be null!");
93f22ef01cSRoman Divacky 
94f22ef01cSRoman Divacky #ifndef NDEBUG
957d523365SDimitry Andric   for (const Argument &I : OldFunc->args())
967d523365SDimitry Andric     assert(VMap.count(&I) && "No mapping from source argument specified!");
97f22ef01cSRoman Divacky #endif
98f22ef01cSRoman Divacky 
997a7e6055SDimitry Andric   // Copy all attributes other than those stored in the AttributeList.  We need
1007a7e6055SDimitry Andric   // to remap the parameter indices of the AttributeList.
1017a7e6055SDimitry Andric   AttributeList NewAttrs = NewFunc->getAttributes();
10291bc56edSDimitry Andric   NewFunc->copyAttributesFrom(OldFunc);
10391bc56edSDimitry Andric   NewFunc->setAttributes(NewAttrs);
10491bc56edSDimitry Andric 
1057d523365SDimitry Andric   // Fix up the personality function that got copied over.
1067d523365SDimitry Andric   if (OldFunc->hasPersonalityFn())
1077d523365SDimitry Andric     NewFunc->setPersonalityFn(
1087d523365SDimitry Andric         MapValue(OldFunc->getPersonalityFn(), VMap,
1097d523365SDimitry Andric                  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
1107d523365SDimitry Andric                  TypeMapper, Materializer));
1117d523365SDimitry Andric 
1127a7e6055SDimitry Andric   SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
1137a7e6055SDimitry Andric   AttributeList OldAttrs = OldFunc->getAttributes();
1147a7e6055SDimitry Andric 
115284c1978SDimitry Andric   // Clone any argument attributes that are present in the VMap.
1167a7e6055SDimitry Andric   for (const Argument &OldArg : OldFunc->args()) {
11791bc56edSDimitry Andric     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
1187a7e6055SDimitry Andric       NewArgAttrs[NewArg->getArgNo()] =
1197a7e6055SDimitry Andric           OldAttrs.getParamAttributes(OldArg.getArgNo());
1207a7e6055SDimitry Andric     }
121139f7f9bSDimitry Andric   }
122284c1978SDimitry Andric 
12391bc56edSDimitry Andric   NewFunc->setAttributes(
1247a7e6055SDimitry Andric       AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttributes(),
1257a7e6055SDimitry Andric                          OldAttrs.getRetAttributes(), NewArgAttrs));
126f22ef01cSRoman Divacky 
1276d97bb29SDimitry Andric   bool MustCloneSP =
1286d97bb29SDimitry Andric       OldFunc->getParent() && OldFunc->getParent() == NewFunc->getParent();
1296d97bb29SDimitry Andric   DISubprogram *SP = OldFunc->getSubprogram();
1306d97bb29SDimitry Andric   if (SP) {
1316d97bb29SDimitry Andric     assert(!MustCloneSP || ModuleLevelChanges);
1326d97bb29SDimitry Andric     // Add mappings for some DebugInfo nodes that we don't want duplicated
1336d97bb29SDimitry Andric     // even if they're distinct.
1346d97bb29SDimitry Andric     auto &MD = VMap.MD();
1356d97bb29SDimitry Andric     MD[SP->getUnit()].reset(SP->getUnit());
1366d97bb29SDimitry Andric     MD[SP->getType()].reset(SP->getType());
1376d97bb29SDimitry Andric     MD[SP->getFile()].reset(SP->getFile());
1386d97bb29SDimitry Andric     // If we're not cloning into the same module, no need to clone the
1396d97bb29SDimitry Andric     // subprogram
1406d97bb29SDimitry Andric     if (!MustCloneSP)
1416d97bb29SDimitry Andric       MD[SP].reset(SP);
1426d97bb29SDimitry Andric   }
1436d97bb29SDimitry Andric 
1443ca95b02SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1453ca95b02SDimitry Andric   OldFunc->getAllMetadata(MDs);
1465517e702SDimitry Andric   for (auto MD : MDs) {
1476d97bb29SDimitry Andric     NewFunc->addMetadata(
1486d97bb29SDimitry Andric         MD.first,
1496d97bb29SDimitry Andric         *MapMetadata(MD.second, VMap,
1503ca95b02SDimitry Andric                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
1516d97bb29SDimitry Andric                      TypeMapper, Materializer));
1525517e702SDimitry Andric   }
1533ca95b02SDimitry Andric 
1546d97bb29SDimitry Andric   // When we remap instructions, we want to avoid duplicating inlined
1556d97bb29SDimitry Andric   // DISubprograms, so record all subprograms we find as we duplicate
1566d97bb29SDimitry Andric   // instructions and then freeze them in the MD map.
157c4394386SDimitry Andric   // We also record information about dbg.value and dbg.declare to avoid
158c4394386SDimitry Andric   // duplicating the types.
1596d97bb29SDimitry Andric   DebugInfoFinder DIFinder;
1606d97bb29SDimitry Andric 
161f22ef01cSRoman Divacky   // Loop over all of the basic blocks in the function, cloning them as
162f22ef01cSRoman Divacky   // appropriate.  Note that we save BE this way in order to handle cloning of
163f22ef01cSRoman Divacky   // recursive functions into themselves.
164f22ef01cSRoman Divacky   //
165f22ef01cSRoman Divacky   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
166f22ef01cSRoman Divacky        BI != BE; ++BI) {
167f22ef01cSRoman Divacky     const BasicBlock &BB = *BI;
168f22ef01cSRoman Divacky 
169f22ef01cSRoman Divacky     // Create a new basic block and copy instructions into it!
1706d97bb29SDimitry Andric     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
1714ba319b5SDimitry Andric                                       ModuleLevelChanges ? &DIFinder : nullptr);
172f22ef01cSRoman Divacky 
173dff0c46cSDimitry Andric     // Add basic block mapping.
174dff0c46cSDimitry Andric     VMap[&BB] = CBB;
175dff0c46cSDimitry Andric 
176dff0c46cSDimitry Andric     // It is only legal to clone a function if a block address within that
177dff0c46cSDimitry Andric     // function is never referenced outside of the function.  Given that, we
178dff0c46cSDimitry Andric     // want to map block addresses from the old function to block addresses in
179dff0c46cSDimitry Andric     // the clone. (This is different from the generic ValueMapper
180dff0c46cSDimitry Andric     // implementation, which generates an invalid blockaddress when
181dff0c46cSDimitry Andric     // cloning a function.)
182dff0c46cSDimitry Andric     if (BB.hasAddressTaken()) {
183dff0c46cSDimitry Andric       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
184dff0c46cSDimitry Andric                                               const_cast<BasicBlock*>(&BB));
185dff0c46cSDimitry Andric       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
186dff0c46cSDimitry Andric     }
187dff0c46cSDimitry Andric 
188dff0c46cSDimitry Andric     // Note return instructions for the caller.
189f22ef01cSRoman Divacky     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
190f22ef01cSRoman Divacky       Returns.push_back(RI);
191f22ef01cSRoman Divacky   }
192f22ef01cSRoman Divacky 
1934ba319b5SDimitry Andric   for (DISubprogram *ISP : DIFinder.subprograms())
1944ba319b5SDimitry Andric     if (ISP != SP)
1956d97bb29SDimitry Andric       VMap.MD()[ISP].reset(ISP);
1966d97bb29SDimitry Andric 
1974ba319b5SDimitry Andric   for (DICompileUnit *CU : DIFinder.compile_units())
1984ba319b5SDimitry Andric     VMap.MD()[CU].reset(CU);
1994ba319b5SDimitry Andric 
2004ba319b5SDimitry Andric   for (DIType *Type : DIFinder.types())
201c4394386SDimitry Andric     VMap.MD()[Type].reset(Type);
202c4394386SDimitry Andric 
203f22ef01cSRoman Divacky   // Loop over all of the instructions in the function, fixing up operand
204ffd1746dSEd Schouten   // references as we go.  This uses VMap to do all the hard work.
2057d523365SDimitry Andric   for (Function::iterator BB =
2067d523365SDimitry Andric            cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
2077d523365SDimitry Andric                           BE = NewFunc->end();
2087d523365SDimitry Andric        BB != BE; ++BB)
209f22ef01cSRoman Divacky     // Loop over all instructions, fixing each one as we find it...
2107d523365SDimitry Andric     for (Instruction &II : *BB)
2117d523365SDimitry Andric       RemapInstruction(&II, VMap,
212dff0c46cSDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
213f785676fSDimitry Andric                        TypeMapper, Materializer);
214f22ef01cSRoman Divacky }
215f22ef01cSRoman Divacky 
2163ca95b02SDimitry Andric /// Return a copy of the specified function and add it to that function's
2173ca95b02SDimitry Andric /// module.  Also, any references specified in the VMap are changed to refer to
2183ca95b02SDimitry Andric /// their mapped value instead of the original one.  If any of the arguments to
2193ca95b02SDimitry Andric /// the function are in the VMap, the arguments are deleted from the resultant
2203ca95b02SDimitry Andric /// function.  The VMap is updated to include mappings from all of the
2213ca95b02SDimitry Andric /// instructions and basicblocks in the function from their old to new values.
222f22ef01cSRoman Divacky ///
CloneFunction(Function * F,ValueToValueMapTy & VMap,ClonedCodeInfo * CodeInfo)2233ca95b02SDimitry Andric Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
224f22ef01cSRoman Divacky                               ClonedCodeInfo *CodeInfo) {
22517a519f9SDimitry Andric   std::vector<Type*> ArgTypes;
226f22ef01cSRoman Divacky 
227f22ef01cSRoman Divacky   // The user might be deleting arguments to the function by specifying them in
228ffd1746dSEd Schouten   // the VMap.  If so, we need to not add the arguments to the arg ty vector
229f22ef01cSRoman Divacky   //
2307d523365SDimitry Andric   for (const Argument &I : F->args())
2317d523365SDimitry Andric     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
2327d523365SDimitry Andric       ArgTypes.push_back(I.getType());
233f22ef01cSRoman Divacky 
234f22ef01cSRoman Divacky   // Create a new function type...
235f22ef01cSRoman Divacky   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
236f22ef01cSRoman Divacky                                     ArgTypes, F->getFunctionType()->isVarArg());
237f22ef01cSRoman Divacky 
238f22ef01cSRoman Divacky   // Create the new function...
239*b5893f02SDimitry Andric   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
240*b5893f02SDimitry Andric                                     F->getName(), F->getParent());
241f22ef01cSRoman Divacky 
242f22ef01cSRoman Divacky   // Loop over the arguments, copying the names of the mapped arguments over...
243f22ef01cSRoman Divacky   Function::arg_iterator DestI = NewF->arg_begin();
2447d523365SDimitry Andric   for (const Argument & I : F->args())
2457d523365SDimitry Andric     if (VMap.count(&I) == 0) {     // Is this argument preserved?
2467d523365SDimitry Andric       DestI->setName(I.getName()); // Copy the name over...
2477d523365SDimitry Andric       VMap[&I] = &*DestI++;        // Add mapping to VMap
248f22ef01cSRoman Divacky     }
249f22ef01cSRoman Divacky 
250f22ef01cSRoman Divacky   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
2516d97bb29SDimitry Andric   CloneFunctionInto(NewF, F, VMap, F->getSubprogram() != nullptr, Returns, "",
2523ca95b02SDimitry Andric                     CodeInfo);
2533ca95b02SDimitry Andric 
254f22ef01cSRoman Divacky   return NewF;
255f22ef01cSRoman Divacky }
256f22ef01cSRoman Divacky 
257f22ef01cSRoman Divacky 
258f22ef01cSRoman Divacky 
259f22ef01cSRoman Divacky namespace {
260ff0cc061SDimitry Andric   /// This is a private class used to implement CloneAndPruneFunctionInto.
261f22ef01cSRoman Divacky   struct PruningFunctionCloner {
262f22ef01cSRoman Divacky     Function *NewFunc;
263f22ef01cSRoman Divacky     const Function *OldFunc;
264ffd1746dSEd Schouten     ValueToValueMapTy &VMap;
265e580952dSDimitry Andric     bool ModuleLevelChanges;
266f22ef01cSRoman Divacky     const char *NameSuffix;
267f22ef01cSRoman Divacky     ClonedCodeInfo *CodeInfo;
268ff0cc061SDimitry Andric 
269f22ef01cSRoman Divacky   public:
PruningFunctionCloner__anonf2c8084a0111::PruningFunctionCloner270f22ef01cSRoman Divacky     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
271ff0cc061SDimitry Andric                           ValueToValueMapTy &valueMap, bool moduleLevelChanges,
272444ed5c5SDimitry Andric                           const char *nameSuffix, ClonedCodeInfo *codeInfo)
273ff0cc061SDimitry Andric         : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
274ff0cc061SDimitry Andric           ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
275444ed5c5SDimitry Andric           CodeInfo(codeInfo) {}
276f22ef01cSRoman Divacky 
277ff0cc061SDimitry Andric     /// The specified block is found to be reachable, clone it and
278f22ef01cSRoman Divacky     /// anything that it can reach.
279f22ef01cSRoman Divacky     void CloneBlock(const BasicBlock *BB,
280ff0cc061SDimitry Andric                     BasicBlock::const_iterator StartingInst,
281f22ef01cSRoman Divacky                     std::vector<const BasicBlock*> &ToClone);
282f22ef01cSRoman Divacky   };
2833dac3a9bSDimitry Andric }
284f22ef01cSRoman Divacky 
285ff0cc061SDimitry Andric /// The specified block is found to be reachable, clone it and
286f22ef01cSRoman Divacky /// anything that it can reach.
CloneBlock(const BasicBlock * BB,BasicBlock::const_iterator StartingInst,std::vector<const BasicBlock * > & ToClone)287f22ef01cSRoman Divacky void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
288ff0cc061SDimitry Andric                                        BasicBlock::const_iterator StartingInst,
289f22ef01cSRoman Divacky                                        std::vector<const BasicBlock*> &ToClone){
290f37b6182SDimitry Andric   WeakTrackingVH &BBEntry = VMap[BB];
291f22ef01cSRoman Divacky 
292f22ef01cSRoman Divacky   // Have we already cloned this block?
293f22ef01cSRoman Divacky   if (BBEntry) return;
294f22ef01cSRoman Divacky 
295f22ef01cSRoman Divacky   // Nope, clone it now.
296f22ef01cSRoman Divacky   BasicBlock *NewBB;
297f22ef01cSRoman Divacky   BBEntry = NewBB = BasicBlock::Create(BB->getContext());
298f22ef01cSRoman Divacky   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
299f22ef01cSRoman Divacky 
300dff0c46cSDimitry Andric   // It is only legal to clone a function if a block address within that
301dff0c46cSDimitry Andric   // function is never referenced outside of the function.  Given that, we
302dff0c46cSDimitry Andric   // want to map block addresses from the old function to block addresses in
303dff0c46cSDimitry Andric   // the clone. (This is different from the generic ValueMapper
304dff0c46cSDimitry Andric   // implementation, which generates an invalid blockaddress when
305dff0c46cSDimitry Andric   // cloning a function.)
306dff0c46cSDimitry Andric   //
307dff0c46cSDimitry Andric   // Note that we don't need to fix the mapping for unreachable blocks;
308dff0c46cSDimitry Andric   // the default mapping there is safe.
309dff0c46cSDimitry Andric   if (BB->hasAddressTaken()) {
310dff0c46cSDimitry Andric     Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
311dff0c46cSDimitry Andric                                             const_cast<BasicBlock*>(BB));
312dff0c46cSDimitry Andric     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
313dff0c46cSDimitry Andric   }
314dff0c46cSDimitry Andric 
315f22ef01cSRoman Divacky   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
316f22ef01cSRoman Divacky 
317f22ef01cSRoman Divacky   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
318f22ef01cSRoman Divacky   // loop doesn't include the terminator.
319ff0cc061SDimitry Andric   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
320f22ef01cSRoman Divacky        II != IE; ++II) {
321ff0cc061SDimitry Andric 
322dff0c46cSDimitry Andric     Instruction *NewInst = II->clone();
323dff0c46cSDimitry Andric 
324dff0c46cSDimitry Andric     // Eagerly remap operands to the newly cloned instruction, except for PHI
325dff0c46cSDimitry Andric     // nodes for which we defer processing until we update the CFG.
326dff0c46cSDimitry Andric     if (!isa<PHINode>(NewInst)) {
327dff0c46cSDimitry Andric       RemapInstruction(NewInst, VMap,
328444ed5c5SDimitry Andric                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
329dff0c46cSDimitry Andric 
330dff0c46cSDimitry Andric       // If we can simplify this instruction to some other value, simply add
331dff0c46cSDimitry Andric       // a mapping to that value rather than inserting a new instruction into
332dff0c46cSDimitry Andric       // the basic block.
333ff0cc061SDimitry Andric       if (Value *V =
334ff0cc061SDimitry Andric               SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
335dff0c46cSDimitry Andric         // On the off-chance that this simplifies to an instruction in the old
336dff0c46cSDimitry Andric         // function, map it back into the new function.
3370fa43771SDimitry Andric         if (NewFunc != OldFunc)
338dff0c46cSDimitry Andric           if (Value *MappedV = VMap.lookup(V))
339dff0c46cSDimitry Andric             V = MappedV;
340dff0c46cSDimitry Andric 
3413ca95b02SDimitry Andric         if (!NewInst->mayHaveSideEffects()) {
3427d523365SDimitry Andric           VMap[&*II] = V;
343d8866befSDimitry Andric           NewInst->deleteValue();
344f22ef01cSRoman Divacky           continue;
345f22ef01cSRoman Divacky         }
346dff0c46cSDimitry Andric       }
3473ca95b02SDimitry Andric     }
348f22ef01cSRoman Divacky 
349f22ef01cSRoman Divacky     if (II->hasName())
350f22ef01cSRoman Divacky       NewInst->setName(II->getName()+NameSuffix);
3517d523365SDimitry Andric     VMap[&*II] = NewInst; // Add instruction map to value.
352dff0c46cSDimitry Andric     NewBB->getInstList().push_back(NewInst);
353f22ef01cSRoman Divacky     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
3547d523365SDimitry Andric 
3557d523365SDimitry Andric     if (CodeInfo)
3567d523365SDimitry Andric       if (auto CS = ImmutableCallSite(&*II))
3577d523365SDimitry Andric         if (CS.hasOperandBundles())
3587d523365SDimitry Andric           CodeInfo->OperandBundleCallSites.push_back(NewInst);
3597d523365SDimitry Andric 
360f22ef01cSRoman Divacky     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
361f22ef01cSRoman Divacky       if (isa<ConstantInt>(AI->getArraySize()))
362f22ef01cSRoman Divacky         hasStaticAllocas = true;
363f22ef01cSRoman Divacky       else
364f22ef01cSRoman Divacky         hasDynamicAllocas = true;
365f22ef01cSRoman Divacky     }
366f22ef01cSRoman Divacky   }
367f22ef01cSRoman Divacky 
368f22ef01cSRoman Divacky   // Finally, clone over the terminator.
369*b5893f02SDimitry Andric   const Instruction *OldTI = BB->getTerminator();
370f22ef01cSRoman Divacky   bool TerminatorDone = false;
371f22ef01cSRoman Divacky   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
372f22ef01cSRoman Divacky     if (BI->isConditional()) {
373f22ef01cSRoman Divacky       // If the condition was a known constant in the callee...
374f22ef01cSRoman Divacky       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
375f22ef01cSRoman Divacky       // Or is a known constant in the caller...
37691bc56edSDimitry Andric       if (!Cond) {
3773ca95b02SDimitry Andric         Value *V = VMap.lookup(BI->getCondition());
3782754fe60SDimitry Andric         Cond = dyn_cast_or_null<ConstantInt>(V);
3792754fe60SDimitry Andric       }
380f22ef01cSRoman Divacky 
381f22ef01cSRoman Divacky       // Constant fold to uncond branch!
382f22ef01cSRoman Divacky       if (Cond) {
383f22ef01cSRoman Divacky         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
384ffd1746dSEd Schouten         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
385f22ef01cSRoman Divacky         ToClone.push_back(Dest);
386f22ef01cSRoman Divacky         TerminatorDone = true;
387f22ef01cSRoman Divacky       }
388f22ef01cSRoman Divacky     }
389f22ef01cSRoman Divacky   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
390f22ef01cSRoman Divacky     // If switching on a value known constant in the caller.
391f22ef01cSRoman Divacky     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
39291bc56edSDimitry Andric     if (!Cond) { // Or known constant after constant prop in the callee...
3933ca95b02SDimitry Andric       Value *V = VMap.lookup(SI->getCondition());
3942754fe60SDimitry Andric       Cond = dyn_cast_or_null<ConstantInt>(V);
3952754fe60SDimitry Andric     }
396f22ef01cSRoman Divacky     if (Cond) {     // Constant fold to uncond branch!
3977a7e6055SDimitry Andric       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
398dff0c46cSDimitry Andric       BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
399ffd1746dSEd Schouten       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
400f22ef01cSRoman Divacky       ToClone.push_back(Dest);
401f22ef01cSRoman Divacky       TerminatorDone = true;
402f22ef01cSRoman Divacky     }
403f22ef01cSRoman Divacky   }
404f22ef01cSRoman Divacky 
405f22ef01cSRoman Divacky   if (!TerminatorDone) {
406f22ef01cSRoman Divacky     Instruction *NewInst = OldTI->clone();
407f22ef01cSRoman Divacky     if (OldTI->hasName())
408f22ef01cSRoman Divacky       NewInst->setName(OldTI->getName()+NameSuffix);
409f22ef01cSRoman Divacky     NewBB->getInstList().push_back(NewInst);
410ffd1746dSEd Schouten     VMap[OldTI] = NewInst;             // Add instruction map to value.
411f22ef01cSRoman Divacky 
4127d523365SDimitry Andric     if (CodeInfo)
4137d523365SDimitry Andric       if (auto CS = ImmutableCallSite(OldTI))
4147d523365SDimitry Andric         if (CS.hasOperandBundles())
4157d523365SDimitry Andric           CodeInfo->OperandBundleCallSites.push_back(NewInst);
4167d523365SDimitry Andric 
417f22ef01cSRoman Divacky     // Recursively clone any reachable successor blocks.
418*b5893f02SDimitry Andric     const Instruction *TI = BB->getTerminator();
419*b5893f02SDimitry Andric     for (const BasicBlock *Succ : successors(TI))
4207d523365SDimitry Andric       ToClone.push_back(Succ);
421f22ef01cSRoman Divacky   }
422f22ef01cSRoman Divacky 
423f22ef01cSRoman Divacky   if (CodeInfo) {
424f22ef01cSRoman Divacky     CodeInfo->ContainsCalls          |= hasCalls;
425f22ef01cSRoman Divacky     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
426f22ef01cSRoman Divacky     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
427f22ef01cSRoman Divacky       BB != &BB->getParent()->front();
428f22ef01cSRoman Divacky   }
429f22ef01cSRoman Divacky }
430f22ef01cSRoman Divacky 
431ff0cc061SDimitry Andric /// This works like CloneAndPruneFunctionInto, except that it does not clone the
432ff0cc061SDimitry Andric /// entire function. Instead it starts at an instruction provided by the caller
433ff0cc061SDimitry Andric /// and copies (and prunes) only the code reachable from that instruction.
CloneAndPruneIntoFromInst(Function * NewFunc,const Function * OldFunc,const Instruction * StartingInst,ValueToValueMapTy & VMap,bool ModuleLevelChanges,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo)434ff0cc061SDimitry Andric void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
435ff0cc061SDimitry Andric                                      const Instruction *StartingInst,
436ffd1746dSEd Schouten                                      ValueToValueMapTy &VMap,
437e580952dSDimitry Andric                                      bool ModuleLevelChanges,
438f22ef01cSRoman Divacky                                      SmallVectorImpl<ReturnInst *> &Returns,
439f22ef01cSRoman Divacky                                      const char *NameSuffix,
440444ed5c5SDimitry Andric                                      ClonedCodeInfo *CodeInfo) {
441f22ef01cSRoman Divacky   assert(NameSuffix && "NameSuffix cannot be null!");
442f22ef01cSRoman Divacky 
443ff0cc061SDimitry Andric   ValueMapTypeRemapper *TypeMapper = nullptr;
444ff0cc061SDimitry Andric   ValueMaterializer *Materializer = nullptr;
445ff0cc061SDimitry Andric 
446f22ef01cSRoman Divacky #ifndef NDEBUG
4477d523365SDimitry Andric   // If the cloning starts at the beginning of the function, verify that
448ff0cc061SDimitry Andric   // the function arguments are mapped.
449ff0cc061SDimitry Andric   if (!StartingInst)
4507d523365SDimitry Andric     for (const Argument &II : OldFunc->args())
4517d523365SDimitry Andric       assert(VMap.count(&II) && "No mapping from source argument specified!");
452f22ef01cSRoman Divacky #endif
453f22ef01cSRoman Divacky 
454e580952dSDimitry Andric   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
455444ed5c5SDimitry Andric                             NameSuffix, CodeInfo);
456ff0cc061SDimitry Andric   const BasicBlock *StartingBB;
457ff0cc061SDimitry Andric   if (StartingInst)
458ff0cc061SDimitry Andric     StartingBB = StartingInst->getParent();
459ff0cc061SDimitry Andric   else {
460ff0cc061SDimitry Andric     StartingBB = &OldFunc->getEntryBlock();
4617d523365SDimitry Andric     StartingInst = &StartingBB->front();
462ff0cc061SDimitry Andric   }
463f22ef01cSRoman Divacky 
464f22ef01cSRoman Divacky   // Clone the entry block, and anything recursively reachable from it.
465f22ef01cSRoman Divacky   std::vector<const BasicBlock*> CloneWorklist;
4667d523365SDimitry Andric   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
467f22ef01cSRoman Divacky   while (!CloneWorklist.empty()) {
468f22ef01cSRoman Divacky     const BasicBlock *BB = CloneWorklist.back();
469f22ef01cSRoman Divacky     CloneWorklist.pop_back();
470ff0cc061SDimitry Andric     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
471f22ef01cSRoman Divacky   }
472f22ef01cSRoman Divacky 
473f22ef01cSRoman Divacky   // Loop over all of the basic blocks in the old function.  If the block was
474f22ef01cSRoman Divacky   // reachable, we have cloned it and the old block is now in the value map:
475f22ef01cSRoman Divacky   // insert it into the new function in the right order.  If not, ignore it.
476f22ef01cSRoman Divacky   //
477f22ef01cSRoman Divacky   // Defer PHI resolution until rest of function is resolved.
478f22ef01cSRoman Divacky   SmallVector<const PHINode*, 16> PHIToResolve;
4797d523365SDimitry Andric   for (const BasicBlock &BI : *OldFunc) {
4803ca95b02SDimitry Andric     Value *V = VMap.lookup(&BI);
4812754fe60SDimitry Andric     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
48291bc56edSDimitry Andric     if (!NewBB) continue;  // Dead block.
483f22ef01cSRoman Divacky 
484f22ef01cSRoman Divacky     // Add the new block to the new function.
485f22ef01cSRoman Divacky     NewFunc->getBasicBlockList().push_back(NewBB);
486f22ef01cSRoman Divacky 
487f22ef01cSRoman Divacky     // Handle PHI nodes specially, as we have to remove references to dead
488f22ef01cSRoman Divacky     // blocks.
48930785c0eSDimitry Andric     for (const PHINode &PN : BI.phis()) {
490ff0cc061SDimitry Andric       // PHI nodes may have been remapped to non-PHI nodes by the caller or
491ff0cc061SDimitry Andric       // during the cloning process.
49230785c0eSDimitry Andric       if (isa<PHINode>(VMap[&PN]))
49330785c0eSDimitry Andric         PHIToResolve.push_back(&PN);
494dff0c46cSDimitry Andric       else
495dff0c46cSDimitry Andric         break;
496ff0cc061SDimitry Andric     }
497f22ef01cSRoman Divacky 
498dff0c46cSDimitry Andric     // Finally, remap the terminator instructions, as those can't be remapped
499dff0c46cSDimitry Andric     // until all BBs are mapped.
500dff0c46cSDimitry Andric     RemapInstruction(NewBB->getTerminator(), VMap,
501ff0cc061SDimitry Andric                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
502ff0cc061SDimitry Andric                      TypeMapper, Materializer);
503f22ef01cSRoman Divacky   }
504f22ef01cSRoman Divacky 
505f22ef01cSRoman Divacky   // Defer PHI resolution until rest of function is resolved, PHI resolution
506f22ef01cSRoman Divacky   // requires the CFG to be up-to-date.
507f22ef01cSRoman Divacky   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
508f22ef01cSRoman Divacky     const PHINode *OPN = PHIToResolve[phino];
509f22ef01cSRoman Divacky     unsigned NumPreds = OPN->getNumIncomingValues();
510f22ef01cSRoman Divacky     const BasicBlock *OldBB = OPN->getParent();
511ffd1746dSEd Schouten     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
512f22ef01cSRoman Divacky 
513f22ef01cSRoman Divacky     // Map operands for blocks that are live and remove operands for blocks
514f22ef01cSRoman Divacky     // that are dead.
515f22ef01cSRoman Divacky     for (; phino != PHIToResolve.size() &&
516f22ef01cSRoman Divacky          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
517f22ef01cSRoman Divacky       OPN = PHIToResolve[phino];
518ffd1746dSEd Schouten       PHINode *PN = cast<PHINode>(VMap[OPN]);
519f22ef01cSRoman Divacky       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
5203ca95b02SDimitry Andric         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
5212754fe60SDimitry Andric         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
522f22ef01cSRoman Divacky           Value *InVal = MapValue(PN->getIncomingValue(pred),
5232754fe60SDimitry Andric                                   VMap,
5242754fe60SDimitry Andric                         ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
525f22ef01cSRoman Divacky           assert(InVal && "Unknown input value?");
526f22ef01cSRoman Divacky           PN->setIncomingValue(pred, InVal);
527f22ef01cSRoman Divacky           PN->setIncomingBlock(pred, MappedBlock);
528f22ef01cSRoman Divacky         } else {
529f22ef01cSRoman Divacky           PN->removeIncomingValue(pred, false);
5303ca95b02SDimitry Andric           --pred;  // Revisit the next entry.
5313ca95b02SDimitry Andric           --e;
532f22ef01cSRoman Divacky         }
533f22ef01cSRoman Divacky       }
534f22ef01cSRoman Divacky     }
535f22ef01cSRoman Divacky 
536f22ef01cSRoman Divacky     // The loop above has removed PHI entries for those blocks that are dead
537f22ef01cSRoman Divacky     // and has updated others.  However, if a block is live (i.e. copied over)
538f22ef01cSRoman Divacky     // but its terminator has been changed to not go to this block, then our
539f22ef01cSRoman Divacky     // phi nodes will have invalid entries.  Update the PHI nodes in this
540f22ef01cSRoman Divacky     // case.
541f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(NewBB->begin());
5424ba319b5SDimitry Andric     NumPreds = pred_size(NewBB);
543f22ef01cSRoman Divacky     if (NumPreds != PN->getNumIncomingValues()) {
544f22ef01cSRoman Divacky       assert(NumPreds < PN->getNumIncomingValues());
545f22ef01cSRoman Divacky       // Count how many times each predecessor comes to this block.
546f22ef01cSRoman Divacky       std::map<BasicBlock*, unsigned> PredCount;
547f22ef01cSRoman Divacky       for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
548f22ef01cSRoman Divacky            PI != E; ++PI)
549f22ef01cSRoman Divacky         --PredCount[*PI];
550f22ef01cSRoman Divacky 
551f22ef01cSRoman Divacky       // Figure out how many entries to remove from each PHI.
552f22ef01cSRoman Divacky       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
553f22ef01cSRoman Divacky         ++PredCount[PN->getIncomingBlock(i)];
554f22ef01cSRoman Divacky 
555f22ef01cSRoman Divacky       // At this point, the excess predecessor entries are positive in the
556f22ef01cSRoman Divacky       // map.  Loop over all of the PHIs and remove excess predecessor
557f22ef01cSRoman Divacky       // entries.
558f22ef01cSRoman Divacky       BasicBlock::iterator I = NewBB->begin();
559f22ef01cSRoman Divacky       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
5603ca95b02SDimitry Andric         for (const auto &PCI : PredCount) {
5613ca95b02SDimitry Andric           BasicBlock *Pred = PCI.first;
5623ca95b02SDimitry Andric           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
563f22ef01cSRoman Divacky             PN->removeIncomingValue(Pred, false);
564f22ef01cSRoman Divacky         }
565f22ef01cSRoman Divacky       }
566f22ef01cSRoman Divacky     }
567f22ef01cSRoman Divacky 
568f22ef01cSRoman Divacky     // If the loops above have made these phi nodes have 0 or 1 operand,
569f22ef01cSRoman Divacky     // replace them with undef or the input value.  We must do this for
570f22ef01cSRoman Divacky     // correctness, because 0-operand phis are not valid.
571f22ef01cSRoman Divacky     PN = cast<PHINode>(NewBB->begin());
572f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
573f22ef01cSRoman Divacky       BasicBlock::iterator I = NewBB->begin();
574f22ef01cSRoman Divacky       BasicBlock::const_iterator OldI = OldBB->begin();
575f22ef01cSRoman Divacky       while ((PN = dyn_cast<PHINode>(I++))) {
576f22ef01cSRoman Divacky         Value *NV = UndefValue::get(PN->getType());
577f22ef01cSRoman Divacky         PN->replaceAllUsesWith(NV);
5787d523365SDimitry Andric         assert(VMap[&*OldI] == PN && "VMap mismatch");
5797d523365SDimitry Andric         VMap[&*OldI] = NV;
580f22ef01cSRoman Divacky         PN->eraseFromParent();
581f22ef01cSRoman Divacky         ++OldI;
582f22ef01cSRoman Divacky       }
583f22ef01cSRoman Divacky     }
584f22ef01cSRoman Divacky   }
585f22ef01cSRoman Divacky 
586dff0c46cSDimitry Andric   // Make a second pass over the PHINodes now that all of them have been
587dff0c46cSDimitry Andric   // remapped into the new function, simplifying the PHINode and performing any
588dff0c46cSDimitry Andric   // recursive simplifications exposed. This will transparently update the
589f37b6182SDimitry Andric   // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce
590dff0c46cSDimitry Andric   // two PHINodes, the iteration over the old PHIs remains valid, and the
591dff0c46cSDimitry Andric   // mapping will just map us to the new node (which may not even be a PHI
592dff0c46cSDimitry Andric   // node).
5936c4bc1bdSDimitry Andric   const DataLayout &DL = NewFunc->getParent()->getDataLayout();
5946c4bc1bdSDimitry Andric   SmallSetVector<const Value *, 8> Worklist;
595dff0c46cSDimitry Andric   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
5966c4bc1bdSDimitry Andric     if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
5976c4bc1bdSDimitry Andric       Worklist.insert(PHIToResolve[Idx]);
5986c4bc1bdSDimitry Andric 
5996c4bc1bdSDimitry Andric   // Note that we must test the size on each iteration, the worklist can grow.
6006c4bc1bdSDimitry Andric   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6016c4bc1bdSDimitry Andric     const Value *OrigV = Worklist[Idx];
6026c4bc1bdSDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
6036c4bc1bdSDimitry Andric     if (!I)
6046c4bc1bdSDimitry Andric       continue;
6056c4bc1bdSDimitry Andric 
606fccc5558SDimitry Andric     // Skip over non-intrinsic callsites, we don't want to remove any nodes from
607fccc5558SDimitry Andric     // the CGSCC.
608fccc5558SDimitry Andric     CallSite CS = CallSite(I);
609fccc5558SDimitry Andric     if (CS && CS.getCalledFunction() && !CS.getCalledFunction()->isIntrinsic())
610fccc5558SDimitry Andric       continue;
611fccc5558SDimitry Andric 
6126c4bc1bdSDimitry Andric     // See if this instruction simplifies.
6136c4bc1bdSDimitry Andric     Value *SimpleV = SimplifyInstruction(I, DL);
6146c4bc1bdSDimitry Andric     if (!SimpleV)
6156c4bc1bdSDimitry Andric       continue;
6166c4bc1bdSDimitry Andric 
6176c4bc1bdSDimitry Andric     // Stash away all the uses of the old instruction so we can check them for
6186c4bc1bdSDimitry Andric     // recursive simplifications after a RAUW. This is cheaper than checking all
6196c4bc1bdSDimitry Andric     // uses of To on the recursive step in most cases.
6206c4bc1bdSDimitry Andric     for (const User *U : OrigV->users())
6216c4bc1bdSDimitry Andric       Worklist.insert(cast<Instruction>(U));
6226c4bc1bdSDimitry Andric 
6236c4bc1bdSDimitry Andric     // Replace the instruction with its simplified value.
6246c4bc1bdSDimitry Andric     I->replaceAllUsesWith(SimpleV);
6256c4bc1bdSDimitry Andric 
6266c4bc1bdSDimitry Andric     // If the original instruction had no side effects, remove it.
6276c4bc1bdSDimitry Andric     if (isInstructionTriviallyDead(I))
6286c4bc1bdSDimitry Andric       I->eraseFromParent();
6296c4bc1bdSDimitry Andric     else
6306c4bc1bdSDimitry Andric       VMap[OrigV] = I;
6316c4bc1bdSDimitry Andric   }
632dff0c46cSDimitry Andric 
633f22ef01cSRoman Divacky   // Now that the inlined function body has been fully constructed, go through
634ff0cc061SDimitry Andric   // and zap unconditional fall-through branches. This happens all the time when
635f22ef01cSRoman Divacky   // specializing code: code specialization turns conditional branches into
636f22ef01cSRoman Divacky   // uncond branches, and this code folds them.
6377d523365SDimitry Andric   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
638dff0c46cSDimitry Andric   Function::iterator I = Begin;
639f22ef01cSRoman Divacky   while (I != NewFunc->end()) {
6404ba319b5SDimitry Andric     // We need to simplify conditional branches and switches with a constant
6414ba319b5SDimitry Andric     // operand. We try to prune these out when cloning, but if the
6424ba319b5SDimitry Andric     // simplification required looking through PHI nodes, those are only
6434ba319b5SDimitry Andric     // available after forming the full basic block. That may leave some here,
6444ba319b5SDimitry Andric     // and we still want to prune the dead code as early as possible.
6454ba319b5SDimitry Andric     //
6464ba319b5SDimitry Andric     // Do the folding before we check if the block is dead since we want code
6474ba319b5SDimitry Andric     // like
6484ba319b5SDimitry Andric     //  bb:
6494ba319b5SDimitry Andric     //    br i1 undef, label %bb, label %bb
6504ba319b5SDimitry Andric     // to be simplified to
6514ba319b5SDimitry Andric     //  bb:
6524ba319b5SDimitry Andric     //    br label %bb
6534ba319b5SDimitry Andric     // before we call I->getSinglePredecessor().
6544ba319b5SDimitry Andric     ConstantFoldTerminator(&*I);
6554ba319b5SDimitry Andric 
656dff0c46cSDimitry Andric     // Check if this block has become dead during inlining or other
657dff0c46cSDimitry Andric     // simplifications. Note that the first block will appear dead, as it has
658dff0c46cSDimitry Andric     // not yet been wired up properly.
6597d523365SDimitry Andric     if (I != Begin && (pred_begin(&*I) == pred_end(&*I) ||
6607d523365SDimitry Andric                        I->getSinglePredecessor() == &*I)) {
6617d523365SDimitry Andric       BasicBlock *DeadBB = &*I++;
662dff0c46cSDimitry Andric       DeleteDeadBlock(DeadBB);
663dff0c46cSDimitry Andric       continue;
664dff0c46cSDimitry Andric     }
665dff0c46cSDimitry Andric 
666f22ef01cSRoman Divacky     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
667f22ef01cSRoman Divacky     if (!BI || BI->isConditional()) { ++I; continue; }
668f22ef01cSRoman Divacky 
669f22ef01cSRoman Divacky     BasicBlock *Dest = BI->getSuccessor(0);
670dff0c46cSDimitry Andric     if (!Dest->getSinglePredecessor()) {
671f22ef01cSRoman Divacky       ++I; continue;
672f22ef01cSRoman Divacky     }
673f22ef01cSRoman Divacky 
674dff0c46cSDimitry Andric     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
675dff0c46cSDimitry Andric     // above should have zapped all of them..
676dff0c46cSDimitry Andric     assert(!isa<PHINode>(Dest->begin()));
677dff0c46cSDimitry Andric 
678f22ef01cSRoman Divacky     // We know all single-entry PHI nodes in the inlined function have been
679f22ef01cSRoman Divacky     // removed, so we just need to splice the blocks.
680f22ef01cSRoman Divacky     BI->eraseFromParent();
681f22ef01cSRoman Divacky 
682f22ef01cSRoman Divacky     // Make all PHI nodes that referred to Dest now refer to I as their source.
6837d523365SDimitry Andric     Dest->replaceAllUsesWith(&*I);
684f22ef01cSRoman Divacky 
68517a519f9SDimitry Andric     // Move all the instructions in the succ to the pred.
68617a519f9SDimitry Andric     I->getInstList().splice(I->end(), Dest->getInstList());
68717a519f9SDimitry Andric 
688f22ef01cSRoman Divacky     // Remove the dest block.
689f22ef01cSRoman Divacky     Dest->eraseFromParent();
690f22ef01cSRoman Divacky 
691f22ef01cSRoman Divacky     // Do not increment I, iteratively merge all things this block branches to.
692f22ef01cSRoman Divacky   }
693dff0c46cSDimitry Andric 
694ff0cc061SDimitry Andric   // Make a final pass over the basic blocks from the old function to gather
695dff0c46cSDimitry Andric   // any return instructions which survived folding. We have to do this here
696dff0c46cSDimitry Andric   // because we can iteratively remove and merge returns above.
6977d523365SDimitry Andric   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
698dff0c46cSDimitry Andric                           E = NewFunc->end();
699dff0c46cSDimitry Andric        I != E; ++I)
700dff0c46cSDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
701dff0c46cSDimitry Andric       Returns.push_back(RI);
702f22ef01cSRoman Divacky }
703ff0cc061SDimitry Andric 
704ff0cc061SDimitry Andric 
705ff0cc061SDimitry Andric /// This works exactly like CloneFunctionInto,
706ff0cc061SDimitry Andric /// except that it does some simple constant prop and DCE on the fly.  The
707ff0cc061SDimitry Andric /// effect of this is to copy significantly less code in cases where (for
708ff0cc061SDimitry Andric /// example) a function call with constant arguments is inlined, and those
709ff0cc061SDimitry Andric /// constant arguments cause a significant amount of code in the callee to be
710ff0cc061SDimitry Andric /// dead.  Since this doesn't produce an exact copy of the input, it can't be
711ff0cc061SDimitry Andric /// used for things like CloneFunction or CloneModule.
CloneAndPruneFunctionInto(Function * NewFunc,const Function * OldFunc,ValueToValueMapTy & VMap,bool ModuleLevelChanges,SmallVectorImpl<ReturnInst * > & Returns,const char * NameSuffix,ClonedCodeInfo * CodeInfo,Instruction * TheCall)712ff0cc061SDimitry Andric void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
713ff0cc061SDimitry Andric                                      ValueToValueMapTy &VMap,
714ff0cc061SDimitry Andric                                      bool ModuleLevelChanges,
715ff0cc061SDimitry Andric                                      SmallVectorImpl<ReturnInst*> &Returns,
716ff0cc061SDimitry Andric                                      const char *NameSuffix,
717ff0cc061SDimitry Andric                                      ClonedCodeInfo *CodeInfo,
718ff0cc061SDimitry Andric                                      Instruction *TheCall) {
7197d523365SDimitry Andric   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
720444ed5c5SDimitry Andric                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
721ff0cc061SDimitry Andric }
722875ed548SDimitry Andric 
7234ba319b5SDimitry Andric /// Remaps instructions in \p Blocks using the mapping in \p VMap.
remapInstructionsInBlocks(const SmallVectorImpl<BasicBlock * > & Blocks,ValueToValueMapTy & VMap)724875ed548SDimitry Andric void llvm::remapInstructionsInBlocks(
725875ed548SDimitry Andric     const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
726875ed548SDimitry Andric   // Rewrite the code to refer to itself.
727875ed548SDimitry Andric   for (auto *BB : Blocks)
728875ed548SDimitry Andric     for (auto &Inst : *BB)
729875ed548SDimitry Andric       RemapInstruction(&Inst, VMap,
7303ca95b02SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
731875ed548SDimitry Andric }
732875ed548SDimitry Andric 
7334ba319b5SDimitry Andric /// Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
734875ed548SDimitry Andric /// Blocks.
735875ed548SDimitry Andric ///
736875ed548SDimitry Andric /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
737875ed548SDimitry Andric /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
cloneLoopWithPreheader(BasicBlock * Before,BasicBlock * LoopDomBB,Loop * OrigLoop,ValueToValueMapTy & VMap,const Twine & NameSuffix,LoopInfo * LI,DominatorTree * DT,SmallVectorImpl<BasicBlock * > & Blocks)738875ed548SDimitry Andric Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
739875ed548SDimitry Andric                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
740875ed548SDimitry Andric                                    const Twine &NameSuffix, LoopInfo *LI,
741875ed548SDimitry Andric                                    DominatorTree *DT,
742875ed548SDimitry Andric                                    SmallVectorImpl<BasicBlock *> &Blocks) {
7433ca95b02SDimitry Andric   assert(OrigLoop->getSubLoops().empty() &&
7443ca95b02SDimitry Andric          "Loop to be cloned cannot have inner loop");
745875ed548SDimitry Andric   Function *F = OrigLoop->getHeader()->getParent();
746875ed548SDimitry Andric   Loop *ParentLoop = OrigLoop->getParentLoop();
747875ed548SDimitry Andric 
7482cab237bSDimitry Andric   Loop *NewLoop = LI->AllocateLoop();
749875ed548SDimitry Andric   if (ParentLoop)
750875ed548SDimitry Andric     ParentLoop->addChildLoop(NewLoop);
751875ed548SDimitry Andric   else
752875ed548SDimitry Andric     LI->addTopLevelLoop(NewLoop);
753875ed548SDimitry Andric 
754875ed548SDimitry Andric   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
755875ed548SDimitry Andric   assert(OrigPH && "No preheader");
756875ed548SDimitry Andric   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
757875ed548SDimitry Andric   // To rename the loop PHIs.
758875ed548SDimitry Andric   VMap[OrigPH] = NewPH;
759875ed548SDimitry Andric   Blocks.push_back(NewPH);
760875ed548SDimitry Andric 
761875ed548SDimitry Andric   // Update LoopInfo.
762875ed548SDimitry Andric   if (ParentLoop)
763875ed548SDimitry Andric     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
764875ed548SDimitry Andric 
765875ed548SDimitry Andric   // Update DominatorTree.
766875ed548SDimitry Andric   DT->addNewBlock(NewPH, LoopDomBB);
767875ed548SDimitry Andric 
768875ed548SDimitry Andric   for (BasicBlock *BB : OrigLoop->getBlocks()) {
769875ed548SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
770875ed548SDimitry Andric     VMap[BB] = NewBB;
771875ed548SDimitry Andric 
772875ed548SDimitry Andric     // Update LoopInfo.
773875ed548SDimitry Andric     NewLoop->addBasicBlockToLoop(NewBB, *LI);
774875ed548SDimitry Andric 
7753ca95b02SDimitry Andric     // Add DominatorTree node. After seeing all blocks, update to correct IDom.
7763ca95b02SDimitry Andric     DT->addNewBlock(NewBB, NewPH);
777875ed548SDimitry Andric 
778875ed548SDimitry Andric     Blocks.push_back(NewBB);
779875ed548SDimitry Andric   }
780875ed548SDimitry Andric 
7813ca95b02SDimitry Andric   for (BasicBlock *BB : OrigLoop->getBlocks()) {
7823ca95b02SDimitry Andric     // Update DominatorTree.
7833ca95b02SDimitry Andric     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
7843ca95b02SDimitry Andric     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
7853ca95b02SDimitry Andric                                  cast<BasicBlock>(VMap[IDomBB]));
7863ca95b02SDimitry Andric   }
7873ca95b02SDimitry Andric 
788875ed548SDimitry Andric   // Move them physically from the end of the block list.
7897d523365SDimitry Andric   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
7907d523365SDimitry Andric                                 NewPH);
7917d523365SDimitry Andric   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
7927d523365SDimitry Andric                                 NewLoop->getHeader()->getIterator(), F->end());
793875ed548SDimitry Andric 
794875ed548SDimitry Andric   return NewLoop;
795875ed548SDimitry Andric }
7967a7e6055SDimitry Andric 
7974ba319b5SDimitry Andric /// Duplicate non-Phi instructions from the beginning of block up to
7987a7e6055SDimitry Andric /// StopAt instruction into a split block between BB and its predecessor.
DuplicateInstructionsInSplitBetween(BasicBlock * BB,BasicBlock * PredBB,Instruction * StopAt,ValueToValueMapTy & ValueMapping,DomTreeUpdater & DTU)799*b5893f02SDimitry Andric BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
800*b5893f02SDimitry Andric     BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
801*b5893f02SDimitry Andric     ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
802*b5893f02SDimitry Andric 
803*b5893f02SDimitry Andric   assert(count(successors(PredBB), BB) == 1 &&
804*b5893f02SDimitry Andric          "There must be a single edge between PredBB and BB!");
8057a7e6055SDimitry Andric   // We are going to have to map operands from the original BB block to the new
8067a7e6055SDimitry Andric   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
8077a7e6055SDimitry Andric   // account for entry from PredBB.
8087a7e6055SDimitry Andric   BasicBlock::iterator BI = BB->begin();
8097a7e6055SDimitry Andric   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
8107a7e6055SDimitry Andric     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
8117a7e6055SDimitry Andric 
812*b5893f02SDimitry Andric   BasicBlock *NewBB = SplitEdge(PredBB, BB);
8137a7e6055SDimitry Andric   NewBB->setName(PredBB->getName() + ".split");
8147a7e6055SDimitry Andric   Instruction *NewTerm = NewBB->getTerminator();
8157a7e6055SDimitry Andric 
816*b5893f02SDimitry Andric   // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
817*b5893f02SDimitry Andric   //        in the update set here.
818*b5893f02SDimitry Andric   DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
819*b5893f02SDimitry Andric                     {DominatorTree::Insert, PredBB, NewBB},
820*b5893f02SDimitry Andric                     {DominatorTree::Insert, NewBB, BB}});
821*b5893f02SDimitry Andric 
8227a7e6055SDimitry Andric   // Clone the non-phi instructions of BB into NewBB, keeping track of the
8237a7e6055SDimitry Andric   // mapping and using it to remap operands in the cloned instructions.
8244ba319b5SDimitry Andric   // Stop once we see the terminator too. This covers the case where BB's
8254ba319b5SDimitry Andric   // terminator gets replaced and StopAt == BB's terminator.
8264ba319b5SDimitry Andric   for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
8277a7e6055SDimitry Andric     Instruction *New = BI->clone();
8287a7e6055SDimitry Andric     New->setName(BI->getName());
8297a7e6055SDimitry Andric     New->insertBefore(NewTerm);
8307a7e6055SDimitry Andric     ValueMapping[&*BI] = New;
8317a7e6055SDimitry Andric 
8327a7e6055SDimitry Andric     // Remap operands to patch up intra-block references.
8337a7e6055SDimitry Andric     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
8347a7e6055SDimitry Andric       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
8357a7e6055SDimitry Andric         auto I = ValueMapping.find(Inst);
8367a7e6055SDimitry Andric         if (I != ValueMapping.end())
8377a7e6055SDimitry Andric           New->setOperand(i, I->second);
8387a7e6055SDimitry Andric       }
8397a7e6055SDimitry Andric   }
8407a7e6055SDimitry Andric 
8417a7e6055SDimitry Andric   return NewBB;
8427a7e6055SDimitry Andric }
843