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