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