Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/CloneFunction.cpp
35271 views
//===- CloneFunction.cpp - Clone a function into another function ---------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the CloneFunctionInto interface, which is used as the9// low-level function cloner. This is used by the CloneFunction and function10// inliner to do the dirty work of copying the body of a function around.11//12//===----------------------------------------------------------------------===//1314#include "llvm/ADT/SetVector.h"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/Instructions.h"27#include "llvm/IR/IntrinsicInst.h"28#include "llvm/IR/LLVMContext.h"29#include "llvm/IR/MDBuilder.h"30#include "llvm/IR/Metadata.h"31#include "llvm/IR/Module.h"32#include "llvm/Transforms/Utils/BasicBlockUtils.h"33#include "llvm/Transforms/Utils/Cloning.h"34#include "llvm/Transforms/Utils/Local.h"35#include "llvm/Transforms/Utils/ValueMapper.h"36#include <map>37#include <optional>38using namespace llvm;3940#define DEBUG_TYPE "clone-function"4142/// See comments in Cloning.h.43BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,44const Twine &NameSuffix, Function *F,45ClonedCodeInfo *CodeInfo,46DebugInfoFinder *DIFinder) {47BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);48NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;49if (BB->hasName())50NewBB->setName(BB->getName() + NameSuffix);5152bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;53Module *TheModule = F ? F->getParent() : nullptr;5455// Loop over all instructions, and copy them over.56for (const Instruction &I : *BB) {57if (DIFinder && TheModule)58DIFinder->processInstruction(*TheModule, I);5960Instruction *NewInst = I.clone();61if (I.hasName())62NewInst->setName(I.getName() + NameSuffix);6364NewInst->insertBefore(*NewBB, NewBB->end());65NewInst->cloneDebugInfoFrom(&I);6667VMap[&I] = NewInst; // Add instruction map to value.6869if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {70hasCalls = true;71hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);72}73if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {74if (!AI->isStaticAlloca()) {75hasDynamicAllocas = true;76}77}78}7980if (CodeInfo) {81CodeInfo->ContainsCalls |= hasCalls;82CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;83CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;84}85return NewBB;86}8788// Clone OldFunc into NewFunc, transforming the old arguments into references to89// VMap values.90//91void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,92ValueToValueMapTy &VMap,93CloneFunctionChangeType Changes,94SmallVectorImpl<ReturnInst *> &Returns,95const char *NameSuffix, ClonedCodeInfo *CodeInfo,96ValueMapTypeRemapper *TypeMapper,97ValueMaterializer *Materializer) {98NewFunc->setIsNewDbgInfoFormat(OldFunc->IsNewDbgInfoFormat);99assert(NameSuffix && "NameSuffix cannot be null!");100101#ifndef NDEBUG102for (const Argument &I : OldFunc->args())103assert(VMap.count(&I) && "No mapping from source argument specified!");104#endif105106bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;107108// Copy all attributes other than those stored in the AttributeList. We need109// to remap the parameter indices of the AttributeList.110AttributeList NewAttrs = NewFunc->getAttributes();111NewFunc->copyAttributesFrom(OldFunc);112NewFunc->setAttributes(NewAttrs);113114const RemapFlags FuncGlobalRefFlags =115ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;116117// Fix up the personality function that got copied over.118if (OldFunc->hasPersonalityFn())119NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,120FuncGlobalRefFlags, TypeMapper,121Materializer));122123if (OldFunc->hasPrefixData()) {124NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,125FuncGlobalRefFlags, TypeMapper,126Materializer));127}128129if (OldFunc->hasPrologueData()) {130NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,131FuncGlobalRefFlags, TypeMapper,132Materializer));133}134135SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());136AttributeList OldAttrs = OldFunc->getAttributes();137138// Clone any argument attributes that are present in the VMap.139for (const Argument &OldArg : OldFunc->args()) {140if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {141NewArgAttrs[NewArg->getArgNo()] =142OldAttrs.getParamAttrs(OldArg.getArgNo());143}144}145146NewFunc->setAttributes(147AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),148OldAttrs.getRetAttrs(), NewArgAttrs));149150// Everything else beyond this point deals with function instructions,151// so if we are dealing with a function declaration, we're done.152if (OldFunc->isDeclaration())153return;154155// When we remap instructions within the same module, we want to avoid156// duplicating inlined DISubprograms, so record all subprograms we find as we157// duplicate instructions and then freeze them in the MD map. We also record158// information about dbg.value and dbg.declare to avoid duplicating the159// types.160std::optional<DebugInfoFinder> DIFinder;161162// Track the subprogram attachment that needs to be cloned to fine-tune the163// mapping within the same module.164DISubprogram *SPClonedWithinModule = nullptr;165if (Changes < CloneFunctionChangeType::DifferentModule) {166assert((NewFunc->getParent() == nullptr ||167NewFunc->getParent() == OldFunc->getParent()) &&168"Expected NewFunc to have the same parent, or no parent");169170// Need to find subprograms, types, and compile units.171DIFinder.emplace();172173SPClonedWithinModule = OldFunc->getSubprogram();174if (SPClonedWithinModule)175DIFinder->processSubprogram(SPClonedWithinModule);176} else {177assert((NewFunc->getParent() == nullptr ||178NewFunc->getParent() != OldFunc->getParent()) &&179"Expected NewFunc to have different parents, or no parent");180181if (Changes == CloneFunctionChangeType::DifferentModule) {182assert(NewFunc->getParent() &&183"Need parent of new function to maintain debug info invariants");184185// Need to find all the compile units.186DIFinder.emplace();187}188}189190// Loop over all of the basic blocks in the function, cloning them as191// appropriate. Note that we save BE this way in order to handle cloning of192// recursive functions into themselves.193for (const BasicBlock &BB : *OldFunc) {194195// Create a new basic block and copy instructions into it!196BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,197DIFinder ? &*DIFinder : nullptr);198199// Add basic block mapping.200VMap[&BB] = CBB;201202// It is only legal to clone a function if a block address within that203// function is never referenced outside of the function. Given that, we204// want to map block addresses from the old function to block addresses in205// the clone. (This is different from the generic ValueMapper206// implementation, which generates an invalid blockaddress when207// cloning a function.)208if (BB.hasAddressTaken()) {209Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),210const_cast<BasicBlock *>(&BB));211VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);212}213214// Note return instructions for the caller.215if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))216Returns.push_back(RI);217}218219if (Changes < CloneFunctionChangeType::DifferentModule &&220DIFinder->subprogram_count() > 0) {221// Turn on module-level changes, since we need to clone (some of) the222// debug info metadata.223//224// FIXME: Metadata effectively owned by a function should be made225// local, and only that local metadata should be cloned.226ModuleLevelChanges = true;227228auto mapToSelfIfNew = [&VMap](MDNode *N) {229// Avoid clobbering an existing mapping.230(void)VMap.MD().try_emplace(N, N);231};232233// Avoid cloning types, compile units, and (other) subprograms.234SmallPtrSet<const DISubprogram *, 16> MappedToSelfSPs;235for (DISubprogram *ISP : DIFinder->subprograms()) {236if (ISP != SPClonedWithinModule) {237mapToSelfIfNew(ISP);238MappedToSelfSPs.insert(ISP);239}240}241242// If a subprogram isn't going to be cloned skip its lexical blocks as well.243for (DIScope *S : DIFinder->scopes()) {244auto *LScope = dyn_cast<DILocalScope>(S);245if (LScope && MappedToSelfSPs.count(LScope->getSubprogram()))246mapToSelfIfNew(S);247}248249for (DICompileUnit *CU : DIFinder->compile_units())250mapToSelfIfNew(CU);251252for (DIType *Type : DIFinder->types())253mapToSelfIfNew(Type);254} else {255assert(!SPClonedWithinModule &&256"Subprogram should be in DIFinder->subprogram_count()...");257}258259const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;260// Duplicate the metadata that is attached to the cloned function.261// Subprograms/CUs/types that were already mapped to themselves won't be262// duplicated.263SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;264OldFunc->getAllMetadata(MDs);265for (auto MD : MDs) {266NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag,267TypeMapper, Materializer));268}269270// Loop over all of the instructions in the new function, fixing up operand271// references as we go. This uses VMap to do all the hard work.272for (Function::iterator273BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),274BE = NewFunc->end();275BB != BE; ++BB)276// Loop over all instructions, fixing each one as we find it, and any277// attached debug-info records.278for (Instruction &II : *BB) {279RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer);280RemapDbgRecordRange(II.getModule(), II.getDbgRecordRange(), VMap,281RemapFlag, TypeMapper, Materializer);282}283284// Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the285// same module, the compile unit will already be listed (or not). When286// cloning a module, CloneModule() will handle creating the named metadata.287if (Changes != CloneFunctionChangeType::DifferentModule)288return;289290// Update !llvm.dbg.cu with compile units added to the new module if this291// function is being cloned in isolation.292//293// FIXME: This is making global / module-level changes, which doesn't seem294// like the right encapsulation Consider dropping the requirement to update295// !llvm.dbg.cu (either obsoleting the node, or restricting it to296// non-discardable compile units) instead of discovering compile units by297// visiting the metadata attached to global values, which would allow this298// code to be deleted. Alternatively, perhaps give responsibility for this299// update to CloneFunctionInto's callers.300auto *NewModule = NewFunc->getParent();301auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");302// Avoid multiple insertions of the same DICompileUnit to NMD.303SmallPtrSet<const void *, 8> Visited;304for (auto *Operand : NMD->operands())305Visited.insert(Operand);306for (auto *Unit : DIFinder->compile_units()) {307MDNode *MappedUnit =308MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);309if (Visited.insert(MappedUnit).second)310NMD->addOperand(MappedUnit);311}312}313314/// Return a copy of the specified function and add it to that function's315/// module. Also, any references specified in the VMap are changed to refer to316/// their mapped value instead of the original one. If any of the arguments to317/// the function are in the VMap, the arguments are deleted from the resultant318/// function. The VMap is updated to include mappings from all of the319/// instructions and basicblocks in the function from their old to new values.320///321Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,322ClonedCodeInfo *CodeInfo) {323std::vector<Type *> ArgTypes;324325// The user might be deleting arguments to the function by specifying them in326// the VMap. If so, we need to not add the arguments to the arg ty vector327//328for (const Argument &I : F->args())329if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?330ArgTypes.push_back(I.getType());331332// Create a new function type...333FunctionType *FTy =334FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,335F->getFunctionType()->isVarArg());336337// Create the new function...338Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),339F->getName(), F->getParent());340NewF->setIsNewDbgInfoFormat(F->IsNewDbgInfoFormat);341342// Loop over the arguments, copying the names of the mapped arguments over...343Function::arg_iterator DestI = NewF->arg_begin();344for (const Argument &I : F->args())345if (VMap.count(&I) == 0) { // Is this argument preserved?346DestI->setName(I.getName()); // Copy the name over...347VMap[&I] = &*DestI++; // Add mapping to VMap348}349350SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.351CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,352Returns, "", CodeInfo);353354return NewF;355}356357namespace {358/// This is a private class used to implement CloneAndPruneFunctionInto.359struct PruningFunctionCloner {360Function *NewFunc;361const Function *OldFunc;362ValueToValueMapTy &VMap;363bool ModuleLevelChanges;364const char *NameSuffix;365ClonedCodeInfo *CodeInfo;366bool HostFuncIsStrictFP;367368Instruction *cloneInstruction(BasicBlock::const_iterator II);369370public:371PruningFunctionCloner(Function *newFunc, const Function *oldFunc,372ValueToValueMapTy &valueMap, bool moduleLevelChanges,373const char *nameSuffix, ClonedCodeInfo *codeInfo)374: NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),375ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),376CodeInfo(codeInfo) {377HostFuncIsStrictFP =378newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);379}380381/// The specified block is found to be reachable, clone it and382/// anything that it can reach.383void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,384std::vector<const BasicBlock *> &ToClone);385};386} // namespace387388Instruction *389PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {390const Instruction &OldInst = *II;391Instruction *NewInst = nullptr;392if (HostFuncIsStrictFP) {393Intrinsic::ID CIID = getConstrainedIntrinsicID(OldInst);394if (CIID != Intrinsic::not_intrinsic) {395// Instead of cloning the instruction, a call to constrained intrinsic396// should be created.397// Assume the first arguments of constrained intrinsics are the same as398// the operands of original instruction.399400// Determine overloaded types of the intrinsic.401SmallVector<Type *, 2> TParams;402SmallVector<Intrinsic::IITDescriptor, 8> Descriptor;403getIntrinsicInfoTableEntries(CIID, Descriptor);404for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {405Intrinsic::IITDescriptor Operand = Descriptor[I];406switch (Operand.Kind) {407case Intrinsic::IITDescriptor::Argument:408if (Operand.getArgumentKind() !=409Intrinsic::IITDescriptor::AK_MatchType) {410if (I == 0)411TParams.push_back(OldInst.getType());412else413TParams.push_back(OldInst.getOperand(I - 1)->getType());414}415break;416case Intrinsic::IITDescriptor::SameVecWidthArgument:417++I;418break;419default:420break;421}422}423424// Create intrinsic call.425LLVMContext &Ctx = NewFunc->getContext();426Function *IFn =427Intrinsic::getDeclaration(NewFunc->getParent(), CIID, TParams);428SmallVector<Value *, 4> Args;429unsigned NumOperands = OldInst.getNumOperands();430if (isa<CallInst>(OldInst))431--NumOperands;432for (unsigned I = 0; I < NumOperands; ++I) {433Value *Op = OldInst.getOperand(I);434Args.push_back(Op);435}436if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {437FCmpInst::Predicate Pred = CmpI->getPredicate();438StringRef PredName = FCmpInst::getPredicateName(Pred);439Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));440}441442// The last arguments of a constrained intrinsic are metadata that443// represent rounding mode (absents in some intrinsics) and exception444// behavior. The inlined function uses default settings.445if (Intrinsic::hasConstrainedFPRoundingModeOperand(CIID))446Args.push_back(447MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));448Args.push_back(449MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));450451NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");452}453}454if (!NewInst)455NewInst = II->clone();456return NewInst;457}458459/// The specified block is found to be reachable, clone it and460/// anything that it can reach.461void PruningFunctionCloner::CloneBlock(462const BasicBlock *BB, BasicBlock::const_iterator StartingInst,463std::vector<const BasicBlock *> &ToClone) {464WeakTrackingVH &BBEntry = VMap[BB];465466// Have we already cloned this block?467if (BBEntry)468return;469470// Nope, clone it now.471BasicBlock *NewBB;472Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");473BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);474NewBB->IsNewDbgInfoFormat = BB->IsNewDbgInfoFormat;475476// It is only legal to clone a function if a block address within that477// function is never referenced outside of the function. Given that, we478// want to map block addresses from the old function to block addresses in479// the clone. (This is different from the generic ValueMapper480// implementation, which generates an invalid blockaddress when481// cloning a function.)482//483// Note that we don't need to fix the mapping for unreachable blocks;484// the default mapping there is safe.485if (BB->hasAddressTaken()) {486Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),487const_cast<BasicBlock *>(BB));488VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);489}490491bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;492bool hasMemProfMetadata = false;493494// Keep a cursor pointing at the last place we cloned debug-info records from.495BasicBlock::const_iterator DbgCursor = StartingInst;496auto CloneDbgRecordsToHere =497[NewBB, &DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {498if (!NewBB->IsNewDbgInfoFormat)499return;500501// Clone debug-info records onto this instruction. Iterate through any502// source-instructions we've cloned and then subsequently optimised503// away, so that their debug-info doesn't go missing.504for (; DbgCursor != II; ++DbgCursor)505NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);506NewInst->cloneDebugInfoFrom(&*II);507DbgCursor = std::next(II);508};509510// Loop over all instructions, and copy them over, DCE'ing as we go. This511// loop doesn't include the terminator.512for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;513++II) {514515Instruction *NewInst = cloneInstruction(II);516NewInst->insertInto(NewBB, NewBB->end());517518if (HostFuncIsStrictFP) {519// All function calls in the inlined function must get 'strictfp'520// attribute to prevent undesirable optimizations.521if (auto *Call = dyn_cast<CallInst>(NewInst))522Call->addFnAttr(Attribute::StrictFP);523}524525// Eagerly remap operands to the newly cloned instruction, except for PHI526// nodes for which we defer processing until we update the CFG. Also defer527// debug intrinsic processing because they may contain use-before-defs.528if (!isa<PHINode>(NewInst) && !isa<DbgVariableIntrinsic>(NewInst)) {529RemapInstruction(NewInst, VMap,530ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);531532// Eagerly constant fold the newly cloned instruction. If successful, add533// a mapping to the new value. Non-constant operands may be incomplete at534// this stage, thus instruction simplification is performed after535// processing phi-nodes.536if (Value *V = ConstantFoldInstruction(537NewInst, BB->getDataLayout())) {538if (isInstructionTriviallyDead(NewInst)) {539VMap[&*II] = V;540NewInst->eraseFromParent();541continue;542}543}544}545546if (II->hasName())547NewInst->setName(II->getName() + NameSuffix);548VMap[&*II] = NewInst; // Add instruction map to value.549if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {550hasCalls = true;551hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);552}553554CloneDbgRecordsToHere(NewInst, II);555556if (CodeInfo) {557CodeInfo->OrigVMap[&*II] = NewInst;558if (auto *CB = dyn_cast<CallBase>(&*II))559if (CB->hasOperandBundles())560CodeInfo->OperandBundleCallSites.push_back(NewInst);561}562563if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {564if (isa<ConstantInt>(AI->getArraySize()))565hasStaticAllocas = true;566else567hasDynamicAllocas = true;568}569}570571// Finally, clone over the terminator.572const Instruction *OldTI = BB->getTerminator();573bool TerminatorDone = false;574if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {575if (BI->isConditional()) {576// If the condition was a known constant in the callee...577ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());578// Or is a known constant in the caller...579if (!Cond) {580Value *V = VMap.lookup(BI->getCondition());581Cond = dyn_cast_or_null<ConstantInt>(V);582}583584// Constant fold to uncond branch!585if (Cond) {586BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());587VMap[OldTI] = BranchInst::Create(Dest, NewBB);588ToClone.push_back(Dest);589TerminatorDone = true;590}591}592} else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {593// If switching on a value known constant in the caller.594ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());595if (!Cond) { // Or known constant after constant prop in the callee...596Value *V = VMap.lookup(SI->getCondition());597Cond = dyn_cast_or_null<ConstantInt>(V);598}599if (Cond) { // Constant fold to uncond branch!600SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);601BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());602VMap[OldTI] = BranchInst::Create(Dest, NewBB);603ToClone.push_back(Dest);604TerminatorDone = true;605}606}607608if (!TerminatorDone) {609Instruction *NewInst = OldTI->clone();610if (OldTI->hasName())611NewInst->setName(OldTI->getName() + NameSuffix);612NewInst->insertInto(NewBB, NewBB->end());613614CloneDbgRecordsToHere(NewInst, OldTI->getIterator());615616VMap[OldTI] = NewInst; // Add instruction map to value.617618if (CodeInfo) {619CodeInfo->OrigVMap[OldTI] = NewInst;620if (auto *CB = dyn_cast<CallBase>(OldTI))621if (CB->hasOperandBundles())622CodeInfo->OperandBundleCallSites.push_back(NewInst);623}624625// Recursively clone any reachable successor blocks.626append_range(ToClone, successors(BB->getTerminator()));627} else {628// If we didn't create a new terminator, clone DbgVariableRecords from the629// old terminator onto the new terminator.630Instruction *NewInst = NewBB->getTerminator();631assert(NewInst);632633CloneDbgRecordsToHere(NewInst, OldTI->getIterator());634}635636if (CodeInfo) {637CodeInfo->ContainsCalls |= hasCalls;638CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;639CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;640CodeInfo->ContainsDynamicAllocas |=641hasStaticAllocas && BB != &BB->getParent()->front();642}643}644645/// This works like CloneAndPruneFunctionInto, except that it does not clone the646/// entire function. Instead it starts at an instruction provided by the caller647/// and copies (and prunes) only the code reachable from that instruction.648void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,649const Instruction *StartingInst,650ValueToValueMapTy &VMap,651bool ModuleLevelChanges,652SmallVectorImpl<ReturnInst *> &Returns,653const char *NameSuffix,654ClonedCodeInfo *CodeInfo) {655assert(NameSuffix && "NameSuffix cannot be null!");656657ValueMapTypeRemapper *TypeMapper = nullptr;658ValueMaterializer *Materializer = nullptr;659660#ifndef NDEBUG661// If the cloning starts at the beginning of the function, verify that662// the function arguments are mapped.663if (!StartingInst)664for (const Argument &II : OldFunc->args())665assert(VMap.count(&II) && "No mapping from source argument specified!");666#endif667668PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,669NameSuffix, CodeInfo);670const BasicBlock *StartingBB;671if (StartingInst)672StartingBB = StartingInst->getParent();673else {674StartingBB = &OldFunc->getEntryBlock();675StartingInst = &StartingBB->front();676}677678// Collect debug intrinsics for remapping later.679SmallVector<const DbgVariableIntrinsic *, 8> DbgIntrinsics;680for (const auto &BB : *OldFunc) {681for (const auto &I : BB) {682if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))683DbgIntrinsics.push_back(DVI);684}685}686687// Clone the entry block, and anything recursively reachable from it.688std::vector<const BasicBlock *> CloneWorklist;689PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);690while (!CloneWorklist.empty()) {691const BasicBlock *BB = CloneWorklist.back();692CloneWorklist.pop_back();693PFC.CloneBlock(BB, BB->begin(), CloneWorklist);694}695696// Loop over all of the basic blocks in the old function. If the block was697// reachable, we have cloned it and the old block is now in the value map:698// insert it into the new function in the right order. If not, ignore it.699//700// Defer PHI resolution until rest of function is resolved.701SmallVector<const PHINode *, 16> PHIToResolve;702for (const BasicBlock &BI : *OldFunc) {703Value *V = VMap.lookup(&BI);704BasicBlock *NewBB = cast_or_null<BasicBlock>(V);705if (!NewBB)706continue; // Dead block.707708// Move the new block to preserve the order in the original function.709NewBB->moveBefore(NewFunc->end());710711// Handle PHI nodes specially, as we have to remove references to dead712// blocks.713for (const PHINode &PN : BI.phis()) {714// PHI nodes may have been remapped to non-PHI nodes by the caller or715// during the cloning process.716if (isa<PHINode>(VMap[&PN]))717PHIToResolve.push_back(&PN);718else719break;720}721722// Finally, remap the terminator instructions, as those can't be remapped723// until all BBs are mapped.724RemapInstruction(NewBB->getTerminator(), VMap,725ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,726TypeMapper, Materializer);727}728729// Defer PHI resolution until rest of function is resolved, PHI resolution730// requires the CFG to be up-to-date.731for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {732const PHINode *OPN = PHIToResolve[phino];733unsigned NumPreds = OPN->getNumIncomingValues();734const BasicBlock *OldBB = OPN->getParent();735BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);736737// Map operands for blocks that are live and remove operands for blocks738// that are dead.739for (; phino != PHIToResolve.size() &&740PHIToResolve[phino]->getParent() == OldBB;741++phino) {742OPN = PHIToResolve[phino];743PHINode *PN = cast<PHINode>(VMap[OPN]);744for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {745Value *V = VMap.lookup(PN->getIncomingBlock(pred));746if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {747Value *InVal =748MapValue(PN->getIncomingValue(pred), VMap,749ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);750assert(InVal && "Unknown input value?");751PN->setIncomingValue(pred, InVal);752PN->setIncomingBlock(pred, MappedBlock);753} else {754PN->removeIncomingValue(pred, false);755--pred; // Revisit the next entry.756--e;757}758}759}760761// The loop above has removed PHI entries for those blocks that are dead762// and has updated others. However, if a block is live (i.e. copied over)763// but its terminator has been changed to not go to this block, then our764// phi nodes will have invalid entries. Update the PHI nodes in this765// case.766PHINode *PN = cast<PHINode>(NewBB->begin());767NumPreds = pred_size(NewBB);768if (NumPreds != PN->getNumIncomingValues()) {769assert(NumPreds < PN->getNumIncomingValues());770// Count how many times each predecessor comes to this block.771std::map<BasicBlock *, unsigned> PredCount;772for (BasicBlock *Pred : predecessors(NewBB))773--PredCount[Pred];774775// Figure out how many entries to remove from each PHI.776for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)777++PredCount[PN->getIncomingBlock(i)];778779// At this point, the excess predecessor entries are positive in the780// map. Loop over all of the PHIs and remove excess predecessor781// entries.782BasicBlock::iterator I = NewBB->begin();783for (; (PN = dyn_cast<PHINode>(I)); ++I) {784for (const auto &PCI : PredCount) {785BasicBlock *Pred = PCI.first;786for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)787PN->removeIncomingValue(Pred, false);788}789}790}791792// If the loops above have made these phi nodes have 0 or 1 operand,793// replace them with poison or the input value. We must do this for794// correctness, because 0-operand phis are not valid.795PN = cast<PHINode>(NewBB->begin());796if (PN->getNumIncomingValues() == 0) {797BasicBlock::iterator I = NewBB->begin();798BasicBlock::const_iterator OldI = OldBB->begin();799while ((PN = dyn_cast<PHINode>(I++))) {800Value *NV = PoisonValue::get(PN->getType());801PN->replaceAllUsesWith(NV);802assert(VMap[&*OldI] == PN && "VMap mismatch");803VMap[&*OldI] = NV;804PN->eraseFromParent();805++OldI;806}807}808}809810// Drop all incompatible return attributes that cannot be applied to NewFunc811// during cloning, so as to allow instruction simplification to reason on the812// old state of the function. The original attributes are restored later.813AttributeMask IncompatibleAttrs =814AttributeFuncs::typeIncompatible(OldFunc->getReturnType());815AttributeList Attrs = NewFunc->getAttributes();816NewFunc->removeRetAttrs(IncompatibleAttrs);817818// As phi-nodes have been now remapped, allow incremental simplification of819// newly-cloned instructions.820const DataLayout &DL = NewFunc->getDataLayout();821for (const auto &BB : *OldFunc) {822for (const auto &I : BB) {823auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));824if (!NewI)825continue;826827if (Value *V = simplifyInstruction(NewI, DL)) {828NewI->replaceAllUsesWith(V);829830if (isInstructionTriviallyDead(NewI)) {831NewI->eraseFromParent();832} else {833// Did not erase it? Restore the new instruction into VMap previously834// dropped by `ValueIsRAUWd`.835VMap[&I] = NewI;836}837}838}839}840841// Restore attributes.842NewFunc->setAttributes(Attrs);843844// Remap debug intrinsic operands now that all values have been mapped.845// Doing this now (late) preserves use-before-defs in debug intrinsics. If846// we didn't do this, ValueAsMetadata(use-before-def) operands would be847// replaced by empty metadata. This would signal later cleanup passes to848// remove the debug intrinsics, potentially causing incorrect locations.849for (const auto *DVI : DbgIntrinsics) {850if (DbgVariableIntrinsic *NewDVI =851cast_or_null<DbgVariableIntrinsic>(VMap.lookup(DVI)))852RemapInstruction(NewDVI, VMap,853ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,854TypeMapper, Materializer);855}856857// Do the same for DbgVariableRecords, touching all the instructions in the858// cloned range of blocks.859Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();860for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {861for (Instruction &I : BB) {862RemapDbgRecordRange(I.getModule(), I.getDbgRecordRange(), VMap,863ModuleLevelChanges ? RF_None864: RF_NoModuleLevelChanges,865TypeMapper, Materializer);866}867}868869// Simplify conditional branches and switches with a constant operand. We try870// to prune these out when cloning, but if the simplification required871// looking through PHI nodes, those are only available after forming the full872// basic block. That may leave some here, and we still want to prune the dead873// code as early as possible.874for (BasicBlock &BB : make_range(Begin, NewFunc->end()))875ConstantFoldTerminator(&BB);876877// Some blocks may have become unreachable as a result. Find and delete them.878{879SmallPtrSet<BasicBlock *, 16> ReachableBlocks;880SmallVector<BasicBlock *, 16> Worklist;881Worklist.push_back(&*Begin);882while (!Worklist.empty()) {883BasicBlock *BB = Worklist.pop_back_val();884if (ReachableBlocks.insert(BB).second)885append_range(Worklist, successors(BB));886}887888SmallVector<BasicBlock *, 16> UnreachableBlocks;889for (BasicBlock &BB : make_range(Begin, NewFunc->end()))890if (!ReachableBlocks.contains(&BB))891UnreachableBlocks.push_back(&BB);892DeleteDeadBlocks(UnreachableBlocks);893}894895// Now that the inlined function body has been fully constructed, go through896// and zap unconditional fall-through branches. This happens all the time when897// specializing code: code specialization turns conditional branches into898// uncond branches, and this code folds them.899Function::iterator I = Begin;900while (I != NewFunc->end()) {901BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());902if (!BI || BI->isConditional()) {903++I;904continue;905}906907BasicBlock *Dest = BI->getSuccessor(0);908if (!Dest->getSinglePredecessor()) {909++I;910continue;911}912913// We shouldn't be able to get single-entry PHI nodes here, as instsimplify914// above should have zapped all of them..915assert(!isa<PHINode>(Dest->begin()));916917// We know all single-entry PHI nodes in the inlined function have been918// removed, so we just need to splice the blocks.919BI->eraseFromParent();920921// Make all PHI nodes that referred to Dest now refer to I as their source.922Dest->replaceAllUsesWith(&*I);923924// Move all the instructions in the succ to the pred.925I->splice(I->end(), Dest);926927// Remove the dest block.928Dest->eraseFromParent();929930// Do not increment I, iteratively merge all things this block branches to.931}932933// Make a final pass over the basic blocks from the old function to gather934// any return instructions which survived folding. We have to do this here935// because we can iteratively remove and merge returns above.936for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),937E = NewFunc->end();938I != E; ++I)939if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))940Returns.push_back(RI);941}942943/// This works exactly like CloneFunctionInto,944/// except that it does some simple constant prop and DCE on the fly. The945/// effect of this is to copy significantly less code in cases where (for946/// example) a function call with constant arguments is inlined, and those947/// constant arguments cause a significant amount of code in the callee to be948/// dead. Since this doesn't produce an exact copy of the input, it can't be949/// used for things like CloneFunction or CloneModule.950void llvm::CloneAndPruneFunctionInto(951Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,952bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,953const char *NameSuffix, ClonedCodeInfo *CodeInfo) {954CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,955ModuleLevelChanges, Returns, NameSuffix, CodeInfo);956}957958/// Remaps instructions in \p Blocks using the mapping in \p VMap.959void llvm::remapInstructionsInBlocks(ArrayRef<BasicBlock *> Blocks,960ValueToValueMapTy &VMap) {961// Rewrite the code to refer to itself.962for (auto *BB : Blocks) {963for (auto &Inst : *BB) {964RemapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange(), VMap,965RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);966RemapInstruction(&Inst, VMap,967RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);968}969}970}971972/// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p973/// Blocks.974///975/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block976/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.977Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,978Loop *OrigLoop, ValueToValueMapTy &VMap,979const Twine &NameSuffix, LoopInfo *LI,980DominatorTree *DT,981SmallVectorImpl<BasicBlock *> &Blocks) {982Function *F = OrigLoop->getHeader()->getParent();983Loop *ParentLoop = OrigLoop->getParentLoop();984DenseMap<Loop *, Loop *> LMap;985986Loop *NewLoop = LI->AllocateLoop();987LMap[OrigLoop] = NewLoop;988if (ParentLoop)989ParentLoop->addChildLoop(NewLoop);990else991LI->addTopLevelLoop(NewLoop);992993BasicBlock *OrigPH = OrigLoop->getLoopPreheader();994assert(OrigPH && "No preheader");995BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);996// To rename the loop PHIs.997VMap[OrigPH] = NewPH;998Blocks.push_back(NewPH);9991000// Update LoopInfo.1001if (ParentLoop)1002ParentLoop->addBasicBlockToLoop(NewPH, *LI);10031004// Update DominatorTree.1005DT->addNewBlock(NewPH, LoopDomBB);10061007for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {1008Loop *&NewLoop = LMap[CurLoop];1009if (!NewLoop) {1010NewLoop = LI->AllocateLoop();10111012// Establish the parent/child relationship.1013Loop *OrigParent = CurLoop->getParentLoop();1014assert(OrigParent && "Could not find the original parent loop");1015Loop *NewParentLoop = LMap[OrigParent];1016assert(NewParentLoop && "Could not find the new parent loop");10171018NewParentLoop->addChildLoop(NewLoop);1019}1020}10211022for (BasicBlock *BB : OrigLoop->getBlocks()) {1023Loop *CurLoop = LI->getLoopFor(BB);1024Loop *&NewLoop = LMap[CurLoop];1025assert(NewLoop && "Expecting new loop to be allocated");10261027BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);1028VMap[BB] = NewBB;10291030// Update LoopInfo.1031NewLoop->addBasicBlockToLoop(NewBB, *LI);10321033// Add DominatorTree node. After seeing all blocks, update to correct1034// IDom.1035DT->addNewBlock(NewBB, NewPH);10361037Blocks.push_back(NewBB);1038}10391040for (BasicBlock *BB : OrigLoop->getBlocks()) {1041// Update loop headers.1042Loop *CurLoop = LI->getLoopFor(BB);1043if (BB == CurLoop->getHeader())1044LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));10451046// Update DominatorTree.1047BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();1048DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),1049cast<BasicBlock>(VMap[IDomBB]));1050}10511052// Move them physically from the end of the block list.1053F->splice(Before->getIterator(), F, NewPH->getIterator());1054F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),1055F->end());10561057return NewLoop;1058}10591060/// Duplicate non-Phi instructions from the beginning of block up to1061/// StopAt instruction into a split block between BB and its predecessor.1062BasicBlock *llvm::DuplicateInstructionsInSplitBetween(1063BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,1064ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {10651066assert(count(successors(PredBB), BB) == 1 &&1067"There must be a single edge between PredBB and BB!");1068// We are going to have to map operands from the original BB block to the new1069// copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to1070// account for entry from PredBB.1071BasicBlock::iterator BI = BB->begin();1072for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)1073ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);10741075BasicBlock *NewBB = SplitEdge(PredBB, BB);1076NewBB->setName(PredBB->getName() + ".split");1077Instruction *NewTerm = NewBB->getTerminator();10781079// FIXME: SplitEdge does not yet take a DTU, so we include the split edge1080// in the update set here.1081DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},1082{DominatorTree::Insert, PredBB, NewBB},1083{DominatorTree::Insert, NewBB, BB}});10841085// Clone the non-phi instructions of BB into NewBB, keeping track of the1086// mapping and using it to remap operands in the cloned instructions.1087// Stop once we see the terminator too. This covers the case where BB's1088// terminator gets replaced and StopAt == BB's terminator.1089for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {1090Instruction *New = BI->clone();1091New->setName(BI->getName());1092New->insertBefore(NewTerm);1093New->cloneDebugInfoFrom(&*BI);1094ValueMapping[&*BI] = New;10951096// Remap operands to patch up intra-block references.1097for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)1098if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {1099auto I = ValueMapping.find(Inst);1100if (I != ValueMapping.end())1101New->setOperand(i, I->second);1102}11031104// Remap debug variable operands.1105remapDebugVariable(ValueMapping, New);1106}11071108return NewBB;1109}11101111void llvm::cloneNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,1112DenseMap<MDNode *, MDNode *> &ClonedScopes,1113StringRef Ext, LLVMContext &Context) {1114MDBuilder MDB(Context);11151116for (auto *ScopeList : NoAliasDeclScopes) {1117for (const auto &MDOperand : ScopeList->operands()) {1118if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {1119AliasScopeNode SNANode(MD);11201121std::string Name;1122auto ScopeName = SNANode.getName();1123if (!ScopeName.empty())1124Name = (Twine(ScopeName) + ":" + Ext).str();1125else1126Name = std::string(Ext);11271128MDNode *NewScope = MDB.createAnonymousAliasScope(1129const_cast<MDNode *>(SNANode.getDomain()), Name);1130ClonedScopes.insert(std::make_pair(MD, NewScope));1131}1132}1133}1134}11351136void llvm::adaptNoAliasScopes(Instruction *I,1137const DenseMap<MDNode *, MDNode *> &ClonedScopes,1138LLVMContext &Context) {1139auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {1140bool NeedsReplacement = false;1141SmallVector<Metadata *, 8> NewScopeList;1142for (const auto &MDOp : ScopeList->operands()) {1143if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {1144if (auto *NewMD = ClonedScopes.lookup(MD)) {1145NewScopeList.push_back(NewMD);1146NeedsReplacement = true;1147continue;1148}1149NewScopeList.push_back(MD);1150}1151}1152if (NeedsReplacement)1153return MDNode::get(Context, NewScopeList);1154return nullptr;1155};11561157if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))1158if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))1159Decl->setScopeList(NewScopeList);11601161auto replaceWhenNeeded = [&](unsigned MD_ID) {1162if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))1163if (auto *NewScopeList = CloneScopeList(CSNoAlias))1164I->setMetadata(MD_ID, NewScopeList);1165};1166replaceWhenNeeded(LLVMContext::MD_noalias);1167replaceWhenNeeded(LLVMContext::MD_alias_scope);1168}11691170void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,1171ArrayRef<BasicBlock *> NewBlocks,1172LLVMContext &Context, StringRef Ext) {1173if (NoAliasDeclScopes.empty())1174return;11751176DenseMap<MDNode *, MDNode *> ClonedScopes;1177LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "1178<< NoAliasDeclScopes.size() << " node(s)\n");11791180cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);1181// Identify instructions using metadata that needs adaptation1182for (BasicBlock *NewBlock : NewBlocks)1183for (Instruction &I : *NewBlock)1184adaptNoAliasScopes(&I, ClonedScopes, Context);1185}11861187void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,1188Instruction *IStart, Instruction *IEnd,1189LLVMContext &Context, StringRef Ext) {1190if (NoAliasDeclScopes.empty())1191return;11921193DenseMap<MDNode *, MDNode *> ClonedScopes;1194LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "1195<< NoAliasDeclScopes.size() << " node(s)\n");11961197cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);1198// Identify instructions using metadata that needs adaptation1199assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");1200auto ItStart = IStart->getIterator();1201auto ItEnd = IEnd->getIterator();1202++ItEnd; // IEnd is included, increment ItEnd to get the end of the range1203for (auto &I : llvm::make_range(ItStart, ItEnd))1204adaptNoAliasScopes(&I, ClonedScopes, Context);1205}12061207void llvm::identifyNoAliasScopesToClone(1208ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {1209for (BasicBlock *BB : BBs)1210for (Instruction &I : *BB)1211if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))1212NoAliasDeclScopes.push_back(Decl->getScopeList());1213}12141215void llvm::identifyNoAliasScopesToClone(1216BasicBlock::iterator Start, BasicBlock::iterator End,1217SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {1218for (Instruction &I : make_range(Start, End))1219if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))1220NoAliasDeclScopes.push_back(Decl->getScopeList());1221}122212231224