1//===- CloneFunction.cpp - Clone a function into another function ---------===// 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 7//===----------------------------------------------------------------------===// 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. 13//===----------------------------------------------------------------------===// 41#define DEBUG_TYPE "clone-function" 43/// See comments in Cloning.h. 52bool hasCalls =
false, hasDynamicAllocas =
false, hasMemProfMetadata =
false;
54// Loop over all instructions, and copy them over. 58 NewInst->
setName(
I.getName() + NameSuffix);
63 VMap[&
I] = NewInst;
// Add instruction map to value. 65if (isa<CallInst>(
I) && !
I.isDebugOrPseudoInst()) {
67 hasMemProfMetadata |=
I.hasMetadata(LLVMContext::MD_memprof);
68 hasMemProfMetadata |=
I.hasMetadata(LLVMContext::MD_callsite);
70if (
constAllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
71if (!AI->isStaticAlloca()) {
72 hasDynamicAllocas =
true;
88bool ModuleLevelChanges,
91// Copy all attributes other than those stored in Function's AttributeList 92// which holds e.g. parameters and return value attributes. 100// Fix up the personality function that got copied over. 103 FuncGlobalRefFlags, TypeMapper,
108 FuncGlobalRefFlags, TypeMapper,
114 FuncGlobalRefFlags, TypeMapper,
121// Clone any argument attributes that are present in the VMap. 123if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
124// Remap the parameter indices. 125 NewArgAttrs[NewArg->getArgNo()] =
139if (Changes < CloneFunctionChangeType::DifferentModule) {
140 SPClonedWithinModule =
F.getSubprogram();
142if (SPClonedWithinModule)
146if (Changes != CloneFunctionChangeType::ClonedModule && M) {
147// Inspect instructions to process e.g. DILexicalBlocks of inlined functions 152return SPClonedWithinModule;
161if (Changes < CloneFunctionChangeType::DifferentModule &&
163// Avoid cloning types, compile units, and (other) subprograms. 165if (ISP != SPClonedWithinModule)
169// If a subprogram isn't going to be cloned skip its lexical blocks as well. 171auto *LScope = dyn_cast<DILocalScope>(S);
172if (LScope && LScope->getSubprogram() != SPClonedWithinModule)
182assert(!SPClonedWithinModule &&
183"Subprogram should be in DIFinder->subprogram_count()...");
199 *
MapMetadata(MD.second, VMap, RemapFlag, TypeMapper,
200 Materializer, IdentityMD));
207constchar *NameSuffix,
215// Loop over all of the basic blocks in the function, cloning them as 216// appropriate. Note that we save BE this way in order to handle cloning of 217// recursive functions into themselves. 220// Create a new basic block and copy instructions into it! 224// Add basic block mapping. 227// It is only legal to clone a function if a block address within that 228// function is never referenced outside of the function. Given that, we 229// want to map block addresses from the old function to block addresses in 230// the clone. (This is different from the generic ValueMapper 231// implementation, which generates an invalid blockaddress when 232// cloning a function.) 233if (BB.hasAddressTaken()) {
239// Note return instructions for the caller. 244// Loop over all of the instructions in the new function, fixing up operand 245// references as we go. This uses VMap to do all the hard work. 247 BB = cast<BasicBlock>(VMap[&OldFunc.
front()])->getIterator(),
250// Loop over all instructions, fixing each one as we find it, and any 251// attached debug-info records. 256 RemapFlag, TypeMapper, Materializer, IdentityMD);
260// Clone OldFunc into NewFunc, transforming the old arguments into references to 270assert(NameSuffix &&
"NameSuffix cannot be null!");
274assert(VMap.
count(&
I) &&
"No mapping from source argument specified!");
277bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
280 TypeMapper, Materializer);
282// Everything else beyond this point deals with function instructions, 283// so if we are dealing with a function declaration, we're done. 287// When we remap instructions within the same module, we want to avoid 288// duplicating inlined DISubprograms, so record all subprograms we find as we 289// duplicate instructions and then freeze them in the MD map. We also record 290// information about dbg.value and dbg.declare to avoid duplicating the 294// Track the subprogram attachment that needs to be cloned to fine-tune the 295// mapping within the same module. 296if (Changes < CloneFunctionChangeType::DifferentModule) {
297// Need to find subprograms, types, and compile units. 301"Expected NewFunc to have the same parent, or no parent");
303// Need to find all the compile units. 307"Expected NewFunc to have different parents, or no parent");
309if (Changes == CloneFunctionChangeType::DifferentModule) {
311"Need parent of new function to maintain debug info invariants");
321// Cloning is always a Module level operation, since Metadata needs to be 326 Materializer, &IdentityMD);
329 NameSuffix, CodeInfo, TypeMapper, Materializer,
332// Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the 333// same module, the compile unit will already be listed (or not). When 334// cloning a module, CloneModule() will handle creating the named metadata. 335if (Changes != CloneFunctionChangeType::DifferentModule)
338// Update !llvm.dbg.cu with compile units added to the new module if this 339// function is being cloned in isolation. 341// FIXME: This is making global / module-level changes, which doesn't seem 342// like the right encapsulation Consider dropping the requirement to update 343// !llvm.dbg.cu (either obsoleting the node, or restricting it to 344// non-discardable compile units) instead of discovering compile units by 345// visiting the metadata attached to global values, which would allow this 346// code to be deleted. Alternatively, perhaps give responsibility for this 347// update to CloneFunctionInto's callers. 350// Avoid multiple insertions of the same DICompileUnit to NMD. 352for (
auto *Operand : NMD->operands())
357if (Visited.
insert(MappedUnit).second)
358 NMD->addOperand(MappedUnit);
362/// Return a copy of the specified function and add it to that function's 363/// module. Also, any references specified in the VMap are changed to refer to 364/// their mapped value instead of the original one. If any of the arguments to 365/// the function are in the VMap, the arguments are deleted from the resultant 366/// function. The VMap is updated to include mappings from all of the 367/// instructions and basicblocks in the function from their old to new values. 371 std::vector<Type *> ArgTypes;
373// The user might be deleting arguments to the function by specifying them in 374// the VMap. If so, we need to not add the arguments to the arg ty vector 377if (VMap.
count(&
I) == 0)
// Haven't mapped the argument to anything yet? 378 ArgTypes.push_back(
I.getType());
380// Create a new function type... 382 FunctionType::get(
F->getFunctionType()->getReturnType(), ArgTypes,
383F->getFunctionType()->isVarArg());
385// Create the new function... 387F->getName(),
F->getParent());
390// Loop over the arguments, copying the names of the mapped arguments over... 393if (VMap.
count(&
I) == 0) {
// Is this argument preserved? 394 DestI->
setName(
I.getName());
// Copy the name over... 395 VMap[&
I] = &*DestI++;
// Add mapping to VMap 400 Returns,
"", CodeInfo);
406/// This is a private class used to implement CloneAndPruneFunctionInto. 407structPruningFunctionCloner {
411bool ModuleLevelChanges;
412constchar *NameSuffix;
414bool HostFuncIsStrictFP;
422 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
423 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
429 /// The specified block is found to be reachable, clone it and 430 /// anything that it can reach. 432 std::vector<const BasicBlock *> &ToClone);
440if (HostFuncIsStrictFP) {
443// Instead of cloning the instruction, a call to constrained intrinsic 445// Assume the first arguments of constrained intrinsics are the same as 446// the operands of original instruction. 448// Determine overloaded types of the intrinsic. 452for (
unsignedI = 0, E = Descriptor.
size();
I != E; ++
I) {
454switch (Operand.
Kind) {
457 Intrinsic::IITDescriptor::AK_MatchType) {
472// Create intrinsic call. 478if (isa<CallInst>(OldInst))
480for (
unsignedI = 0;
I < NumOperands; ++
I) {
484if (
constauto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
486StringRef PredName = FCmpInst::getPredicateName(Pred);
490// The last arguments of a constrained intrinsic are metadata that 491// represent rounding mode (absents in some intrinsics) and exception 492// behavior. The inlined function uses default settings. 503 NewInst =
II->clone();
507/// The specified block is found to be reachable, clone it and 508/// anything that it can reach. 509void PruningFunctionCloner::CloneBlock(
511 std::vector<const BasicBlock *> &ToClone) {
514// Have we already cloned this block? 518// Nope, clone it now. 524// It is only legal to clone a function if a block address within that 525// function is never referenced outside of the function. Given that, we 526// want to map block addresses from the old function to block addresses in 527// the clone. (This is different from the generic ValueMapper 528// implementation, which generates an invalid blockaddress when 529// cloning a function.) 531// Note that we don't need to fix the mapping for unreachable blocks; 532// the default mapping there is safe. 539bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
540bool hasMemProfMetadata =
false;
542// Keep a cursor pointing at the last place we cloned debug-info records from. 544auto CloneDbgRecordsToHere =
549// Clone debug-info records onto this instruction. Iterate through any 550// source-instructions we've cloned and then subsequently optimised 551// away, so that their debug-info doesn't go missing. 552for (; DbgCursor !=
II; ++DbgCursor)
553 NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt,
false);
554 NewInst->cloneDebugInfoFrom(&*
II);
555 DbgCursor = std::next(
II);
558// Loop over all instructions, and copy them over, DCE'ing as we go. This 559// loop doesn't include the terminator. 563// Don't clone fake_use as it may suppress many optimizations 564// due to inlining, especially SROA. 565if (
auto *IntrInst = dyn_cast<IntrinsicInst>(
II))
566if (IntrInst->getIntrinsicID() == Intrinsic::fake_use)
572if (HostFuncIsStrictFP) {
573// All function calls in the inlined function must get 'strictfp' 574// attribute to prevent undesirable optimizations. 575if (
auto *Call = dyn_cast<CallInst>(NewInst))
576Call->addFnAttr(Attribute::StrictFP);
579// Eagerly remap operands to the newly cloned instruction, except for PHI 580// nodes for which we defer processing until we update the CFG. Also defer 581// debug intrinsic processing because they may contain use-before-defs. 582if (!isa<PHINode>(NewInst) && !isa<DbgVariableIntrinsic>(NewInst)) {
586// Eagerly constant fold the newly cloned instruction. If successful, add 587// a mapping to the new value. Non-constant operands may be incomplete at 588// this stage, thus instruction simplification is performed after 589// processing phi-nodes. 601 NewInst->
setName(
II->getName() + NameSuffix);
602 VMap[&*
II] = NewInst;
// Add instruction map to value. 603if (isa<CallInst>(
II) && !
II->isDebugOrPseudoInst()) {
605 hasMemProfMetadata |=
II->hasMetadata(LLVMContext::MD_memprof);
606 hasMemProfMetadata |=
II->hasMetadata(LLVMContext::MD_callsite);
609 CloneDbgRecordsToHere(NewInst,
II);
613if (
auto *CB = dyn_cast<CallBase>(&*
II))
614if (CB->hasOperandBundles())
619if (isa<ConstantInt>(AI->getArraySize()))
620 hasStaticAllocas =
true;
622 hasDynamicAllocas =
true;
626// Finally, clone over the terminator. 628bool TerminatorDone =
false;
629if (
constBranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
630if (BI->isConditional()) {
631// If the condition was a known constant in the callee... 633// Or is a known constant in the caller... 636Cond = dyn_cast_or_null<ConstantInt>(V);
639// Constant fold to uncond branch! 643 ToClone.push_back(Dest);
644 TerminatorDone =
true;
647 }
elseif (
constSwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
648// If switching on a value known constant in the caller. 650if (!
Cond) {
// Or known constant after constant prop in the callee... 652Cond = dyn_cast_or_null<ConstantInt>(V);
654if (
Cond) {
// Constant fold to uncond branch! 658 ToClone.push_back(Dest);
659 TerminatorDone =
true;
663if (!TerminatorDone) {
669 CloneDbgRecordsToHere(NewInst, OldTI->
getIterator());
671 VMap[OldTI] = NewInst;
// Add instruction map to value. 674 CodeInfo->
OrigVMap[OldTI] = NewInst;
675if (
auto *CB = dyn_cast<CallBase>(OldTI))
676if (CB->hasOperandBundles())
680// Recursively clone any reachable successor blocks. 683// If we didn't create a new terminator, clone DbgVariableRecords from the 684// old terminator onto the new terminator. 688 CloneDbgRecordsToHere(NewInst, OldTI->
getIterator());
700/// This works like CloneAndPruneFunctionInto, except that it does not clone the 701/// entire function. Instead it starts at an instruction provided by the caller 702/// and copies (and prunes) only the code reachable from that instruction. 706bool ModuleLevelChanges,
708constchar *NameSuffix,
710assert(NameSuffix &&
"NameSuffix cannot be null!");
716// If the cloning starts at the beginning of the function, verify that 717// the function arguments are mapped. 720assert(VMap.
count(&
II) &&
"No mapping from source argument specified!");
723 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
724 NameSuffix, CodeInfo);
730 StartingInst = &StartingBB->
front();
733// Collect debug intrinsics for remapping later. 735for (
constauto &BB : *OldFunc) {
736for (
constauto &
I : BB) {
737if (
constauto *DVI = dyn_cast<DbgVariableIntrinsic>(&
I))
742// Clone the entry block, and anything recursively reachable from it. 743 std::vector<const BasicBlock *> CloneWorklist;
744 PFC.CloneBlock(StartingBB, StartingInst->
getIterator(), CloneWorklist);
745while (!CloneWorklist.empty()) {
747 CloneWorklist.pop_back();
748 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
751// Loop over all of the basic blocks in the old function. If the block was 752// reachable, we have cloned it and the old block is now in the value map: 753// insert it into the new function in the right order. If not, ignore it. 755// Defer PHI resolution until rest of function is resolved. 759BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
761continue;
// Dead block. 763// Move the new block to preserve the order in the original function. 766// Handle PHI nodes specially, as we have to remove references to dead 768for (
constPHINode &PN : BI.phis()) {
769// PHI nodes may have been remapped to non-PHI nodes by the caller or 770// during the cloning process. 771if (isa<PHINode>(VMap[&PN]))
777// Finally, remap the terminator instructions, as those can't be remapped 778// until all BBs are mapped. 781 TypeMapper, Materializer);
784// Defer PHI resolution until rest of function is resolved, PHI resolution 785// requires the CFG to be up-to-date. 786for (
unsigned phino = 0, e = PHIToResolve.
size(); phino != e;) {
787constPHINode *OPN = PHIToResolve[phino];
790BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
792// Map operands for blocks that are live and remove operands for blocks 794for (; phino != PHIToResolve.
size() &&
795 PHIToResolve[phino]->
getParent() == OldBB;
797 OPN = PHIToResolve[phino];
798PHINode *PN = cast<PHINode>(VMap[OPN]);
801if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
805assert(InVal &&
"Unknown input value?");
810 --
pred;
// Revisit the next entry. 816// The loop above has removed PHI entries for those blocks that are dead 817// and has updated others. However, if a block is live (i.e. copied over) 818// but its terminator has been changed to not go to this block, then our 819// phi nodes will have invalid entries. Update the PHI nodes in this 824assert(NumPreds < PN->getNumIncomingValues());
825// Count how many times each predecessor comes to this block. 826 std::map<BasicBlock *, unsigned> PredCount;
830// Figure out how many entries to remove from each PHI. 834// At this point, the excess predecessor entries are positive in the 835// map. Loop over all of the PHIs and remove excess predecessor 838for (; (PN = dyn_cast<PHINode>(
I)); ++
I) {
839for (
constauto &PCI : PredCount) {
841for (
unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
847// If the loops above have made these phi nodes have 0 or 1 operand, 848// replace them with poison or the input value. We must do this for 849// correctness, because 0-operand phis are not valid. 850 PN = cast<PHINode>(NewBB->
begin());
854while ((PN = dyn_cast<PHINode>(
I++))) {
857assert(VMap[&*OldI] == PN &&
"VMap mismatch");
865// Drop all incompatible return attributes that cannot be applied to NewFunc 866// during cloning, so as to allow instruction simplification to reason on the 867// old state of the function. The original attributes are restored later. 873// As phi-nodes have been now remapped, allow incremental simplification of 874// newly-cloned instructions. 876for (
constauto &BB : *OldFunc) {
877for (
constauto &
I : BB) {
878auto *NewI = dyn_cast_or_null<Instruction>(VMap.
lookup(&
I));
883 NewI->replaceAllUsesWith(V);
886 NewI->eraseFromParent();
888// Did not erase it? Restore the new instruction into VMap previously 889// dropped by `ValueIsRAUWd`. 896// Restore attributes. 899// Remap debug intrinsic operands now that all values have been mapped. 900// Doing this now (late) preserves use-before-defs in debug intrinsics. If 901// we didn't do this, ValueAsMetadata(use-before-def) operands would be 902// replaced by empty metadata. This would signal later cleanup passes to 903// remove the debug intrinsics, potentially causing incorrect locations. 904for (
constauto *DVI : DbgIntrinsics) {
906 cast_or_null<DbgVariableIntrinsic>(VMap.
lookup(DVI)))
909 TypeMapper, Materializer);
912// Do the same for DbgVariableRecords, touching all the instructions in the 913// cloned range of blocks. 920 TypeMapper, Materializer);
924// Simplify conditional branches and switches with a constant operand. We try 925// to prune these out when cloning, but if the simplification required 926// looking through PHI nodes, those are only available after forming the full 927// basic block. That may leave some here, and we still want to prune the dead 928// code as early as possible. 932// Some blocks may have become unreachable as a result. Find and delete them. 937while (!Worklist.
empty()) {
939if (ReachableBlocks.
insert(BB).second)
950// Now that the inlined function body has been fully constructed, go through 951// and zap unconditional fall-through branches. This happens all the time when 952// specializing code: code specialization turns conditional branches into 953// uncond branches, and this code folds them. 955while (
I != NewFunc->
end()) {
956BranchInst *BI = dyn_cast<BranchInst>(
I->getTerminator());
968// We shouldn't be able to get single-entry PHI nodes here, as instsimplify 969// above should have zapped all of them.. 972// We know all single-entry PHI nodes in the inlined function have been 973// removed, so we just need to splice the blocks. 976// Make all PHI nodes that referred to Dest now refer to I as their source. 979// Move all the instructions in the succ to the pred. 980I->splice(
I->end(), Dest);
982// Remove the dest block. 985// Do not increment I, iteratively merge all things this block branches to. 988// Make a final pass over the basic blocks from the old function to gather 989// any return instructions which survived folding. We have to do this here 990// because we can iteratively remove and merge returns above. 994if (
ReturnInst *RI = dyn_cast<ReturnInst>(
I->getTerminator()))
998/// This works exactly like CloneFunctionInto, 999/// except that it does some simple constant prop and DCE on the fly. The 1000/// effect of this is to copy significantly less code in cases where (for 1001/// example) a function call with constant arguments is inlined, and those 1002/// constant arguments cause a significant amount of code in the callee to be 1003/// dead. Since this doesn't produce an exact copy of the input, it can't be 1004/// used for things like CloneFunction or CloneModule. 1010 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
1013/// Remaps instructions in \p Blocks using the mapping in \p VMap. 1016// Rewrite the code to refer to itself. 1018for (
auto &Inst : *BB) {
1027/// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p 1030/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block 1031/// \p LoopDomBB. Insert the new blocks before block specified in \p Before. 1042 LMap[OrigLoop] = NewLoop;
1049assert(OrigPH &&
"No preheader");
1051// To rename the loop PHIs. 1052 VMap[OrigPH] = NewPH;
1059// Update DominatorTree. 1063Loop *&NewLoop = LMap[CurLoop];
1067// Establish the parent/child relationship. 1069assert(OrigParent &&
"Could not find the original parent loop");
1070Loop *NewParentLoop = LMap[OrigParent];
1071assert(NewParentLoop &&
"Could not find the new parent loop");
1079Loop *&NewLoop = LMap[CurLoop];
1080assert(NewLoop &&
"Expecting new loop to be allocated");
1088// Add DominatorTree node. After seeing all blocks, update to correct 1096// Update loop headers. 1099 LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1101// Update DominatorTree. 1104 cast<BasicBlock>(VMap[IDomBB]));
1107// Move them physically from the end of the block list. 1115/// Duplicate non-Phi instructions from the beginning of block up to 1116/// StopAt instruction into a split block between BB and its predecessor. 1122"There must be a single edge between PredBB and BB!");
1123// We are going to have to map operands from the original BB block to the new 1124// copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 1125// account for entry from PredBB. 1127for (;
PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1134// FIXME: SplitEdge does not yet take a DTU, so we include the split edge 1135// in the update set here. 1137 {DominatorTree::Insert, PredBB, NewBB},
1138 {DominatorTree::Insert, NewBB, BB}});
1140// Clone the non-phi instructions of BB into NewBB, keeping track of the 1141// mapping and using it to remap operands in the cloned instructions. 1142// Stop once we see the terminator too. This covers the case where BB's 1143// terminator gets replaced and StopAt == BB's terminator. 1144for (; StopAt != &*BI && BB->
getTerminator() != &*BI; ++BI) {
1146 New->setName(BI->getName());
1148 New->cloneDebugInfoFrom(&*BI);
1149 ValueMapping[&*BI] = New;
1151// Remap operands to patch up intra-block references. 1152for (
unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1153if (
Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1154autoI = ValueMapping.
find(Inst);
1155if (
I != ValueMapping.
end())
1156 New->setOperand(i,
I->second);
1159// Remap debug variable operands. 1171for (
auto *ScopeList : NoAliasDeclScopes) {
1172for (
constauto &
MDOperand : ScopeList->operands()) {
1177auto ScopeName = SNANode.
getName();
1178if (!ScopeName.empty())
1179Name = (
Twine(ScopeName) +
":" + Ext).str();
1181Name = std::string(Ext);
1185 ClonedScopes.
insert(std::make_pair(MD, NewScope));
1194auto CloneScopeList = [&](
constMDNode *ScopeList) ->
MDNode * {
1195bool NeedsReplacement =
false;
1197for (
constauto &MDOp : ScopeList->operands()) {
1198if (
MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1199if (
auto *NewMD = ClonedScopes.
lookup(MD)) {
1201 NeedsReplacement =
true;
1207if (NeedsReplacement)
1212if (
auto *Decl = dyn_cast<NoAliasScopeDeclInst>(
I))
1213if (
auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
1214 Decl->setScopeList(NewScopeList);
1216auto replaceWhenNeeded = [&](
unsigned MD_ID) {
1217if (
constMDNode *CSNoAlias =
I->getMetadata(MD_ID))
1218if (
auto *NewScopeList = CloneScopeList(CSNoAlias))
1219I->setMetadata(MD_ID, NewScopeList);
1221 replaceWhenNeeded(LLVMContext::MD_noalias);
1222 replaceWhenNeeded(LLVMContext::MD_alias_scope);
1228if (NoAliasDeclScopes.
empty())
1233 << NoAliasDeclScopes.
size() <<
" node(s)\n");
1236// Identify instructions using metadata that needs adaptation 1245if (NoAliasDeclScopes.
empty())
1250 << NoAliasDeclScopes.
size() <<
" node(s)\n");
1253// Identify instructions using metadata that needs adaptation 1257 ++ItEnd;
// IEnd is included, increment ItEnd to get the end of the range 1266if (
auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&
I))
1267 NoAliasDeclScopes.
push_back(Decl->getScopeList());
1274if (
auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&
I))
1275 NoAliasDeclScopes.
push_back(Decl->getScopeList());
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DenseMap< Block *, BlockRelaxAux > Blocks
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
StringRef getName() const
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if the attribute exists for the function.
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
InstListType::const_iterator const_iterator
const Instruction & front() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool IsNewDbgInfoFormat
Flag recording whether or not this block stores debug-info in the form of intrinsic instructions (fal...
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
const Instruction & back() const
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
This is the shared class of boolean and integer constants.
This is an important base class in LLVM.
Base class for scope-like contexts.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
This is the common base class for debug info intrinsics for variables.
Utility to find all debug info in a module.
void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
unsigned subprogram_count() const
void processSubprogram(DISubprogram *SP)
Process subprogram.
iterator_range< subprogram_iterator > subprograms() const
iterator_range< type_iterator > types() const
iterator_range< scope_iterator > scopes() const
iterator_range< compile_unit_iterator > compile_units() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
DomTreeNodeBase * getIDom() const
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const BasicBlock & getEntryBlock() const
BasicBlockListType::iterator iterator
void setPrefixData(Constant *PrefixData)
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
const BasicBlock & front() const
iterator_range< arg_iterator > args()
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
bool hasPrefixData() const
Check whether this function has prefix data.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Constant * getPrologueData() const
Get the prologue data associated with this function.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setPersonalityFn(Constant *Fn)
AttributeList getAttributes() const
Return the attribute list for this Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
void setIsNewDbgInfoFormat(bool NewVal)
Type * getReturnType() const
Returns the type of the ret val.
Constant * getPrefixData() const
Get the prefix data associated with this function.
bool hasPrologueData() const
Check whether this function has prologue data.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Module * getParent()
Get the module that this global value is contained inside of...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
SmallVector< const LoopT *, 4 > getLoopsInPreorder() const
Return all loops in the loop nest rooted by the loop in preorder, with siblings in forward program or...
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Tracking metadata reference owned by Metadata.
static MDString * get(LLVMContext &Context, StringRef Str)
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
A Module instance is used to store all the information related to an LLVM module.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Return a value (possibly void), from a function.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
A handle to a particular switch case.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const KeyT &Val)
This is a class that can be implemented by clients to materialize Values on demand.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
StringRef getName() const
Return a constant reference to the value's name.
Value handle that is nullable, but tries to track the Value.
const ParentTy * getParent() const
self_iterator getIterator()
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
AttributeMask typeIncompatible(Type *Ty, AttributeSet AS, AttributeSafetyKind ASK=ASK_ALL)
Which attributes cannot be applied to a type.
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "Constrained Floating-Point Intrinsics" that take ...
This is an optimization pass for GlobalISel generic memory operations.
void CloneFunctionAttributesInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc's attributes into NewFunc, transforming values based on the mappings in VMap.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
auto successors(const MachineBasicBlock *BB)
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Lookup or compute a mapping for a piece of metadata.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
auto pred_size(const MachineBasicBlock *BB)
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
RemapFlags
These are flags that the value mapping APIs allow.
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Look up or compute a value in the value map.
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
void cloneNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, DenseMap< MDNode *, MDNode * > &ClonedScopes, StringRef Ext, LLVMContext &Context)
Duplicate the specified list of noalias decl scopes.
Intrinsic::ID getConstrainedIntrinsicID(const Instruction &Instr)
Returns constrained intrinsic id to represent the given instruction in strictfp function.
MetadataSetTy FindDebugInfoToIdentityMap(CloneFunctionChangeType Changes, DebugInfoFinder &DIFinder, DISubprogram *SPClonedWithinModule)
Based on Changes and DIFinder return debug info that needs to be identity mapped during Metadata clon...
void CloneFunctionMetadataInto(Function &NewFunc, const Function &OldFunc, ValueToValueMapTy &VMap, RemapFlags RemapFlag, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Clone OldFunc's metadata into NewFunc.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void adaptNoAliasScopes(llvm::Instruction *I, const DenseMap< MDNode *, MDNode * > &ClonedScopes, LLVMContext &Context)
Adapt the metadata for the specified instruction according to the provided mapping.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
auto predecessors(const MachineBasicBlock *BB)
DISubprogram * CollectDebugInfoForCloning(const Function &F, CloneFunctionChangeType Changes, DebugInfoFinder &DIFinder)
Collect debug information such as types, compile units, and other subprograms that are reachable from...
void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function.
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
void CloneFunctionBodyInto(Function &NewFunc, const Function &OldFunc, ValueToValueMapTy &VMap, RemapFlags RemapFlag, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Clone OldFunc's body into NewFunc.
This struct can be used to capture information about code being cloned, while it is being cloned.
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
bool ContainsMemProfMetadata
This is set to true if there is memprof related metadata (memprof or callsite metadata) in the cloned...
DenseMap< const Value *, const Value * > OrigVMap
Like VMap, but maps only unsimplified instructions.
std::vector< WeakTrackingVH > OperandBundleCallSites
All cloned call sites that have operand bundles attached are appended to this vector.
This is a type descriptor which explains the type requirements of an intrinsic.
enum llvm::Intrinsic::IITDescriptor::IITDescriptorKind Kind
ArgKind getArgumentKind() const