xref: /llvm-project/llvm/lib/Transforms/Utils/CloneFunction.cpp (revision 79b32bcda662a3e7789ad2835a021020fd2a5158)
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/AttributeMask.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.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 #include <optional>
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "clone-function"
42 
43 /// See comments in Cloning.h.
44 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
45                                   const Twine &NameSuffix, Function *F,
46                                   ClonedCodeInfo *CodeInfo,
47                                   DebugInfoFinder *DIFinder) {
48   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
49   NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;
50   if (BB->hasName())
51     NewBB->setName(BB->getName() + NameSuffix);
52 
53   bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
54   Module *TheModule = F ? F->getParent() : nullptr;
55 
56   // Loop over all instructions, and copy them over.
57   for (const Instruction &I : *BB) {
58     if (DIFinder && TheModule)
59       DIFinder->processInstruction(*TheModule, I);
60 
61     Instruction *NewInst = I.clone();
62     if (I.hasName())
63       NewInst->setName(I.getName() + NameSuffix);
64 
65     NewInst->insertBefore(*NewBB, NewBB->end());
66     NewInst->cloneDebugInfoFrom(&I);
67 
68     VMap[&I] = NewInst; // Add instruction map to value.
69 
70     if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {
71       hasCalls = true;
72       hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
73       hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_callsite);
74     }
75     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
76       if (!AI->isStaticAlloca()) {
77         hasDynamicAllocas = true;
78       }
79     }
80   }
81 
82   if (CodeInfo) {
83     CodeInfo->ContainsCalls |= hasCalls;
84     CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
85     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
86   }
87   return NewBB;
88 }
89 
90 // Clone OldFunc into NewFunc, transforming the old arguments into references to
91 // VMap values.
92 //
93 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
94                              ValueToValueMapTy &VMap,
95                              CloneFunctionChangeType Changes,
96                              SmallVectorImpl<ReturnInst *> &Returns,
97                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
98                              ValueMapTypeRemapper *TypeMapper,
99                              ValueMaterializer *Materializer) {
100   NewFunc->setIsNewDbgInfoFormat(OldFunc->IsNewDbgInfoFormat);
101   assert(NameSuffix && "NameSuffix cannot be null!");
102 
103 #ifndef NDEBUG
104   for (const Argument &I : OldFunc->args())
105     assert(VMap.count(&I) && "No mapping from source argument specified!");
106 #endif
107 
108   bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
109 
110   // Copy all attributes other than those stored in the AttributeList.  We need
111   // to remap the parameter indices of the AttributeList.
112   AttributeList NewAttrs = NewFunc->getAttributes();
113   NewFunc->copyAttributesFrom(OldFunc);
114   NewFunc->setAttributes(NewAttrs);
115 
116   const RemapFlags FuncGlobalRefFlags =
117       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
118 
119   // Fix up the personality function that got copied over.
120   if (OldFunc->hasPersonalityFn())
121     NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,
122                                        FuncGlobalRefFlags, TypeMapper,
123                                        Materializer));
124 
125   if (OldFunc->hasPrefixData()) {
126     NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,
127                                     FuncGlobalRefFlags, TypeMapper,
128                                     Materializer));
129   }
130 
131   if (OldFunc->hasPrologueData()) {
132     NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,
133                                       FuncGlobalRefFlags, TypeMapper,
134                                       Materializer));
135   }
136 
137   SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
138   AttributeList OldAttrs = OldFunc->getAttributes();
139 
140   // Clone any argument attributes that are present in the VMap.
141   for (const Argument &OldArg : OldFunc->args()) {
142     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
143       NewArgAttrs[NewArg->getArgNo()] =
144           OldAttrs.getParamAttrs(OldArg.getArgNo());
145     }
146   }
147 
148   NewFunc->setAttributes(
149       AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
150                          OldAttrs.getRetAttrs(), NewArgAttrs));
151 
152   // Everything else beyond this point deals with function instructions,
153   // so if we are dealing with a function declaration, we're done.
154   if (OldFunc->isDeclaration())
155     return;
156 
157   // When we remap instructions within the same module, we want to avoid
158   // duplicating inlined DISubprograms, so record all subprograms we find as we
159   // duplicate instructions and then freeze them in the MD map. We also record
160   // information about dbg.value and dbg.declare to avoid duplicating the
161   // types.
162   std::optional<DebugInfoFinder> DIFinder;
163 
164   // Track the subprogram attachment that needs to be cloned to fine-tune the
165   // mapping within the same module.
166   DISubprogram *SPClonedWithinModule = nullptr;
167   if (Changes < CloneFunctionChangeType::DifferentModule) {
168     assert((NewFunc->getParent() == nullptr ||
169             NewFunc->getParent() == OldFunc->getParent()) &&
170            "Expected NewFunc to have the same parent, or no parent");
171 
172     // Need to find subprograms, types, and compile units.
173     DIFinder.emplace();
174 
175     SPClonedWithinModule = OldFunc->getSubprogram();
176     if (SPClonedWithinModule)
177       DIFinder->processSubprogram(SPClonedWithinModule);
178   } else {
179     assert((NewFunc->getParent() == nullptr ||
180             NewFunc->getParent() != OldFunc->getParent()) &&
181            "Expected NewFunc to have different parents, or no parent");
182 
183     if (Changes == CloneFunctionChangeType::DifferentModule) {
184       assert(NewFunc->getParent() &&
185              "Need parent of new function to maintain debug info invariants");
186 
187       // Need to find all the compile units.
188       DIFinder.emplace();
189     }
190   }
191 
192   // Loop over all of the basic blocks in the function, cloning them as
193   // appropriate.  Note that we save BE this way in order to handle cloning of
194   // recursive functions into themselves.
195   for (const BasicBlock &BB : *OldFunc) {
196 
197     // Create a new basic block and copy instructions into it!
198     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
199                                       DIFinder ? &*DIFinder : nullptr);
200 
201     // Add basic block mapping.
202     VMap[&BB] = CBB;
203 
204     // It is only legal to clone a function if a block address within that
205     // function is never referenced outside of the function.  Given that, we
206     // want to map block addresses from the old function to block addresses in
207     // the clone. (This is different from the generic ValueMapper
208     // implementation, which generates an invalid blockaddress when
209     // cloning a function.)
210     if (BB.hasAddressTaken()) {
211       Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
212                                               const_cast<BasicBlock *>(&BB));
213       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
214     }
215 
216     // Note return instructions for the caller.
217     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
218       Returns.push_back(RI);
219   }
220 
221   if (Changes < CloneFunctionChangeType::DifferentModule &&
222       DIFinder->subprogram_count() > 0) {
223     // Turn on module-level changes, since we need to clone (some of) the
224     // debug info metadata.
225     //
226     // FIXME: Metadata effectively owned by a function should be made
227     // local, and only that local metadata should be cloned.
228     ModuleLevelChanges = true;
229 
230     auto mapToSelfIfNew = [&VMap](MDNode *N) {
231       // Avoid clobbering an existing mapping.
232       (void)VMap.MD().try_emplace(N, N);
233     };
234 
235     // Avoid cloning types, compile units, and (other) subprograms.
236     SmallPtrSet<const DISubprogram *, 16> MappedToSelfSPs;
237     for (DISubprogram *ISP : DIFinder->subprograms()) {
238       if (ISP != SPClonedWithinModule) {
239         mapToSelfIfNew(ISP);
240         MappedToSelfSPs.insert(ISP);
241       }
242     }
243 
244     // If a subprogram isn't going to be cloned skip its lexical blocks as well.
245     for (DIScope *S : DIFinder->scopes()) {
246       auto *LScope = dyn_cast<DILocalScope>(S);
247       if (LScope && MappedToSelfSPs.count(LScope->getSubprogram()))
248         mapToSelfIfNew(S);
249     }
250 
251     for (DICompileUnit *CU : DIFinder->compile_units())
252       mapToSelfIfNew(CU);
253 
254     for (DIType *Type : DIFinder->types())
255       mapToSelfIfNew(Type);
256   } else {
257     assert(!SPClonedWithinModule &&
258            "Subprogram should be in DIFinder->subprogram_count()...");
259   }
260 
261   const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
262   // Duplicate the metadata that is attached to the cloned function.
263   // Subprograms/CUs/types that were already mapped to themselves won't be
264   // duplicated.
265   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
266   OldFunc->getAllMetadata(MDs);
267   for (auto MD : MDs) {
268     NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag,
269                                                 TypeMapper, Materializer));
270   }
271 
272   // Loop over all of the instructions in the new function, fixing up operand
273   // references as we go. This uses VMap to do all the hard work.
274   for (Function::iterator
275            BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
276            BE = NewFunc->end();
277        BB != BE; ++BB)
278     // Loop over all instructions, fixing each one as we find it, and any
279     // attached debug-info records.
280     for (Instruction &II : *BB) {
281       RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer);
282       RemapDbgRecordRange(II.getModule(), II.getDbgRecordRange(), VMap,
283                           RemapFlag, TypeMapper, Materializer);
284     }
285 
286   // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
287   // same module, the compile unit will already be listed (or not). When
288   // cloning a module, CloneModule() will handle creating the named metadata.
289   if (Changes != CloneFunctionChangeType::DifferentModule)
290     return;
291 
292   // Update !llvm.dbg.cu with compile units added to the new module if this
293   // function is being cloned in isolation.
294   //
295   // FIXME: This is making global / module-level changes, which doesn't seem
296   // like the right encapsulation  Consider dropping the requirement to update
297   // !llvm.dbg.cu (either obsoleting the node, or restricting it to
298   // non-discardable compile units) instead of discovering compile units by
299   // visiting the metadata attached to global values, which would allow this
300   // code to be deleted. Alternatively, perhaps give responsibility for this
301   // update to CloneFunctionInto's callers.
302   auto *NewModule = NewFunc->getParent();
303   auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
304   // Avoid multiple insertions of the same DICompileUnit to NMD.
305   SmallPtrSet<const void *, 8> Visited;
306   for (auto *Operand : NMD->operands())
307     Visited.insert(Operand);
308   for (auto *Unit : DIFinder->compile_units()) {
309     MDNode *MappedUnit =
310         MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
311     if (Visited.insert(MappedUnit).second)
312       NMD->addOperand(MappedUnit);
313   }
314 }
315 
316 /// Return a copy of the specified function and add it to that function's
317 /// module.  Also, any references specified in the VMap are changed to refer to
318 /// their mapped value instead of the original one.  If any of the arguments to
319 /// the function are in the VMap, the arguments are deleted from the resultant
320 /// function.  The VMap is updated to include mappings from all of the
321 /// instructions and basicblocks in the function from their old to new values.
322 ///
323 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
324                               ClonedCodeInfo *CodeInfo) {
325   std::vector<Type *> ArgTypes;
326 
327   // The user might be deleting arguments to the function by specifying them in
328   // the VMap.  If so, we need to not add the arguments to the arg ty vector
329   //
330   for (const Argument &I : F->args())
331     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
332       ArgTypes.push_back(I.getType());
333 
334   // Create a new function type...
335   FunctionType *FTy =
336       FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
337                         F->getFunctionType()->isVarArg());
338 
339   // Create the new function...
340   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
341                                     F->getName(), F->getParent());
342   NewF->setIsNewDbgInfoFormat(F->IsNewDbgInfoFormat);
343 
344   // Loop over the arguments, copying the names of the mapped arguments over...
345   Function::arg_iterator DestI = NewF->arg_begin();
346   for (const Argument &I : F->args())
347     if (VMap.count(&I) == 0) {     // Is this argument preserved?
348       DestI->setName(I.getName()); // Copy the name over...
349       VMap[&I] = &*DestI++;        // Add mapping to VMap
350     }
351 
352   SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
353   CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
354                     Returns, "", CodeInfo);
355 
356   return NewF;
357 }
358 
359 namespace {
360 /// This is a private class used to implement CloneAndPruneFunctionInto.
361 struct PruningFunctionCloner {
362   Function *NewFunc;
363   const Function *OldFunc;
364   ValueToValueMapTy &VMap;
365   bool ModuleLevelChanges;
366   const char *NameSuffix;
367   ClonedCodeInfo *CodeInfo;
368   bool HostFuncIsStrictFP;
369 
370   Instruction *cloneInstruction(BasicBlock::const_iterator II);
371 
372 public:
373   PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
374                         ValueToValueMapTy &valueMap, bool moduleLevelChanges,
375                         const char *nameSuffix, ClonedCodeInfo *codeInfo)
376       : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
377         ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
378         CodeInfo(codeInfo) {
379     HostFuncIsStrictFP =
380         newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
381   }
382 
383   /// The specified block is found to be reachable, clone it and
384   /// anything that it can reach.
385   void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
386                   std::vector<const BasicBlock *> &ToClone);
387 };
388 } // namespace
389 
390 Instruction *
391 PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
392   const Instruction &OldInst = *II;
393   Instruction *NewInst = nullptr;
394   if (HostFuncIsStrictFP) {
395     Intrinsic::ID CIID = getConstrainedIntrinsicID(OldInst);
396     if (CIID != Intrinsic::not_intrinsic) {
397       // Instead of cloning the instruction, a call to constrained intrinsic
398       // should be created.
399       // Assume the first arguments of constrained intrinsics are the same as
400       // the operands of original instruction.
401 
402       // Determine overloaded types of the intrinsic.
403       SmallVector<Type *, 2> TParams;
404       SmallVector<Intrinsic::IITDescriptor, 8> Descriptor;
405       getIntrinsicInfoTableEntries(CIID, Descriptor);
406       for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {
407         Intrinsic::IITDescriptor Operand = Descriptor[I];
408         switch (Operand.Kind) {
409         case Intrinsic::IITDescriptor::Argument:
410           if (Operand.getArgumentKind() !=
411               Intrinsic::IITDescriptor::AK_MatchType) {
412             if (I == 0)
413               TParams.push_back(OldInst.getType());
414             else
415               TParams.push_back(OldInst.getOperand(I - 1)->getType());
416           }
417           break;
418         case Intrinsic::IITDescriptor::SameVecWidthArgument:
419           ++I;
420           break;
421         default:
422           break;
423         }
424       }
425 
426       // Create intrinsic call.
427       LLVMContext &Ctx = NewFunc->getContext();
428       Function *IFn =
429           Intrinsic::getDeclaration(NewFunc->getParent(), CIID, TParams);
430       SmallVector<Value *, 4> Args;
431       unsigned NumOperands = OldInst.getNumOperands();
432       if (isa<CallInst>(OldInst))
433         --NumOperands;
434       for (unsigned I = 0; I < NumOperands; ++I) {
435         Value *Op = OldInst.getOperand(I);
436         Args.push_back(Op);
437       }
438       if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
439         FCmpInst::Predicate Pred = CmpI->getPredicate();
440         StringRef PredName = FCmpInst::getPredicateName(Pred);
441         Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
442       }
443 
444       // The last arguments of a constrained intrinsic are metadata that
445       // represent rounding mode (absents in some intrinsics) and exception
446       // behavior. The inlined function uses default settings.
447       if (Intrinsic::hasConstrainedFPRoundingModeOperand(CIID))
448         Args.push_back(
449             MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
450       Args.push_back(
451           MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
452 
453       NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
454     }
455   }
456   if (!NewInst)
457     NewInst = II->clone();
458   return NewInst;
459 }
460 
461 /// The specified block is found to be reachable, clone it and
462 /// anything that it can reach.
463 void PruningFunctionCloner::CloneBlock(
464     const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
465     std::vector<const BasicBlock *> &ToClone) {
466   WeakTrackingVH &BBEntry = VMap[BB];
467 
468   // Have we already cloned this block?
469   if (BBEntry)
470     return;
471 
472   // Nope, clone it now.
473   BasicBlock *NewBB;
474   Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");
475   BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);
476   NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;
477 
478   // It is only legal to clone a function if a block address within that
479   // function is never referenced outside of the function.  Given that, we
480   // want to map block addresses from the old function to block addresses in
481   // the clone. (This is different from the generic ValueMapper
482   // implementation, which generates an invalid blockaddress when
483   // cloning a function.)
484   //
485   // Note that we don't need to fix the mapping for unreachable blocks;
486   // the default mapping there is safe.
487   if (BB->hasAddressTaken()) {
488     Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
489                                             const_cast<BasicBlock *>(BB));
490     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
491   }
492 
493   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
494   bool hasMemProfMetadata = false;
495 
496   // Keep a cursor pointing at the last place we cloned debug-info records from.
497   BasicBlock::const_iterator DbgCursor = StartingInst;
498   auto CloneDbgRecordsToHere =
499       [NewBB, &DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {
500         if (!NewBB->IsNewDbgInfoFormat)
501           return;
502 
503         // Clone debug-info records onto this instruction. Iterate through any
504         // source-instructions we've cloned and then subsequently optimised
505         // away, so that their debug-info doesn't go missing.
506         for (; DbgCursor != II; ++DbgCursor)
507           NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);
508         NewInst->cloneDebugInfoFrom(&*II);
509         DbgCursor = std::next(II);
510       };
511 
512   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
513   // loop doesn't include the terminator.
514   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
515        ++II) {
516 
517     // Don't clone fake_use as it may suppress many optimizations
518     // due to inlining, especially SROA.
519     if (auto *IntrInst = dyn_cast<IntrinsicInst>(II))
520       if (IntrInst->getIntrinsicID() == Intrinsic::fake_use)
521         continue;
522 
523     Instruction *NewInst = cloneInstruction(II);
524     NewInst->insertInto(NewBB, NewBB->end());
525 
526     if (HostFuncIsStrictFP) {
527       // All function calls in the inlined function must get 'strictfp'
528       // attribute to prevent undesirable optimizations.
529       if (auto *Call = dyn_cast<CallInst>(NewInst))
530         Call->addFnAttr(Attribute::StrictFP);
531     }
532 
533     // Eagerly remap operands to the newly cloned instruction, except for PHI
534     // nodes for which we defer processing until we update the CFG. Also defer
535     // debug intrinsic processing because they may contain use-before-defs.
536     if (!isa<PHINode>(NewInst) && !isa<DbgVariableIntrinsic>(NewInst)) {
537       RemapInstruction(NewInst, VMap,
538                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
539 
540       // Eagerly constant fold the newly cloned instruction. If successful, add
541       // a mapping to the new value. Non-constant operands may be incomplete at
542       // this stage, thus instruction simplification is performed after
543       // processing phi-nodes.
544       if (Value *V = ConstantFoldInstruction(
545               NewInst, BB->getDataLayout())) {
546         if (isInstructionTriviallyDead(NewInst)) {
547           VMap[&*II] = V;
548           NewInst->eraseFromParent();
549           continue;
550         }
551       }
552     }
553 
554     if (II->hasName())
555       NewInst->setName(II->getName() + NameSuffix);
556     VMap[&*II] = NewInst; // Add instruction map to value.
557     if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {
558       hasCalls = true;
559       hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
560       hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_callsite);
561     }
562 
563     CloneDbgRecordsToHere(NewInst, II);
564 
565     if (CodeInfo) {
566       CodeInfo->OrigVMap[&*II] = NewInst;
567       if (auto *CB = dyn_cast<CallBase>(&*II))
568         if (CB->hasOperandBundles())
569           CodeInfo->OperandBundleCallSites.push_back(NewInst);
570     }
571 
572     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
573       if (isa<ConstantInt>(AI->getArraySize()))
574         hasStaticAllocas = true;
575       else
576         hasDynamicAllocas = true;
577     }
578   }
579 
580   // Finally, clone over the terminator.
581   const Instruction *OldTI = BB->getTerminator();
582   bool TerminatorDone = false;
583   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
584     if (BI->isConditional()) {
585       // If the condition was a known constant in the callee...
586       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
587       // Or is a known constant in the caller...
588       if (!Cond) {
589         Value *V = VMap.lookup(BI->getCondition());
590         Cond = dyn_cast_or_null<ConstantInt>(V);
591       }
592 
593       // Constant fold to uncond branch!
594       if (Cond) {
595         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
596         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
597         ToClone.push_back(Dest);
598         TerminatorDone = true;
599       }
600     }
601   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
602     // If switching on a value known constant in the caller.
603     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
604     if (!Cond) { // Or known constant after constant prop in the callee...
605       Value *V = VMap.lookup(SI->getCondition());
606       Cond = dyn_cast_or_null<ConstantInt>(V);
607     }
608     if (Cond) { // Constant fold to uncond branch!
609       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
610       BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
611       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
612       ToClone.push_back(Dest);
613       TerminatorDone = true;
614     }
615   }
616 
617   if (!TerminatorDone) {
618     Instruction *NewInst = OldTI->clone();
619     if (OldTI->hasName())
620       NewInst->setName(OldTI->getName() + NameSuffix);
621     NewInst->insertInto(NewBB, NewBB->end());
622 
623     CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
624 
625     VMap[OldTI] = NewInst; // Add instruction map to value.
626 
627     if (CodeInfo) {
628       CodeInfo->OrigVMap[OldTI] = NewInst;
629       if (auto *CB = dyn_cast<CallBase>(OldTI))
630         if (CB->hasOperandBundles())
631           CodeInfo->OperandBundleCallSites.push_back(NewInst);
632     }
633 
634     // Recursively clone any reachable successor blocks.
635     append_range(ToClone, successors(BB->getTerminator()));
636   } else {
637     // If we didn't create a new terminator, clone DbgVariableRecords from the
638     // old terminator onto the new terminator.
639     Instruction *NewInst = NewBB->getTerminator();
640     assert(NewInst);
641 
642     CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
643   }
644 
645   if (CodeInfo) {
646     CodeInfo->ContainsCalls |= hasCalls;
647     CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
648     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
649     CodeInfo->ContainsDynamicAllocas |=
650         hasStaticAllocas && BB != &BB->getParent()->front();
651   }
652 }
653 
654 /// This works like CloneAndPruneFunctionInto, except that it does not clone the
655 /// entire function. Instead it starts at an instruction provided by the caller
656 /// and copies (and prunes) only the code reachable from that instruction.
657 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
658                                      const Instruction *StartingInst,
659                                      ValueToValueMapTy &VMap,
660                                      bool ModuleLevelChanges,
661                                      SmallVectorImpl<ReturnInst *> &Returns,
662                                      const char *NameSuffix,
663                                      ClonedCodeInfo *CodeInfo) {
664   assert(NameSuffix && "NameSuffix cannot be null!");
665 
666   ValueMapTypeRemapper *TypeMapper = nullptr;
667   ValueMaterializer *Materializer = nullptr;
668 
669 #ifndef NDEBUG
670   // If the cloning starts at the beginning of the function, verify that
671   // the function arguments are mapped.
672   if (!StartingInst)
673     for (const Argument &II : OldFunc->args())
674       assert(VMap.count(&II) && "No mapping from source argument specified!");
675 #endif
676 
677   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
678                             NameSuffix, CodeInfo);
679   const BasicBlock *StartingBB;
680   if (StartingInst)
681     StartingBB = StartingInst->getParent();
682   else {
683     StartingBB = &OldFunc->getEntryBlock();
684     StartingInst = &StartingBB->front();
685   }
686 
687   // Collect debug intrinsics for remapping later.
688   SmallVector<const DbgVariableIntrinsic *, 8> DbgIntrinsics;
689   for (const auto &BB : *OldFunc) {
690     for (const auto &I : BB) {
691       if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
692         DbgIntrinsics.push_back(DVI);
693     }
694   }
695 
696   // Clone the entry block, and anything recursively reachable from it.
697   std::vector<const BasicBlock *> CloneWorklist;
698   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
699   while (!CloneWorklist.empty()) {
700     const BasicBlock *BB = CloneWorklist.back();
701     CloneWorklist.pop_back();
702     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
703   }
704 
705   // Loop over all of the basic blocks in the old function.  If the block was
706   // reachable, we have cloned it and the old block is now in the value map:
707   // insert it into the new function in the right order.  If not, ignore it.
708   //
709   // Defer PHI resolution until rest of function is resolved.
710   SmallVector<const PHINode *, 16> PHIToResolve;
711   for (const BasicBlock &BI : *OldFunc) {
712     Value *V = VMap.lookup(&BI);
713     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
714     if (!NewBB)
715       continue; // Dead block.
716 
717     // Move the new block to preserve the order in the original function.
718     NewBB->moveBefore(NewFunc->end());
719 
720     // Handle PHI nodes specially, as we have to remove references to dead
721     // blocks.
722     for (const PHINode &PN : BI.phis()) {
723       // PHI nodes may have been remapped to non-PHI nodes by the caller or
724       // during the cloning process.
725       if (isa<PHINode>(VMap[&PN]))
726         PHIToResolve.push_back(&PN);
727       else
728         break;
729     }
730 
731     // Finally, remap the terminator instructions, as those can't be remapped
732     // until all BBs are mapped.
733     RemapInstruction(NewBB->getTerminator(), VMap,
734                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
735                      TypeMapper, Materializer);
736   }
737 
738   // Defer PHI resolution until rest of function is resolved, PHI resolution
739   // requires the CFG to be up-to-date.
740   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
741     const PHINode *OPN = PHIToResolve[phino];
742     unsigned NumPreds = OPN->getNumIncomingValues();
743     const BasicBlock *OldBB = OPN->getParent();
744     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
745 
746     // Map operands for blocks that are live and remove operands for blocks
747     // that are dead.
748     for (; phino != PHIToResolve.size() &&
749            PHIToResolve[phino]->getParent() == OldBB;
750          ++phino) {
751       OPN = PHIToResolve[phino];
752       PHINode *PN = cast<PHINode>(VMap[OPN]);
753       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
754         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
755         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
756           Value *InVal =
757               MapValue(PN->getIncomingValue(pred), VMap,
758                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
759           assert(InVal && "Unknown input value?");
760           PN->setIncomingValue(pred, InVal);
761           PN->setIncomingBlock(pred, MappedBlock);
762         } else {
763           PN->removeIncomingValue(pred, false);
764           --pred; // Revisit the next entry.
765           --e;
766         }
767       }
768     }
769 
770     // The loop above has removed PHI entries for those blocks that are dead
771     // and has updated others.  However, if a block is live (i.e. copied over)
772     // but its terminator has been changed to not go to this block, then our
773     // phi nodes will have invalid entries.  Update the PHI nodes in this
774     // case.
775     PHINode *PN = cast<PHINode>(NewBB->begin());
776     NumPreds = pred_size(NewBB);
777     if (NumPreds != PN->getNumIncomingValues()) {
778       assert(NumPreds < PN->getNumIncomingValues());
779       // Count how many times each predecessor comes to this block.
780       std::map<BasicBlock *, unsigned> PredCount;
781       for (BasicBlock *Pred : predecessors(NewBB))
782         --PredCount[Pred];
783 
784       // Figure out how many entries to remove from each PHI.
785       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
786         ++PredCount[PN->getIncomingBlock(i)];
787 
788       // At this point, the excess predecessor entries are positive in the
789       // map.  Loop over all of the PHIs and remove excess predecessor
790       // entries.
791       BasicBlock::iterator I = NewBB->begin();
792       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
793         for (const auto &PCI : PredCount) {
794           BasicBlock *Pred = PCI.first;
795           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
796             PN->removeIncomingValue(Pred, false);
797         }
798       }
799     }
800 
801     // If the loops above have made these phi nodes have 0 or 1 operand,
802     // replace them with poison or the input value.  We must do this for
803     // correctness, because 0-operand phis are not valid.
804     PN = cast<PHINode>(NewBB->begin());
805     if (PN->getNumIncomingValues() == 0) {
806       BasicBlock::iterator I = NewBB->begin();
807       BasicBlock::const_iterator OldI = OldBB->begin();
808       while ((PN = dyn_cast<PHINode>(I++))) {
809         Value *NV = PoisonValue::get(PN->getType());
810         PN->replaceAllUsesWith(NV);
811         assert(VMap[&*OldI] == PN && "VMap mismatch");
812         VMap[&*OldI] = NV;
813         PN->eraseFromParent();
814         ++OldI;
815       }
816     }
817   }
818 
819   // Drop all incompatible return attributes that cannot be applied to NewFunc
820   // during cloning, so as to allow instruction simplification to reason on the
821   // old state of the function. The original attributes are restored later.
822   AttributeMask IncompatibleAttrs =
823       AttributeFuncs::typeIncompatible(OldFunc->getReturnType());
824   AttributeList Attrs = NewFunc->getAttributes();
825   NewFunc->removeRetAttrs(IncompatibleAttrs);
826 
827   // As phi-nodes have been now remapped, allow incremental simplification of
828   // newly-cloned instructions.
829   const DataLayout &DL = NewFunc->getDataLayout();
830   for (const auto &BB : *OldFunc) {
831     for (const auto &I : BB) {
832       auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));
833       if (!NewI)
834         continue;
835 
836       if (Value *V = simplifyInstruction(NewI, DL)) {
837         NewI->replaceAllUsesWith(V);
838 
839         if (isInstructionTriviallyDead(NewI)) {
840           NewI->eraseFromParent();
841         } else {
842           // Did not erase it? Restore the new instruction into VMap previously
843           // dropped by `ValueIsRAUWd`.
844           VMap[&I] = NewI;
845         }
846       }
847     }
848   }
849 
850   // Restore attributes.
851   NewFunc->setAttributes(Attrs);
852 
853   // Remap debug intrinsic operands now that all values have been mapped.
854   // Doing this now (late) preserves use-before-defs in debug intrinsics. If
855   // we didn't do this, ValueAsMetadata(use-before-def) operands would be
856   // replaced by empty metadata. This would signal later cleanup passes to
857   // remove the debug intrinsics, potentially causing incorrect locations.
858   for (const auto *DVI : DbgIntrinsics) {
859     if (DbgVariableIntrinsic *NewDVI =
860             cast_or_null<DbgVariableIntrinsic>(VMap.lookup(DVI)))
861       RemapInstruction(NewDVI, VMap,
862                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
863                        TypeMapper, Materializer);
864   }
865 
866   // Do the same for DbgVariableRecords, touching all the instructions in the
867   // cloned range of blocks.
868   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
869   for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {
870     for (Instruction &I : BB) {
871       RemapDbgRecordRange(I.getModule(), I.getDbgRecordRange(), VMap,
872                           ModuleLevelChanges ? RF_None
873                                              : RF_NoModuleLevelChanges,
874                           TypeMapper, Materializer);
875     }
876   }
877 
878   // Simplify conditional branches and switches with a constant operand. We try
879   // to prune these out when cloning, but if the simplification required
880   // looking through PHI nodes, those are only available after forming the full
881   // basic block. That may leave some here, and we still want to prune the dead
882   // code as early as possible.
883   for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
884     ConstantFoldTerminator(&BB);
885 
886   // Some blocks may have become unreachable as a result. Find and delete them.
887   {
888     SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
889     SmallVector<BasicBlock *, 16> Worklist;
890     Worklist.push_back(&*Begin);
891     while (!Worklist.empty()) {
892       BasicBlock *BB = Worklist.pop_back_val();
893       if (ReachableBlocks.insert(BB).second)
894         append_range(Worklist, successors(BB));
895     }
896 
897     SmallVector<BasicBlock *, 16> UnreachableBlocks;
898     for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
899       if (!ReachableBlocks.contains(&BB))
900         UnreachableBlocks.push_back(&BB);
901     DeleteDeadBlocks(UnreachableBlocks);
902   }
903 
904   // Now that the inlined function body has been fully constructed, go through
905   // and zap unconditional fall-through branches. This happens all the time when
906   // specializing code: code specialization turns conditional branches into
907   // uncond branches, and this code folds them.
908   Function::iterator I = Begin;
909   while (I != NewFunc->end()) {
910     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
911     if (!BI || BI->isConditional()) {
912       ++I;
913       continue;
914     }
915 
916     BasicBlock *Dest = BI->getSuccessor(0);
917     if (!Dest->getSinglePredecessor()) {
918       ++I;
919       continue;
920     }
921 
922     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
923     // above should have zapped all of them..
924     assert(!isa<PHINode>(Dest->begin()));
925 
926     // We know all single-entry PHI nodes in the inlined function have been
927     // removed, so we just need to splice the blocks.
928     BI->eraseFromParent();
929 
930     // Make all PHI nodes that referred to Dest now refer to I as their source.
931     Dest->replaceAllUsesWith(&*I);
932 
933     // Move all the instructions in the succ to the pred.
934     I->splice(I->end(), Dest);
935 
936     // Remove the dest block.
937     Dest->eraseFromParent();
938 
939     // Do not increment I, iteratively merge all things this block branches to.
940   }
941 
942   // Make a final pass over the basic blocks from the old function to gather
943   // any return instructions which survived folding. We have to do this here
944   // because we can iteratively remove and merge returns above.
945   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
946                           E = NewFunc->end();
947        I != E; ++I)
948     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
949       Returns.push_back(RI);
950 }
951 
952 /// This works exactly like CloneFunctionInto,
953 /// except that it does some simple constant prop and DCE on the fly.  The
954 /// effect of this is to copy significantly less code in cases where (for
955 /// example) a function call with constant arguments is inlined, and those
956 /// constant arguments cause a significant amount of code in the callee to be
957 /// dead.  Since this doesn't produce an exact copy of the input, it can't be
958 /// used for things like CloneFunction or CloneModule.
959 void llvm::CloneAndPruneFunctionInto(
960     Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
961     bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
962     const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
963   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
964                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
965 }
966 
967 /// Remaps instructions in \p Blocks using the mapping in \p VMap.
968 void llvm::remapInstructionsInBlocks(ArrayRef<BasicBlock *> Blocks,
969                                      ValueToValueMapTy &VMap) {
970   // Rewrite the code to refer to itself.
971   for (auto *BB : Blocks) {
972     for (auto &Inst : *BB) {
973       RemapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange(), VMap,
974                           RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
975       RemapInstruction(&Inst, VMap,
976                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
977     }
978   }
979 }
980 
981 /// Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
982 /// Blocks.
983 ///
984 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
985 /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
986 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
987                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
988                                    const Twine &NameSuffix, LoopInfo *LI,
989                                    DominatorTree *DT,
990                                    SmallVectorImpl<BasicBlock *> &Blocks) {
991   Function *F = OrigLoop->getHeader()->getParent();
992   Loop *ParentLoop = OrigLoop->getParentLoop();
993   DenseMap<Loop *, Loop *> LMap;
994 
995   Loop *NewLoop = LI->AllocateLoop();
996   LMap[OrigLoop] = NewLoop;
997   if (ParentLoop)
998     ParentLoop->addChildLoop(NewLoop);
999   else
1000     LI->addTopLevelLoop(NewLoop);
1001 
1002   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
1003   assert(OrigPH && "No preheader");
1004   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
1005   // To rename the loop PHIs.
1006   VMap[OrigPH] = NewPH;
1007   Blocks.push_back(NewPH);
1008 
1009   // Update LoopInfo.
1010   if (ParentLoop)
1011     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
1012 
1013   // Update DominatorTree.
1014   DT->addNewBlock(NewPH, LoopDomBB);
1015 
1016   for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
1017     Loop *&NewLoop = LMap[CurLoop];
1018     if (!NewLoop) {
1019       NewLoop = LI->AllocateLoop();
1020 
1021       // Establish the parent/child relationship.
1022       Loop *OrigParent = CurLoop->getParentLoop();
1023       assert(OrigParent && "Could not find the original parent loop");
1024       Loop *NewParentLoop = LMap[OrigParent];
1025       assert(NewParentLoop && "Could not find the new parent loop");
1026 
1027       NewParentLoop->addChildLoop(NewLoop);
1028     }
1029   }
1030 
1031   for (BasicBlock *BB : OrigLoop->getBlocks()) {
1032     Loop *CurLoop = LI->getLoopFor(BB);
1033     Loop *&NewLoop = LMap[CurLoop];
1034     assert(NewLoop && "Expecting new loop to be allocated");
1035 
1036     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
1037     VMap[BB] = NewBB;
1038 
1039     // Update LoopInfo.
1040     NewLoop->addBasicBlockToLoop(NewBB, *LI);
1041 
1042     // Add DominatorTree node. After seeing all blocks, update to correct
1043     // IDom.
1044     DT->addNewBlock(NewBB, NewPH);
1045 
1046     Blocks.push_back(NewBB);
1047   }
1048 
1049   for (BasicBlock *BB : OrigLoop->getBlocks()) {
1050     // Update loop headers.
1051     Loop *CurLoop = LI->getLoopFor(BB);
1052     if (BB == CurLoop->getHeader())
1053       LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1054 
1055     // Update DominatorTree.
1056     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
1057     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
1058                                  cast<BasicBlock>(VMap[IDomBB]));
1059   }
1060 
1061   // Move them physically from the end of the block list.
1062   F->splice(Before->getIterator(), F, NewPH->getIterator());
1063   F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),
1064             F->end());
1065 
1066   return NewLoop;
1067 }
1068 
1069 /// Duplicate non-Phi instructions from the beginning of block up to
1070 /// StopAt instruction into a split block between BB and its predecessor.
1071 BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
1072     BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
1073     ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
1074 
1075   assert(count(successors(PredBB), BB) == 1 &&
1076          "There must be a single edge between PredBB and BB!");
1077   // We are going to have to map operands from the original BB block to the new
1078   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1079   // account for entry from PredBB.
1080   BasicBlock::iterator BI = BB->begin();
1081   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1082     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1083 
1084   BasicBlock *NewBB = SplitEdge(PredBB, BB);
1085   NewBB->setName(PredBB->getName() + ".split");
1086   Instruction *NewTerm = NewBB->getTerminator();
1087 
1088   // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
1089   //        in the update set here.
1090   DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
1091                     {DominatorTree::Insert, PredBB, NewBB},
1092                     {DominatorTree::Insert, NewBB, BB}});
1093 
1094   // Clone the non-phi instructions of BB into NewBB, keeping track of the
1095   // mapping and using it to remap operands in the cloned instructions.
1096   // Stop once we see the terminator too. This covers the case where BB's
1097   // terminator gets replaced and StopAt == BB's terminator.
1098   for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
1099     Instruction *New = BI->clone();
1100     New->setName(BI->getName());
1101     New->insertBefore(NewTerm);
1102     New->cloneDebugInfoFrom(&*BI);
1103     ValueMapping[&*BI] = New;
1104 
1105     // Remap operands to patch up intra-block references.
1106     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1107       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1108         auto I = ValueMapping.find(Inst);
1109         if (I != ValueMapping.end())
1110           New->setOperand(i, I->second);
1111       }
1112 
1113     // Remap debug variable operands.
1114     remapDebugVariable(ValueMapping, New);
1115   }
1116 
1117   return NewBB;
1118 }
1119 
1120 void llvm::cloneNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1121                               DenseMap<MDNode *, MDNode *> &ClonedScopes,
1122                               StringRef Ext, LLVMContext &Context) {
1123   MDBuilder MDB(Context);
1124 
1125   for (auto *ScopeList : NoAliasDeclScopes) {
1126     for (const auto &MDOperand : ScopeList->operands()) {
1127       if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {
1128         AliasScopeNode SNANode(MD);
1129 
1130         std::string Name;
1131         auto ScopeName = SNANode.getName();
1132         if (!ScopeName.empty())
1133           Name = (Twine(ScopeName) + ":" + Ext).str();
1134         else
1135           Name = std::string(Ext);
1136 
1137         MDNode *NewScope = MDB.createAnonymousAliasScope(
1138             const_cast<MDNode *>(SNANode.getDomain()), Name);
1139         ClonedScopes.insert(std::make_pair(MD, NewScope));
1140       }
1141     }
1142   }
1143 }
1144 
1145 void llvm::adaptNoAliasScopes(Instruction *I,
1146                               const DenseMap<MDNode *, MDNode *> &ClonedScopes,
1147                               LLVMContext &Context) {
1148   auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1149     bool NeedsReplacement = false;
1150     SmallVector<Metadata *, 8> NewScopeList;
1151     for (const auto &MDOp : ScopeList->operands()) {
1152       if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1153         if (auto *NewMD = ClonedScopes.lookup(MD)) {
1154           NewScopeList.push_back(NewMD);
1155           NeedsReplacement = true;
1156           continue;
1157         }
1158         NewScopeList.push_back(MD);
1159       }
1160     }
1161     if (NeedsReplacement)
1162       return MDNode::get(Context, NewScopeList);
1163     return nullptr;
1164   };
1165 
1166   if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1167     if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
1168       Decl->setScopeList(NewScopeList);
1169 
1170   auto replaceWhenNeeded = [&](unsigned MD_ID) {
1171     if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1172       if (auto *NewScopeList = CloneScopeList(CSNoAlias))
1173         I->setMetadata(MD_ID, NewScopeList);
1174   };
1175   replaceWhenNeeded(LLVMContext::MD_noalias);
1176   replaceWhenNeeded(LLVMContext::MD_alias_scope);
1177 }
1178 
1179 void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1180                                       ArrayRef<BasicBlock *> NewBlocks,
1181                                       LLVMContext &Context, StringRef Ext) {
1182   if (NoAliasDeclScopes.empty())
1183     return;
1184 
1185   DenseMap<MDNode *, MDNode *> ClonedScopes;
1186   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1187                     << NoAliasDeclScopes.size() << " node(s)\n");
1188 
1189   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1190   // Identify instructions using metadata that needs adaptation
1191   for (BasicBlock *NewBlock : NewBlocks)
1192     for (Instruction &I : *NewBlock)
1193       adaptNoAliasScopes(&I, ClonedScopes, Context);
1194 }
1195 
1196 void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
1197                                       Instruction *IStart, Instruction *IEnd,
1198                                       LLVMContext &Context, StringRef Ext) {
1199   if (NoAliasDeclScopes.empty())
1200     return;
1201 
1202   DenseMap<MDNode *, MDNode *> ClonedScopes;
1203   LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1204                     << NoAliasDeclScopes.size() << " node(s)\n");
1205 
1206   cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1207   // Identify instructions using metadata that needs adaptation
1208   assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1209   auto ItStart = IStart->getIterator();
1210   auto ItEnd = IEnd->getIterator();
1211   ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1212   for (auto &I : llvm::make_range(ItStart, ItEnd))
1213     adaptNoAliasScopes(&I, ClonedScopes, Context);
1214 }
1215 
1216 void llvm::identifyNoAliasScopesToClone(
1217     ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1218   for (BasicBlock *BB : BBs)
1219     for (Instruction &I : *BB)
1220       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1221         NoAliasDeclScopes.push_back(Decl->getScopeList());
1222 }
1223 
1224 void llvm::identifyNoAliasScopesToClone(
1225     BasicBlock::iterator Start, BasicBlock::iterator End,
1226     SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1227   for (Instruction &I : make_range(Start, End))
1228     if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1229       NoAliasDeclScopes.push_back(Decl->getScopeList());
1230 }
1231