1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CloneFunctionInto interface, which is used as the
10 // low-level function cloner.  This is used by the CloneFunction and function
11 // inliner to do the dirty work of copying the body of a function around.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/ConstantFolding.h"
18 #include "llvm/Analysis/DomTreeUpdater.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DebugInfo.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/ValueMapper.h"
37 #include <map>
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "clone-function"
41 
42 /// See comments in Cloning.h.
43 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
44                                   const Twine &NameSuffix, Function *F,
45                                   ClonedCodeInfo *CodeInfo,
46                                   DebugInfoFinder *DIFinder) {
47   DenseMap<const MDNode *, MDNode *> Cache;
48   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
49   if (BB->hasName())
50     NewBB->setName(BB->getName() + NameSuffix);
51 
52   bool hasCalls = false, hasDynamicAllocas = false;
53   Module *TheModule = F ? F->getParent() : nullptr;
54 
55   // Loop over all instructions, and copy them over.
56   for (const Instruction &I : *BB) {
57     if (DIFinder && TheModule)
58       DIFinder->processInstruction(*TheModule, I);
59 
60     Instruction *NewInst = I.clone();
61     if (I.hasName())
62       NewInst->setName(I.getName() + NameSuffix);
63     NewBB->getInstList().push_back(NewInst);
64     VMap[&I] = NewInst; // Add instruction map to value.
65 
66     hasCalls |= (isa<CallInst>(I) && !isa<DbgInfoIntrinsic>(I));
67     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
68       if (!AI->isStaticAlloca()) {
69         hasDynamicAllocas = true;
70       }
71     }
72   }
73 
74   if (CodeInfo) {
75     CodeInfo->ContainsCalls          |= hasCalls;
76     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
77   }
78   return NewBB;
79 }
80 
81 // Clone OldFunc into NewFunc, transforming the old arguments into references to
82 // VMap values.
83 //
84 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
85                              ValueToValueMapTy &VMap,
86                              bool ModuleLevelChanges,
87                              SmallVectorImpl<ReturnInst*> &Returns,
88                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
89                              ValueMapTypeRemapper *TypeMapper,
90                              ValueMaterializer *Materializer) {
91   assert(NameSuffix && "NameSuffix cannot be null!");
92 
93 #ifndef NDEBUG
94   for (const Argument &I : OldFunc->args())
95     assert(VMap.count(&I) && "No mapping from source argument specified!");
96 #endif
97 
98   // Copy all attributes other than those stored in the AttributeList.  We need
99   // to remap the parameter indices of the AttributeList.
100   AttributeList NewAttrs = NewFunc->getAttributes();
101   NewFunc->copyAttributesFrom(OldFunc);
102   NewFunc->setAttributes(NewAttrs);
103 
104   // Fix up the personality function that got copied over.
105   if (OldFunc->hasPersonalityFn())
106     NewFunc->setPersonalityFn(
107         MapValue(OldFunc->getPersonalityFn(), VMap,
108                  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
109                  TypeMapper, Materializer));
110 
111   SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
112   AttributeList OldAttrs = OldFunc->getAttributes();
113 
114   // Clone any argument attributes that are present in the VMap.
115   for (const Argument &OldArg : OldFunc->args()) {
116     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
117       NewArgAttrs[NewArg->getArgNo()] =
118           OldAttrs.getParamAttributes(OldArg.getArgNo());
119     }
120   }
121 
122   NewFunc->setAttributes(
123       AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttributes(),
124                          OldAttrs.getRetAttributes(), NewArgAttrs));
125 
126   bool MustCloneSP =
127       OldFunc->getParent() && OldFunc->getParent() == NewFunc->getParent();
128   DISubprogram *SP = OldFunc->getSubprogram();
129   if (SP) {
130     assert(!MustCloneSP || ModuleLevelChanges);
131     // Add mappings for some DebugInfo nodes that we don't want duplicated
132     // even if they're distinct.
133     auto &MD = VMap.MD();
134     MD[SP->getUnit()].reset(SP->getUnit());
135     MD[SP->getType()].reset(SP->getType());
136     MD[SP->getFile()].reset(SP->getFile());
137     // If we're not cloning into the same module, no need to clone the
138     // subprogram
139     if (!MustCloneSP)
140       MD[SP].reset(SP);
141   }
142 
143   // Everything else beyond this point deals with function instructions,
144   // so if we are dealing with a function declaration, we're done.
145   if (OldFunc->isDeclaration())
146     return;
147 
148   // When we remap instructions, we want to avoid duplicating inlined
149   // DISubprograms, so record all subprograms we find as we duplicate
150   // instructions and then freeze them in the MD map.
151   // We also record information about dbg.value and dbg.declare to avoid
152   // duplicating the types.
153   DebugInfoFinder DIFinder;
154 
155   // Loop over all of the basic blocks in the function, cloning them as
156   // appropriate.  Note that we save BE this way in order to handle cloning of
157   // recursive functions into themselves.
158   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
159        BI != BE; ++BI) {
160     const BasicBlock &BB = *BI;
161 
162     // Create a new basic block and copy instructions into it!
163     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
164                                       ModuleLevelChanges ? &DIFinder : nullptr);
165 
166     // Add basic block mapping.
167     VMap[&BB] = CBB;
168 
169     // It is only legal to clone a function if a block address within that
170     // function is never referenced outside of the function.  Given that, we
171     // want to map block addresses from the old function to block addresses in
172     // the clone. (This is different from the generic ValueMapper
173     // implementation, which generates an invalid blockaddress when
174     // cloning a function.)
175     if (BB.hasAddressTaken()) {
176       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
177                                               const_cast<BasicBlock*>(&BB));
178       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
179     }
180 
181     // Note return instructions for the caller.
182     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
183       Returns.push_back(RI);
184   }
185 
186   for (DISubprogram *ISP : DIFinder.subprograms())
187     if (ISP != SP)
188       VMap.MD()[ISP].reset(ISP);
189 
190   for (DICompileUnit *CU : DIFinder.compile_units())
191     VMap.MD()[CU].reset(CU);
192 
193   for (DIType *Type : DIFinder.types())
194     VMap.MD()[Type].reset(Type);
195 
196   // Duplicate the metadata that is attached to the cloned function.
197   // Subprograms/CUs/types that were already mapped to themselves won't be
198   // duplicated.
199   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
200   OldFunc->getAllMetadata(MDs);
201   for (auto MD : MDs) {
202     NewFunc->addMetadata(
203         MD.first,
204         *MapMetadata(MD.second, VMap,
205                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
206                      TypeMapper, Materializer));
207   }
208 
209   // Loop over all of the instructions in the function, fixing up operand
210   // references as we go.  This uses VMap to do all the hard work.
211   for (Function::iterator BB =
212            cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
213                           BE = NewFunc->end();
214        BB != BE; ++BB)
215     // Loop over all instructions, fixing each one as we find it...
216     for (Instruction &II : *BB)
217       RemapInstruction(&II, VMap,
218                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
219                        TypeMapper, Materializer);
220 
221   // Register all DICompileUnits of the old parent module in the new parent module
222   auto* OldModule = OldFunc->getParent();
223   auto* NewModule = NewFunc->getParent();
224   if (OldModule && NewModule && OldModule != NewModule && DIFinder.compile_unit_count()) {
225     auto* NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
226     // Avoid multiple insertions of the same DICompileUnit to NMD.
227     SmallPtrSet<const void*, 8> Visited;
228     for (auto* Operand : NMD->operands())
229       Visited.insert(Operand);
230     for (auto* Unit : DIFinder.compile_units())
231       // VMap.MD()[Unit] == Unit
232       if (Visited.insert(Unit).second)
233         NMD->addOperand(Unit);
234   }
235 }
236 
237 /// Return a copy of the specified function and add it to that function's
238 /// module.  Also, any references specified in the VMap are changed to refer to
239 /// their mapped value instead of the original one.  If any of the arguments to
240 /// the function are in the VMap, the arguments are deleted from the resultant
241 /// function.  The VMap is updated to include mappings from all of the
242 /// instructions and basicblocks in the function from their old to new values.
243 ///
244 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
245                               ClonedCodeInfo *CodeInfo) {
246   std::vector<Type*> ArgTypes;
247 
248   // The user might be deleting arguments to the function by specifying them in
249   // the VMap.  If so, we need to not add the arguments to the arg ty vector
250   //
251   for (const Argument &I : F->args())
252     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
253       ArgTypes.push_back(I.getType());
254 
255   // Create a new function type...
256   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
257                                     ArgTypes, F->getFunctionType()->isVarArg());
258 
259   // Create the new function...
260   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
261                                     F->getName(), F->getParent());
262 
263   // Loop over the arguments, copying the names of the mapped arguments over...
264   Function::arg_iterator DestI = NewF->arg_begin();
265   for (const Argument & I : F->args())
266     if (VMap.count(&I) == 0) {     // Is this argument preserved?
267       DestI->setName(I.getName()); // Copy the name over...
268       VMap[&I] = &*DestI++;        // Add mapping to VMap
269     }
270 
271   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
272   CloneFunctionInto(NewF, F, VMap, F->getSubprogram() != nullptr, Returns, "",
273                     CodeInfo);
274 
275   return NewF;
276 }
277 
278 
279 
280 namespace {
281   /// This is a private class used to implement CloneAndPruneFunctionInto.
282   struct PruningFunctionCloner {
283     Function *NewFunc;
284     const Function *OldFunc;
285     ValueToValueMapTy &VMap;
286     bool ModuleLevelChanges;
287     const char *NameSuffix;
288     ClonedCodeInfo *CodeInfo;
289 
290   public:
291     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
292                           ValueToValueMapTy &valueMap, bool moduleLevelChanges,
293                           const char *nameSuffix, ClonedCodeInfo *codeInfo)
294         : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
295           ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
296           CodeInfo(codeInfo) {}
297 
298     /// The specified block is found to be reachable, clone it and
299     /// anything that it can reach.
300     void CloneBlock(const BasicBlock *BB,
301                     BasicBlock::const_iterator StartingInst,
302                     std::vector<const BasicBlock*> &ToClone);
303   };
304 }
305 
306 /// The specified block is found to be reachable, clone it and
307 /// anything that it can reach.
308 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
309                                        BasicBlock::const_iterator StartingInst,
310                                        std::vector<const BasicBlock*> &ToClone){
311   WeakTrackingVH &BBEntry = VMap[BB];
312 
313   // Have we already cloned this block?
314   if (BBEntry) return;
315 
316   // Nope, clone it now.
317   BasicBlock *NewBB;
318   BBEntry = NewBB = BasicBlock::Create(BB->getContext());
319   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
320 
321   // It is only legal to clone a function if a block address within that
322   // function is never referenced outside of the function.  Given that, we
323   // want to map block addresses from the old function to block addresses in
324   // the clone. (This is different from the generic ValueMapper
325   // implementation, which generates an invalid blockaddress when
326   // cloning a function.)
327   //
328   // Note that we don't need to fix the mapping for unreachable blocks;
329   // the default mapping there is safe.
330   if (BB->hasAddressTaken()) {
331     Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
332                                             const_cast<BasicBlock*>(BB));
333     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
334   }
335 
336   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
337 
338   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
339   // loop doesn't include the terminator.
340   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
341        II != IE; ++II) {
342 
343     Instruction *NewInst = II->clone();
344 
345     // Eagerly remap operands to the newly cloned instruction, except for PHI
346     // nodes for which we defer processing until we update the CFG.
347     if (!isa<PHINode>(NewInst)) {
348       RemapInstruction(NewInst, VMap,
349                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
350 
351       // If we can simplify this instruction to some other value, simply add
352       // a mapping to that value rather than inserting a new instruction into
353       // the basic block.
354       if (Value *V =
355               SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
356         // On the off-chance that this simplifies to an instruction in the old
357         // function, map it back into the new function.
358         if (NewFunc != OldFunc)
359           if (Value *MappedV = VMap.lookup(V))
360             V = MappedV;
361 
362         if (!NewInst->mayHaveSideEffects()) {
363           VMap[&*II] = V;
364           NewInst->deleteValue();
365           continue;
366         }
367       }
368     }
369 
370     if (II->hasName())
371       NewInst->setName(II->getName()+NameSuffix);
372     VMap[&*II] = NewInst; // Add instruction map to value.
373     NewBB->getInstList().push_back(NewInst);
374     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
375 
376     if (CodeInfo)
377       if (auto *CB = dyn_cast<CallBase>(&*II))
378         if (CB->hasOperandBundles())
379           CodeInfo->OperandBundleCallSites.push_back(NewInst);
380 
381     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
382       if (isa<ConstantInt>(AI->getArraySize()))
383         hasStaticAllocas = true;
384       else
385         hasDynamicAllocas = true;
386     }
387   }
388 
389   // Finally, clone over the terminator.
390   const Instruction *OldTI = BB->getTerminator();
391   bool TerminatorDone = false;
392   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
393     if (BI->isConditional()) {
394       // If the condition was a known constant in the callee...
395       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
396       // Or is a known constant in the caller...
397       if (!Cond) {
398         Value *V = VMap.lookup(BI->getCondition());
399         Cond = dyn_cast_or_null<ConstantInt>(V);
400       }
401 
402       // Constant fold to uncond branch!
403       if (Cond) {
404         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
405         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
406         ToClone.push_back(Dest);
407         TerminatorDone = true;
408       }
409     }
410   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
411     // If switching on a value known constant in the caller.
412     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
413     if (!Cond) { // Or known constant after constant prop in the callee...
414       Value *V = VMap.lookup(SI->getCondition());
415       Cond = dyn_cast_or_null<ConstantInt>(V);
416     }
417     if (Cond) {     // Constant fold to uncond branch!
418       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
419       BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
420       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
421       ToClone.push_back(Dest);
422       TerminatorDone = true;
423     }
424   }
425 
426   if (!TerminatorDone) {
427     Instruction *NewInst = OldTI->clone();
428     if (OldTI->hasName())
429       NewInst->setName(OldTI->getName()+NameSuffix);
430     NewBB->getInstList().push_back(NewInst);
431     VMap[OldTI] = NewInst;             // Add instruction map to value.
432 
433     if (CodeInfo)
434       if (auto *CB = dyn_cast<CallBase>(OldTI))
435         if (CB->hasOperandBundles())
436           CodeInfo->OperandBundleCallSites.push_back(NewInst);
437 
438     // Recursively clone any reachable successor blocks.
439     append_range(ToClone, successors(BB->getTerminator()));
440   }
441 
442   if (CodeInfo) {
443     CodeInfo->ContainsCalls          |= hasCalls;
444     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
445     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
446       BB != &BB->getParent()->front();
447   }
448 }
449 
450 /// This works like CloneAndPruneFunctionInto, except that it does not clone the
451 /// entire function. Instead it starts at an instruction provided by the caller
452 /// and copies (and prunes) only the code reachable from that instruction.
453 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
454                                      const Instruction *StartingInst,
455                                      ValueToValueMapTy &VMap,
456                                      bool ModuleLevelChanges,
457                                      SmallVectorImpl<ReturnInst *> &Returns,
458                                      const char *NameSuffix,
459                                      ClonedCodeInfo *CodeInfo) {
460   assert(NameSuffix && "NameSuffix cannot be null!");
461 
462   ValueMapTypeRemapper *TypeMapper = nullptr;
463   ValueMaterializer *Materializer = nullptr;
464 
465 #ifndef NDEBUG
466   // If the cloning starts at the beginning of the function, verify that
467   // the function arguments are mapped.
468   if (!StartingInst)
469     for (const Argument &II : OldFunc->args())
470       assert(VMap.count(&II) && "No mapping from source argument specified!");
471 #endif
472 
473   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
474                             NameSuffix, CodeInfo);
475   const BasicBlock *StartingBB;
476   if (StartingInst)
477     StartingBB = StartingInst->getParent();
478   else {
479     StartingBB = &OldFunc->getEntryBlock();
480     StartingInst = &StartingBB->front();
481   }
482 
483   // Clone the entry block, and anything recursively reachable from it.
484   std::vector<const BasicBlock*> CloneWorklist;
485   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
486   while (!CloneWorklist.empty()) {
487     const BasicBlock *BB = CloneWorklist.back();
488     CloneWorklist.pop_back();
489     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
490   }
491 
492   // Loop over all of the basic blocks in the old function.  If the block was
493   // reachable, we have cloned it and the old block is now in the value map:
494   // insert it into the new function in the right order.  If not, ignore it.
495   //
496   // Defer PHI resolution until rest of function is resolved.
497   SmallVector<const PHINode*, 16> PHIToResolve;
498   for (const BasicBlock &BI : *OldFunc) {
499     Value *V = VMap.lookup(&BI);
500     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
501     if (!NewBB) continue;  // Dead block.
502 
503     // Add the new block to the new function.
504     NewFunc->getBasicBlockList().push_back(NewBB);
505 
506     // Handle PHI nodes specially, as we have to remove references to dead
507     // blocks.
508     for (const PHINode &PN : BI.phis()) {
509       // PHI nodes may have been remapped to non-PHI nodes by the caller or
510       // during the cloning process.
511       if (isa<PHINode>(VMap[&PN]))
512         PHIToResolve.push_back(&PN);
513       else
514         break;
515     }
516 
517     // Finally, remap the terminator instructions, as those can't be remapped
518     // until all BBs are mapped.
519     RemapInstruction(NewBB->getTerminator(), VMap,
520                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
521                      TypeMapper, Materializer);
522   }
523 
524   // Defer PHI resolution until rest of function is resolved, PHI resolution
525   // requires the CFG to be up-to-date.
526   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
527     const PHINode *OPN = PHIToResolve[phino];
528     unsigned NumPreds = OPN->getNumIncomingValues();
529     const BasicBlock *OldBB = OPN->getParent();
530     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
531 
532     // Map operands for blocks that are live and remove operands for blocks
533     // that are dead.
534     for (; phino != PHIToResolve.size() &&
535          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
536       OPN = PHIToResolve[phino];
537       PHINode *PN = cast<PHINode>(VMap[OPN]);
538       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
539         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
540         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
541           Value *InVal = MapValue(PN->getIncomingValue(pred),
542                                   VMap,
543                         ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
544           assert(InVal && "Unknown input value?");
545           PN->setIncomingValue(pred, InVal);
546           PN->setIncomingBlock(pred, MappedBlock);
547         } else {
548           PN->removeIncomingValue(pred, false);
549           --pred;  // Revisit the next entry.
550           --e;
551         }
552       }
553     }
554 
555     // The loop above has removed PHI entries for those blocks that are dead
556     // and has updated others.  However, if a block is live (i.e. copied over)
557     // but its terminator has been changed to not go to this block, then our
558     // phi nodes will have invalid entries.  Update the PHI nodes in this
559     // case.
560     PHINode *PN = cast<PHINode>(NewBB->begin());
561     NumPreds = pred_size(NewBB);
562     if (NumPreds != PN->getNumIncomingValues()) {
563       assert(NumPreds < PN->getNumIncomingValues());
564       // Count how many times each predecessor comes to this block.
565       std::map<BasicBlock*, unsigned> PredCount;
566       for (BasicBlock *Pred : predecessors(NewBB))
567         --PredCount[Pred];
568 
569       // Figure out how many entries to remove from each PHI.
570       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
571         ++PredCount[PN->getIncomingBlock(i)];
572 
573       // At this point, the excess predecessor entries are positive in the
574       // map.  Loop over all of the PHIs and remove excess predecessor
575       // entries.
576       BasicBlock::iterator I = NewBB->begin();
577       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
578         for (const auto &PCI : PredCount) {
579           BasicBlock *Pred = PCI.first;
580           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
581             PN->removeIncomingValue(Pred, false);
582         }
583       }
584     }
585 
586     // If the loops above have made these phi nodes have 0 or 1 operand,
587     // replace them with undef or the input value.  We must do this for
588     // correctness, because 0-operand phis are not valid.
589     PN = cast<PHINode>(NewBB->begin());
590     if (PN->getNumIncomingValues() == 0) {
591       BasicBlock::iterator I = NewBB->begin();
592       BasicBlock::const_iterator OldI = OldBB->begin();
593       while ((PN = dyn_cast<PHINode>(I++))) {
594         Value *NV = UndefValue::get(PN->getType());
595         PN->replaceAllUsesWith(NV);
596         assert(VMap[&*OldI] == PN && "VMap mismatch");
597         VMap[&*OldI] = NV;
598         PN->eraseFromParent();
599         ++OldI;
600       }
601     }
602   }
603 
604   // Make a second pass over the PHINodes now that all of them have been
605   // remapped into the new function, simplifying the PHINode and performing any
606   // recursive simplifications exposed. This will transparently update the
607   // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce
608   // two PHINodes, the iteration over the old PHIs remains valid, and the
609   // mapping will just map us to the new node (which may not even be a PHI
610   // node).
611   const DataLayout &DL = NewFunc->getParent()->getDataLayout();
612   SmallSetVector<const Value *, 8> Worklist;
613   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
614     if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
615       Worklist.insert(PHIToResolve[Idx]);
616 
617   // Note that we must test the size on each iteration, the worklist can grow.
618   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
619     const Value *OrigV = Worklist[Idx];
620     auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
621     if (!I)
622       continue;
623 
624     // Skip over non-intrinsic callsites, we don't want to remove any nodes from
625     // the CGSCC.
626     CallBase *CB = dyn_cast<CallBase>(I);
627     if (CB && CB->getCalledFunction() &&
628         !CB->getCalledFunction()->isIntrinsic())
629       continue;
630 
631     // See if this instruction simplifies.
632     Value *SimpleV = SimplifyInstruction(I, DL);
633     if (!SimpleV)
634       continue;
635 
636     // Stash away all the uses of the old instruction so we can check them for
637     // recursive simplifications after a RAUW. This is cheaper than checking all
638     // uses of To on the recursive step in most cases.
639     for (const User *U : OrigV->users())
640       Worklist.insert(cast<Instruction>(U));
641 
642     // Replace the instruction with its simplified value.
643     I->replaceAllUsesWith(SimpleV);
644 
645     // If the original instruction had no side effects, remove it.
646     if (isInstructionTriviallyDead(I))
647       I->eraseFromParent();
648     else
649       VMap[OrigV] = I;
650   }
651 
652   // Now that the inlined function body has been fully constructed, go through
653   // and zap unconditional fall-through branches. This happens all the time when
654   // specializing code: code specialization turns conditional branches into
655   // uncond branches, and this code folds them.
656   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
657   Function::iterator I = Begin;
658   while (I != NewFunc->end()) {
659     // We need to simplify conditional branches and switches with a constant
660     // operand. We try to prune these out when cloning, but if the
661     // simplification required looking through PHI nodes, those are only
662     // available after forming the full basic block. That may leave some here,
663     // and we still want to prune the dead code as early as possible.
664     //
665     // Do the folding before we check if the block is dead since we want code
666     // like
667     //  bb:
668     //    br i1 undef, label %bb, label %bb
669     // to be simplified to
670     //  bb:
671     //    br label %bb
672     // before we call I->getSinglePredecessor().
673     ConstantFoldTerminator(&*I);
674 
675     // Check if this block has become dead during inlining or other
676     // simplifications. Note that the first block will appear dead, as it has
677     // not yet been wired up properly.
678     if (I != Begin && (pred_empty(&*I) || I->getSinglePredecessor() == &*I)) {
679       BasicBlock *DeadBB = &*I++;
680       DeleteDeadBlock(DeadBB);
681       continue;
682     }
683 
684     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
685     if (!BI || BI->isConditional()) { ++I; continue; }
686 
687     BasicBlock *Dest = BI->getSuccessor(0);
688     if (!Dest->getSinglePredecessor()) {
689       ++I; continue;
690     }
691 
692     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
693     // above should have zapped all of them..
694     assert(!isa<PHINode>(Dest->begin()));
695 
696     // We know all single-entry PHI nodes in the inlined function have been
697     // removed, so we just need to splice the blocks.
698     BI->eraseFromParent();
699 
700     // Make all PHI nodes that referred to Dest now refer to I as their source.
701     Dest->replaceAllUsesWith(&*I);
702 
703     // Move all the instructions in the succ to the pred.
704     I->getInstList().splice(I->end(), Dest->getInstList());
705 
706     // Remove the dest block.
707     Dest->eraseFromParent();
708 
709     // Do not increment I, iteratively merge all things this block branches to.
710   }
711 
712   // Make a final pass over the basic blocks from the old function to gather
713   // any return instructions which survived folding. We have to do this here
714   // because we can iteratively remove and merge returns above.
715   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
716                           E = NewFunc->end();
717        I != E; ++I)
718     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
719       Returns.push_back(RI);
720 }
721 
722 
723 /// This works exactly like CloneFunctionInto,
724 /// except that it does some simple constant prop and DCE on the fly.  The
725 /// effect of this is to copy significantly less code in cases where (for
726 /// example) a function call with constant arguments is inlined, and those
727 /// constant arguments cause a significant amount of code in the callee to be
728 /// dead.  Since this doesn't produce an exact copy of the input, it can't be
729 /// used for things like CloneFunction or CloneModule.
730 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
731                                      ValueToValueMapTy &VMap,
732                                      bool ModuleLevelChanges,
733                                      SmallVectorImpl<ReturnInst*> &Returns,
734                                      const char *NameSuffix,
735                                      ClonedCodeInfo *CodeInfo,
736                                      Instruction *TheCall) {
737   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
738                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
739 }
740 
741 /// Remaps instructions in \p Blocks using the mapping in \p VMap.
742 void llvm::remapInstructionsInBlocks(
743     const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
744   // Rewrite the code to refer to itself.
745   for (auto *BB : Blocks)
746     for (auto &Inst : *BB)
747       RemapInstruction(&Inst, VMap,
748                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
749 }
750 
751 /// Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
752 /// Blocks.
753 ///
754 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
755 /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
756 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
757                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
758                                    const Twine &NameSuffix, LoopInfo *LI,
759                                    DominatorTree *DT,
760                                    SmallVectorImpl<BasicBlock *> &Blocks) {
761   Function *F = OrigLoop->getHeader()->getParent();
762   Loop *ParentLoop = OrigLoop->getParentLoop();
763   DenseMap<Loop *, Loop *> LMap;
764 
765   Loop *NewLoop = LI->AllocateLoop();
766   LMap[OrigLoop] = NewLoop;
767   if (ParentLoop)
768     ParentLoop->addChildLoop(NewLoop);
769   else
770     LI->addTopLevelLoop(NewLoop);
771 
772   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
773   assert(OrigPH && "No preheader");
774   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
775   // To rename the loop PHIs.
776   VMap[OrigPH] = NewPH;
777   Blocks.push_back(NewPH);
778 
779   // Update LoopInfo.
780   if (ParentLoop)
781     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
782 
783   // Update DominatorTree.
784   DT->addNewBlock(NewPH, LoopDomBB);
785 
786   for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
787     Loop *&NewLoop = LMap[CurLoop];
788     if (!NewLoop) {
789       NewLoop = LI->AllocateLoop();
790 
791       // Establish the parent/child relationship.
792       Loop *OrigParent = CurLoop->getParentLoop();
793       assert(OrigParent && "Could not find the original parent loop");
794       Loop *NewParentLoop = LMap[OrigParent];
795       assert(NewParentLoop && "Could not find the new parent loop");
796 
797       NewParentLoop->addChildLoop(NewLoop);
798     }
799   }
800 
801   for (BasicBlock *BB : OrigLoop->getBlocks()) {
802     Loop *CurLoop = LI->getLoopFor(BB);
803     Loop *&NewLoop = LMap[CurLoop];
804     assert(NewLoop && "Expecting new loop to be allocated");
805 
806     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
807     VMap[BB] = NewBB;
808 
809     // Update LoopInfo.
810     NewLoop->addBasicBlockToLoop(NewBB, *LI);
811 
812     // Add DominatorTree node. After seeing all blocks, update to correct
813     // IDom.
814     DT->addNewBlock(NewBB, NewPH);
815 
816     Blocks.push_back(NewBB);
817   }
818 
819   for (BasicBlock *BB : OrigLoop->getBlocks()) {
820     // Update loop headers.
821     Loop *CurLoop = LI->getLoopFor(BB);
822     if (BB == CurLoop->getHeader())
823       LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
824 
825     // Update DominatorTree.
826     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
827     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
828                                  cast<BasicBlock>(VMap[IDomBB]));
829   }
830 
831   // Move them physically from the end of the block list.
832   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
833                                 NewPH);
834   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
835                                 NewLoop->getHeader()->getIterator(), F->end());
836 
837   return NewLoop;
838 }
839 
840 /// Duplicate non-Phi instructions from the beginning of block up to
841 /// StopAt instruction into a split block between BB and its predecessor.
842 BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
843     BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
844     ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
845 
846   assert(count(successors(PredBB), BB) == 1 &&
847          "There must be a single edge between PredBB and BB!");
848   // We are going to have to map operands from the original BB block to the new
849   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
850   // account for entry from PredBB.
851   BasicBlock::iterator BI = BB->begin();
852   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
853     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
854 
855   BasicBlock *NewBB = SplitEdge(PredBB, BB);
856   NewBB->setName(PredBB->getName() + ".split");
857   Instruction *NewTerm = NewBB->getTerminator();
858 
859   // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
860   //        in the update set here.
861   DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
862                     {DominatorTree::Insert, PredBB, NewBB},
863                     {DominatorTree::Insert, NewBB, BB}});
864 
865   // Clone the non-phi instructions of BB into NewBB, keeping track of the
866   // mapping and using it to remap operands in the cloned instructions.
867   // Stop once we see the terminator too. This covers the case where BB's
868   // terminator gets replaced and StopAt == BB's terminator.
869   for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
870     Instruction *New = BI->clone();
871     New->setName(BI->getName());
872     New->insertBefore(NewTerm);
873     ValueMapping[&*BI] = New;
874 
875     // Remap operands to patch up intra-block references.
876     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
877       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
878         auto I = ValueMapping.find(Inst);
879         if (I != ValueMapping.end())
880           New->setOperand(i, I->second);
881       }
882   }
883 
884   return NewBB;
885 }
886 
887 void llvm::cloneNoAliasScopes(
888     ArrayRef<MDNode *> NoAliasDeclScopes,
889     DenseMap<MDNode *, MDNode *> &ClonedScopes,
890     StringRef Ext, LLVMContext &Context) {
891   MDBuilder MDB(Context);
892 
893   for (auto *ScopeList : NoAliasDeclScopes) {
894     for (auto &MDOperand : ScopeList->operands()) {
895       if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {
896         AliasScopeNode SNANode(MD);
897 
898         std::string Name;
899         auto ScopeName = SNANode.getName();
900         if (!ScopeName.empty())
901           Name = (Twine(ScopeName) + ":" + Ext).str();
902         else
903           Name = std::string(Ext);
904 
905         MDNode *NewScope = MDB.createAnonymousAliasScope(
906             const_cast<MDNode *>(SNANode.getDomain()), Name);
907         ClonedScopes.insert(std::make_pair(MD, NewScope));
908       }
909     }
910   }
911 }
912 
913 void llvm::adaptNoAliasScopes(
914     Instruction *I, const DenseMap<MDNode *, MDNode *> &ClonedScopes,
915     LLVMContext &Context) {
916   auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
917     bool NeedsReplacement = false;
918     SmallVector<Metadata *, 8> NewScopeList;
919     for (auto &MDOp : ScopeList->operands()) {
920       if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
921         if (auto *NewMD = ClonedScopes.lookup(MD)) {
922           NewScopeList.push_back(NewMD);
923           NeedsReplacement = true;
924           continue;
925         }
926         NewScopeList.push_back(MD);
927       }
928     }
929     if (NeedsReplacement)
930       return MDNode::get(Context, NewScopeList);
931     return nullptr;
932   };
933 
934   if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
935     if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
936       Decl->setScopeList(NewScopeList);
937 
938   auto replaceWhenNeeded = [&](unsigned MD_ID) {
939     if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
940       if (auto *NewScopeList = CloneScopeList(CSNoAlias))
941         I->setMetadata(MD_ID, NewScopeList);
942   };
943   replaceWhenNeeded(LLVMContext::MD_noalias);
944   replaceWhenNeeded(LLVMContext::MD_alias_scope);
945 }
946 
947 void llvm::cloneAndAdaptNoAliasScopes(
948     ArrayRef<MDNode *> NoAliasDeclScopes,
949     ArrayRef<BasicBlock *> NewBlocks, LLVMContext &Context, StringRef Ext) {
950   if (NoAliasDeclScopes.empty())
951     return;
952 
953   DenseMap<MDNode *, MDNode *> ClonedScopes;
954   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
955                     << NoAliasDeclScopes.size() << " node(s)\n");
956 
957   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
958   // Identify instructions using metadata that needs adaptation
959   for (BasicBlock *NewBlock : NewBlocks)
960     for (Instruction &I : *NewBlock)
961       adaptNoAliasScopes(&I, ClonedScopes, Context);
962 }
963 
964 void llvm::cloneAndAdaptNoAliasScopes(
965     ArrayRef<MDNode *> NoAliasDeclScopes, Instruction *IStart,
966     Instruction *IEnd, LLVMContext &Context, StringRef Ext) {
967   if (NoAliasDeclScopes.empty())
968     return;
969 
970   DenseMap<MDNode *, MDNode *> ClonedScopes;
971   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
972                     << NoAliasDeclScopes.size() << " node(s)\n");
973 
974   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
975   // Identify instructions using metadata that needs adaptation
976   assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
977   auto ItStart = IStart->getIterator();
978   auto ItEnd = IEnd->getIterator();
979   ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
980   for (auto &I : llvm::make_range(ItStart, ItEnd))
981     adaptNoAliasScopes(&I, ClonedScopes, Context);
982 }
983 
984 void llvm::identifyNoAliasScopesToClone(
985     ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
986   for (BasicBlock *BB : BBs)
987     for (Instruction &I : *BB)
988       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
989         NoAliasDeclScopes.push_back(Decl->getScopeList());
990 }
991