55#ifdef EXPENSIVE_CHECKS
65#define DEBUG_TYPE "attributor"
66#define VERBOSE_DEBUG_TYPE DEBUG_TYPE "-verbose"
69 "Determine what attributes are manifested in the IR");
73 "How many AAs should be initialized");
79STATISTIC(NumFnDeleted,
"Number of function deleted");
81 "Number of functions with exact definitions");
83 "Number of functions without exact definitions");
84STATISTIC(NumFnShallowWrappersCreated,
"Number of shallow wrappers created");
86 "Number of abstract attributes timed out before fixpoint");
88 "Number of abstract attributes in a valid fixpoint state");
90 "Number of abstract attributes manifested in IR");
113enum class NVPTXAMDGPUAddressSpace :
unsigned {
122enum class SPIRVAddressSpace :
unsigned {
135 const Triple &
T = M.getTargetTriple();
138 return AS ==
static_cast<unsigned>(SPIRVAddressSpace::Shared);
140 return AS ==
static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Shared);
145 const Triple &
T = M.getTargetTriple();
148 return AS ==
static_cast<unsigned>(SPIRVAddressSpace::Constant);
150 return AS ==
static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Constant);
155 const Triple &
T = M.getTargetTriple();
158 return AS ==
static_cast<unsigned>(SPIRVAddressSpace::Local);
160 return AS ==
static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Local);
167 if (CB->hasFnAttr(Attribute::NoSync))
171 if (!CB->isConvergent() && !CB->mayReadOrWriteMemory())
180 if (!
I.mayReadOrWriteMemory())
187 const Value &V,
bool ForAnalysisOnly) {
189 if (!ForAnalysisOnly)
206 bool UsedAssumedInformation =
false;
208 if (
A.hasGlobalVariableSimplificationCallback(*GV)) {
209 auto AssumedGV =
A.getAssumedInitializerFromCallBack(
210 *GV, &QueryingAA, UsedAssumedInformation);
211 Initializer = *AssumedGV;
215 if (!GV->hasLocalLinkage()) {
218 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
223 assert(!GV->hasLocalLinkage() || GV->hasInitializer());
226 Initializer = GV->getInitializer();
230 int64_t StorageSize =
DL.getTypeStoreSize(&Ty);
231 if (StorageSize != RangePtr->
Size)
244 return I->getFunction() == Scope;
246 return A->getParent() == Scope;
259 return A->getParent() == Scope;
261 if (
I->getFunction() == Scope) {
265 return DT->dominates(
I, CtxI);
267 if (CtxI &&
I->getParent() == CtxI->
getParent())
270 [&](
const Instruction &AfterI) { return &AfterI == CtxI; });
277 if (V.getType() == &Ty)
284 if (
C->isNullValue() && !Ty.isPtrOrPtrVectorTy())
286 if (
C->getType()->isPointerTy() && Ty.isPointerTy())
288 if (
C->getType()->getPrimitiveSizeInBits() >= Ty.getPrimitiveSizeInBits()) {
289 if (
C->getType()->isIntegerTy() && Ty.isIntegerTy())
291 if (
C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy())
298std::optional<Value *>
300 const std::optional<Value *> &
B,
313 Ty = (*A)->getType();
323template <
bool IsLoad,
typename Ty>
329 LLVM_DEBUG(
dbgs() <<
"Trying to determine the potential copies of " <<
I
330 <<
" (only exact: " << OnlyExact <<
")\n";);
332 Value &Ptr = *
I.getPointerOperand();
348 Ptr.getType()->getPointerAddressSpace()) &&
349 A.getAssumedSimplified(Ptr, QueryingAA, UsedAssumedInformation,
353 dbgs() <<
"Underlying object is a valid nullptr, giving up.\n";);
359 LLVM_DEBUG(
dbgs() <<
"Underlying object is not supported yet: " << Obj
364 if (!GV->hasLocalLinkage() &&
365 !(GV->isConstant() && GV->hasInitializer())) {
367 "linkage, not supported yet: "
372 bool NullOnly =
true;
373 bool NullRequired =
false;
374 auto CheckForNullOnlyAndUndef = [&](std::optional<Value *>
V,
376 if (!
V || *
V ==
nullptr)
381 NullRequired = !IsExact;
390 LLVM_DEBUG(
dbgs() <<
"Underlying object written but stored value "
391 "cannot be converted to read type: "
413 if (
Value *
V = AdjustWrittenValueType(Acc, *
SI->getValueOperand()))
427 CheckForNullOnlyAndUndef(Acc.
getContent(), IsExact);
428 if (OnlyExact && !IsExact && !NullOnly &&
434 if (NullRequired && !NullOnly) {
435 LLVM_DEBUG(
dbgs() <<
"Required all `null` accesses due to non exact "
436 "one, however found non-null one: "
447 if (PotentialValueOrigins)
453 LLVM_DEBUG(
dbgs() <<
"Underlying object written through a non-store "
454 "instruction not supported yet: "
458 Value *
V = AdjustWrittenValueType(Acc, *
SI->getValueOperand());
462 if (PotentialValueOrigins)
467 if (!LI && OnlyExact) {
469 "instruction not supported yet: "
480 bool HasBeenWrittenTo =
false;
485 if (!PI || !PI->forallInterferingAccesses(
488 !IsLoad, CheckAccess,
489 HasBeenWrittenTo,
Range, SkipCB)) {
492 <<
"Failed to verify all interfering accesses for underlying object: "
497 if (IsLoad && !HasBeenWrittenTo && !
Range.isUnassigned()) {
502 LLVM_DEBUG(
dbgs() <<
"Could not determine required initial value of "
503 "underlying object, abort!\n");
506 CheckForNullOnlyAndUndef(InitialValue,
true);
507 if (NullRequired && !NullOnly) {
508 LLVM_DEBUG(
dbgs() <<
"Non exact access but initial value that is not "
509 "null or undef, abort!\n");
513 NewCopies.
insert(InitialValue);
514 if (PotentialValueOrigins)
515 NewCopyOrigins.
insert(
nullptr);
525 if (!AAUO || !AAUO->forallUnderlyingObjects(
Pred)) {
527 dbgs() <<
"Underlying objects stored into could not be determined\n";);
534 for (
const auto *PI : PIs) {
535 if (!PI->getState().isAtFixpoint())
536 UsedAssumedInformation =
true;
540 if (PotentialValueOrigins)
552 A, LI, PotentialValues, &PotentialValueOrigins, QueryingAA,
553 UsedAssumedInformation, OnlyExact);
561 A,
SI, PotentialCopies,
nullptr, QueryingAA, UsedAssumedInformation,
567 bool RequireReadNone,
bool &IsKnown) {
568 if (RequireReadNone) {
580 const auto *MemLocAA =
582 if (MemLocAA && MemLocAA->isAssumedReadNone()) {
583 IsKnown = MemLocAA->isKnownReadNone();
590 const auto *MemBehaviorAA =
593 (MemBehaviorAA->isAssumedReadNone() ||
594 (!RequireReadNone && MemBehaviorAA->isAssumedReadOnly()))) {
595 IsKnown = RequireReadNone ? MemBehaviorAA->isKnownReadNone()
596 : MemBehaviorAA->isKnownReadOnly();
621 std::function<
bool(
const Function &
F)> GoBackwardsCB) {
623 dbgs() <<
"[AA] isPotentiallyReachable @" << ToFn.
getName() <<
" from "
624 << FromI <<
" [GBCB: " <<
bool(GoBackwardsCB) <<
"][#ExS: "
625 << (ExclusionSet ? std::to_string(ExclusionSet->
size()) :
"none")
628 for (
auto *ES : *ExclusionSet)
629 dbgs() << *ES <<
"\n";
637 if (GoBackwardsCB && &ToFn != FromI.
getFunction() &&
638 !GoBackwardsCB(*FromI.
getFunction()) &&
A.getInfoCache().isKernel(ToFn) &&
640 LLVM_DEBUG(
dbgs() <<
"[AA] assume kernel cannot be reached from within the "
641 "module; success\n";);
650 if (!GoBackwardsCB && !ExclusionSet) {
652 <<
" is not checked backwards and does not have an "
653 "exclusion set, abort\n");
661 while (!Worklist.
empty()) {
663 if (!Visited.
insert(CurFromI).second)
667 if (FromFn == &ToFn) {
670 LLVM_DEBUG(
dbgs() <<
"[AA] check " << *ToI <<
" from " << *CurFromI
671 <<
" intraprocedurally\n");
674 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
675 A, *CurFromI, *ToI, ExclusionSet);
677 << (
Result ?
"can potentially " :
"cannot ") <<
"reach "
678 << *ToI <<
" [Intra]\n");
688 Result = !ToReachabilityAA || ToReachabilityAA->isAssumedReachable(
689 A, EntryI, *ToI, ExclusionSet);
691 <<
" " << (
Result ?
"can potentially " :
"cannot ")
692 <<
"reach @" << *ToI <<
" [ToFn]\n");
700 Result = !FnReachabilityAA || FnReachabilityAA->instructionCanReach(
701 A, *CurFromI, ToFn, ExclusionSet);
703 <<
" " << (
Result ?
"can potentially " :
"cannot ")
704 <<
"reach @" << ToFn.
getName() <<
" [FromFn]\n");
713 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
714 A, *CurFromI, Ret, ExclusionSet);
716 << (
Result ?
"can potentially " :
"cannot ") <<
"reach "
717 << Ret <<
" [Intra]\n");
722 bool UsedAssumedInformation =
false;
723 if (
A.checkForAllInstructions(ReturnInstCB, FromFn, &QueryingAA,
724 {Instruction::Ret}, UsedAssumedInformation)) {
729 if (!GoBackwardsCB) {
731 <<
" is not checked backwards, abort\n");
737 if (!GoBackwardsCB(*FromFn))
744 CallBase *CB = ACS.getInstruction();
756 Result = !
A.checkForAllCallSites(CheckCallSite, *FromFn,
758 &QueryingAA, UsedAssumedInformation);
760 LLVM_DEBUG(
dbgs() <<
"[AA] stepping back to call sites from " << *CurFromI
761 <<
" in @" << FromFn->
getName()
762 <<
" failed, give up\n");
766 LLVM_DEBUG(
dbgs() <<
"[AA] stepped back to call sites from " << *CurFromI
767 <<
" in @" << FromFn->
getName()
768 <<
" worklist size is: " << Worklist.
size() <<
"\n");
777 std::function<
bool(
const Function &
F)> GoBackwardsCB) {
779 return ::isPotentiallyReachable(
A, FromI, &ToI, *ToFn, QueryingAA,
780 ExclusionSet, GoBackwardsCB);
787 std::function<
bool(
const Function &
F)> GoBackwardsCB) {
788 return ::isPotentiallyReachable(
A, FromI,
nullptr, ToFn, QueryingAA,
789 ExclusionSet, GoBackwardsCB);
800 dbgs() <<
"[AA] Object '" << Obj
801 <<
"' is thread local; stack objects are thread local.\n");
804 bool IsKnownNoCapture;
809 << (IsAssumedNoCapture ?
"" :
"not") <<
" thread local; "
810 << (IsAssumedNoCapture ?
"non-" :
"")
811 <<
"captured stack object.\n");
812 return IsAssumedNoCapture;
815 if (GV->isConstant()) {
817 <<
"' is thread local; constant global\n");
820 if (GV->isThreadLocal()) {
822 <<
"' is thread local; thread local global\n");
827 if (
A.getInfoCache().IsTargetGPU()) {
829 Obj.getType()->getPointerAddressSpace())) {
831 <<
"' is thread local; GPU local memory\n");
835 A.getInfoCache().getModule(),
836 Obj.getType()->getPointerAddressSpace())) {
838 <<
"' is thread local; GPU constant memory\n");
843 LLVM_DEBUG(
dbgs() <<
"[AA] Object '" << Obj <<
"' is not thread local\n");
849 if (!
I.mayHaveSideEffects() && !
I.mayReadFromMemory())
854 auto AddLocationPtr = [&](std::optional<MemoryLocation>
Loc) {
857 dbgs() <<
"[AA] Access to unknown location; -> requires barriers\n");
880 for (
const Value *Ptr : Ptrs) {
886 auto Pred = [&](
Value &Obj) {
889 LLVM_DEBUG(
dbgs() <<
"[AA] Access to '" << Obj <<
"' via '" << *Ptr
890 <<
"'; -> requires barrier\n");
896 if (!UnderlyingObjsAA || !UnderlyingObjsAA->forallUnderlyingObjects(Pred))
918 if (Existing.
isValid() && (!ForceReplace || Existing == Attr))
924 if (!ForceReplace && Attr.
getKindAsEnum() == Attribute::Memory) {
959 if (!Callee->hasMetadata(LLVMContext::MD_callback)) {
960 if (Callee->arg_size() >
unsigned(ArgNo))
961 return Callee->getArg(ArgNo);
969 std::optional<Argument *> CBCandidateArg;
972 for (
const Use *U : CallbackUses) {
986 "ACS mapped into var-args arguments!");
987 if (CBCandidateArg) {
988 CBCandidateArg =
nullptr;
996 if (CBCandidateArg && *CBCandidateArg)
997 return *CBCandidateArg;
1001 if (Callee->arg_size() >
unsigned(ArgNo))
1002 return Callee->getArg(ArgNo);
1016 LLVM_DEBUG(
dbgs() <<
"[Attributor] Update " << HasChanged <<
" " << *
this
1027 InfoCache(InfoCache),
1028 MaxInitializationChainLength(
1029 Opts.attributor_max_initialization_chain_length),
1030 Configuration(Configuration) {
1034 if (Fn->hasAddressTaken(
nullptr,
1040 InfoCache.IndirectlyCallableFunctions.push_back(Fn);
1047 "Did expect a valid position!");
1067 unsigned AttrsSize = Attrs.size();
1072 for (
const auto &It : A2K) {
1073 if (
Context.contains(It.first))
1076 return AttrsSize != Attrs.size();
1079template <
typename DescTy>
1085 if (AttrDescs.
empty())
1097 auto [Iter, Inserted] = AttrsMap.insert({AttrListAnchor, AL});
1103 AttributeSet AS =
AL.getAttributes(AttrIdx);
1105 AttrBuilder
AB(Ctx);
1108 for (
const DescTy &AttrDesc : AttrDescs)
1109 if (CB(AttrDesc, AS, AM, AB))
1116 AL =
AL.removeAttributesAtIndex(Ctx, AttrIdx, AM);
1117 AL =
AL.addAttributesAtIndex(Ctx, AttrIdx, AB);
1125 bool IgnoreSubsumingPositions,
1127 bool Implied =
false;
1128 bool HasAttr =
false;
1131 if (AttrSet.hasAttribute(Kind)) {
1132 Implied |= Kind != ImpliedAttributeKind;
1138 updateAttrMap<Attribute::AttrKind>(EquivIRP, AttrKinds, HasAttrCB);
1144 if (IgnoreSubsumingPositions)
1151 if (!InfoCache.getKnowledgeMap().empty()) {
1164 ImpliedAttributeKind)});
1171 bool IgnoreSubsumingPositions) {
1175 if (AttrSet.hasAttribute(Kind))
1176 Attrs.push_back(AttrSet.getAttribute(Kind));
1180 updateAttrMap<Attribute::AttrKind>(EquivIRP, AttrKinds, CollectAttrCB);
1184 if (IgnoreSubsumingPositions)
1187 if (!InfoCache.getKnowledgeMap().empty()) {
1197 if (!AttrSet.hasAttribute(Kind))
1199 AM.addAttribute(Kind);
1202 return updateAttrMap<Attribute::AttrKind>(IRP, AttrKinds, RemoveAttrCB);
1209 if (!AttrSet.hasAttribute(Attr))
1211 AM.addAttribute(Attr);
1215 return updateAttrMap<StringRef>(IRP, Attrs, RemoveAttrCB);
1220 bool ForceReplace) {
1247 Added.push_back(New);
1254 AL = AL.addSortedAttributesAtIndex(Ctx, AttrIdx, Added);
1260 IRPositions.emplace_back(IRP);
1264 auto CanIgnoreOperandBundles = [](
const CallBase &CB) {
1280 assert(CB &&
"Expected call site!");
1283 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
1288 assert(CB &&
"Expected call site!");
1291 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1296 bool SameType = Callee->getReturnType() == CB->getType();
1300 for (
const Argument &Arg : Callee->args())
1301 if (
SameType && Arg.hasReturnedAttr()) {
1302 IRPositions.emplace_back(
1304 IRPositions.emplace_back(
1313 assert(CB &&
"Expected call site!");
1316 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1330#ifdef EXPENSIVE_CHECKS
1331void IRPosition::verify() {
1334 assert((CBContext ==
nullptr) &&
1335 "Invalid position must not have CallBaseContext!");
1337 "Expected a nullptr for an invalid position!");
1341 "Expected specialized kind for argument values!");
1345 "Expected function for a 'returned' position!");
1347 "Associated value mismatch!");
1350 assert((CBContext ==
nullptr) &&
1351 "'call site returned' position must not have CallBaseContext!");
1353 "Expected call base for 'call site returned' position!");
1355 "Associated value mismatch!");
1358 assert((CBContext ==
nullptr) &&
1359 "'call site function' position must not have CallBaseContext!");
1361 "Expected call base for 'call site function' position!");
1363 "Associated value mismatch!");
1367 "Expected function for a 'function' position!");
1369 "Associated value mismatch!");
1373 "Expected argument for a 'argument' position!");
1375 "Associated value mismatch!");
1378 assert((CBContext ==
nullptr) &&
1379 "'call site argument' position must not have CallBaseContext!");
1380 Use *U = getAsUsePtr();
1382 assert(U &&
"Expected use for a 'call site argument' position!");
1384 "Expected call base user for a 'call site argument' position!");
1386 "Expected call base argument operand for a 'call site argument' "
1390 "Argument number mismatch!");
1398std::optional<Constant *>
1401 bool &UsedAssumedInformation) {
1405 for (
auto &CB : SimplificationCallbacks.lookup(IRP)) {
1406 std::optional<Value *> SimplifiedV = CB(IRP, &
AA, UsedAssumedInformation);
1408 return std::nullopt;
1418 UsedAssumedInformation)) {
1420 return std::nullopt;
1434 for (
auto &CB : SimplificationCallbacks.lookup(IRP))
1435 return CB(IRP,
AA, UsedAssumedInformation);
1441 return std::nullopt;
1454 bool &UsedAssumedInformation,
bool RecurseForSelectAndPHI) {
1458 while (!Worklist.
empty()) {
1465 const auto &SimplificationCBs = SimplificationCallbacks.lookup(IRP);
1466 for (
const auto &CB : SimplificationCBs) {
1467 std::optional<Value *> CBResult = CB(IRP,
AA, UsedAssumedInformation);
1468 if (!CBResult.has_value())
1470 Value *V = *CBResult;
1479 if (SimplificationCBs.empty()) {
1482 const auto *PotentialValuesAA =
1484 if (PotentialValuesAA &&
1485 PotentialValuesAA->getAssumedSimplifiedValues(*
this,
Values, S)) {
1486 UsedAssumedInformation |= !PotentialValuesAA->isAtFixpoint();
1495 if (!RecurseForSelectAndPHI)
1498 for (
int I = NV, E =
Values.size();
I < E; ++
I) {
1502 if (!Seen.
insert(V).second)
1519 bool &UsedAssumedInformation) {
1527 if (!Arg->hasPointeeInMemoryValueAttr())
1537 for (
auto &It : AAMap) {
1539 AA->~AbstractAttribute();
1545 bool &UsedAssumedInformation,
1546 bool CheckBBLivenessOnly,
DepClassTy DepClass) {
1547 if (!Configuration.UseLiveness)
1553 CheckBBLivenessOnly, DepClass);
1559 bool &UsedAssumedInformation,
1560 bool CheckBBLivenessOnly,
DepClassTy DepClass) {
1561 if (!Configuration.UseLiveness)
1566 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1571 if (CB->isArgOperand(&U)) {
1575 UsedAssumedInformation, CheckBBLivenessOnly,
1581 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1585 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1587 if (!CheckBBLivenessOnly &&
SI->getPointerOperand() != U.get()) {
1595 UsedAssumedInformation =
true;
1602 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1608 bool &UsedAssumedInformation,
1609 bool CheckBBLivenessOnly,
DepClassTy DepClass,
1610 bool CheckForDeadStore) {
1611 if (!Configuration.UseLiveness)
1616 if (ManifestAddedBlocks.contains(
I.getParent()))
1625 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1629 if (CheckBBLivenessOnly ? FnLivenessAA->
isAssumedDead(
I.getParent())
1634 UsedAssumedInformation =
true;
1638 if (CheckBBLivenessOnly)
1646 if (!IsDeadAA || QueryingAA == IsDeadAA)
1653 UsedAssumedInformation =
true;
1661 UsedAssumedInformation =
true;
1671 bool &UsedAssumedInformation,
1672 bool CheckBBLivenessOnly,
DepClassTy DepClass) {
1673 if (!Configuration.UseLiveness)
1684 isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
1689 if (CheckBBLivenessOnly)
1702 if (!IsDeadAA || QueryingAA == IsDeadAA)
1709 UsedAssumedInformation =
true;
1720 if (!Configuration.UseLiveness)
1728 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1744 return Pred(Callee);
1748 if (!CallEdgesAA || CallEdgesAA->hasUnknownCallee())
1751 const auto &Callees = CallEdgesAA->getOptimisticEdges();
1752 return Pred(Callees.getArrayRef());
1762 bool CheckBBLivenessOnly,
DepClassTy LivenessDepClass,
1763 bool IgnoreDroppableUses,
1768 if (!CB(*
this, &QueryingAA))
1782 auto AddUsers = [&](
const Value &V,
const Use *OldUse) {
1783 for (
const Use &UU : V.uses()) {
1784 if (OldUse && EquivalentUseCB && !EquivalentUseCB(*OldUse, UU)) {
1786 "rejected by the equivalence call back: "
1796 AddUsers(V,
nullptr);
1799 <<
" initial uses to check\n");
1802 const auto *LivenessAA =
1807 while (!Worklist.
empty()) {
1813 dbgs() <<
"[Attributor] Check use: " << **U <<
" in " << Fn->getName()
1816 dbgs() <<
"[Attributor] Check use: " << **U <<
" in " << *U->getUser()
1819 bool UsedAssumedInformation =
false;
1820 if (
isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation,
1821 CheckBBLivenessOnly, LivenessDepClass)) {
1823 dbgs() <<
"[Attributor] Dead use, skip!\n");
1826 if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
1828 dbgs() <<
"[Attributor] Droppable user, skip!\n");
1833 if (&
SI->getOperandUse(0) == U) {
1834 if (!Visited.
insert(U).second)
1838 *
this, *
SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
1842 <<
"[Attributor] Value is stored, continue with "
1843 << PotentialCopies.
size()
1844 <<
" potential copies instead!\n");
1845 for (
Value *PotentialCopy : PotentialCopies)
1846 if (!AddUsers(*PotentialCopy, U))
1853 bool Follow =
false;
1854 if (!
Pred(*U, Follow))
1859 User &Usr = *U->getUser();
1860 AddUsers(Usr,
nullptr);
1868 bool RequireAllCallSites,
1869 bool &UsedAssumedInformation) {
1875 if (!AssociatedFunction) {
1876 LLVM_DEBUG(
dbgs() <<
"[Attributor] No function associated with " << IRP
1882 &QueryingAA, UsedAssumedInformation);
1887 bool RequireAllCallSites,
1889 bool &UsedAssumedInformation,
1890 bool IncludeAssumedDead) {
1894 <<
"[Attributor] Function " << Fn.
getName()
1895 <<
" has no internal linkage, hence not all call sites are known\n");
1900 if (!CB(*
this, QueryingAA))
1904 for (
unsigned u = 0; u <
Uses.size(); ++u) {
1908 dbgs() <<
"[Attributor] Check use: " << Fn->
getName() <<
" in "
1909 << *U.getUser() <<
"\n";
1911 dbgs() <<
"[Attributor] Check use: " << *U <<
" in " << *U.getUser()
1914 if (!IncludeAssumedDead &&
1915 isAssumedDead(U, QueryingAA,
nullptr, UsedAssumedInformation,
1918 dbgs() <<
"[Attributor] Dead use, skip!\n");
1922 if (CE->isCast() && CE->getType()->isPointerTy()) {
1924 dbgs() <<
"[Attributor] Use, is constant cast expression, add "
1925 << CE->getNumUses() <<
" uses of that expression instead!\n";
1927 for (
const Use &CEU : CE->uses())
1928 Uses.push_back(&CEU);
1936 <<
" has non call site use " << *U.get() <<
" in "
1937 << *U.getUser() <<
"\n");
1941 const Use *EffectiveUse =
1944 if (!RequireAllCallSites) {
1945 LLVM_DEBUG(
dbgs() <<
"[Attributor] User " << *EffectiveUse->getUser()
1946 <<
" is not a call of " << Fn.
getName()
1950 LLVM_DEBUG(
dbgs() <<
"[Attributor] User " << *EffectiveUse->getUser()
1951 <<
" is an invalid use of " << Fn.
getName() <<
"\n");
1959 unsigned MinArgsParams =
1961 for (
unsigned u = 0; u < MinArgsParams; ++u) {
1965 dbgs() <<
"[Attributor] Call site / callee argument type mismatch ["
1966 << u <<
"@" << Fn.
getName() <<
": "
1976 LLVM_DEBUG(
dbgs() <<
"[Attributor] Call site callback failed for "
1984bool Attributor::shouldPropagateCallBaseContext(
const IRPosition &IRP) {
1988 return Opts.attributor_enable_call_site_specific_deduction;
1994 bool RecurseForSelectAndPHI) {
1998 if (!AssociatedFunction)
2001 bool UsedAssumedInformation =
false;
2005 UsedAssumedInformation, RecurseForSelectAndPHI))
2017 bool &UsedAssumedInformation,
bool CheckBBLivenessOnly =
false,
2018 bool IncludeAssumedDead =
false) {
2019 for (
unsigned Opcode : Opcodes) {
2021 auto *Insts = OpcodeInstMap[Opcode];
2027 if (
A && !IncludeAssumedDead &&
2029 UsedAssumedInformation, CheckBBLivenessOnly)) {
2031 dbgs() <<
"[Attributor] Instruction " << *
I
2032 <<
" is potentially dead, skip!\n";);
2047 bool &UsedAssumedInformation,
2048 bool CheckBBLivenessOnly,
2049 bool IncludeAssumedDead) {
2054 const AAIsDead *LivenessAA =
nullptr;
2055 if (!IncludeAssumedDead && Configuration.UseLiveness) {
2062 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
2064 LivenessAA, Opcodes, UsedAssumedInformation,
2065 CheckBBLivenessOnly, IncludeAssumedDead))
2074 bool &UsedAssumedInformation,
2075 bool CheckBBLivenessOnly,
2076 bool IncludeAssumedDead) {
2080 UsedAssumedInformation, CheckBBLivenessOnly,
2081 IncludeAssumedDead);
2086 bool &UsedAssumedInformation) {
2089 const Function *AssociatedFunction =
2091 if (!AssociatedFunction)
2095 const auto *LivenessAA =
2099 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
2102 UsedAssumedInformation))
2112void Attributor::runTillFixpoint() {
2116 <<
" abstract attributes.\n");
2121 unsigned IterationCounter = 1;
2123 Opts.attributor_max_iterations);
2133 LLVM_DEBUG(
dbgs() <<
"\n\n[Attributor] #Iteration: " << IterationCounter
2134 <<
", Worklist size: " << Worklist.
size() <<
"\n");
2139 for (
unsigned u = 0; u < InvalidAAs.
size(); ++u) {
2144 dbgs() <<
"[Attributor] InvalidAA: " << *InvalidAA
2145 <<
" has " << InvalidAA->
Deps.
size()
2146 <<
" required & optional dependences\n");
2147 for (
auto &DepIt : InvalidAA->
Deps) {
2151 dbgs() <<
" - recompute: " << *DepAA);
2156 <<
" - invalidate: " << *DepAA);
2160 InvalidAAs.
insert(DepAA);
2169 for (AbstractAttribute *ChangedAA : ChangedAAs) {
2170 for (
auto &DepIt : ChangedAA->Deps)
2172 ChangedAA->Deps.clear();
2175 LLVM_DEBUG(
dbgs() <<
"[Attributor] #Iteration: " << IterationCounter
2176 <<
", Worklist+Dependent size: " << Worklist.
size()
2185 for (AbstractAttribute *AA : Worklist) {
2186 if (!AA->isStateAtFixpoint())
2188 ChangedAAs.push_back(AA);
2192 if (!AA->getState().isValidState())
2198 ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs,
2199 DG.SyntheticRoot.end());
2204 Worklist.insert_range(ChangedAAs);
2205 Worklist.insert_range(QueryAAsAwaitingUpdate);
2206 QueryAAsAwaitingUpdate.clear();
2208 }
while (!Worklist.empty() && (IterationCounter++ < MaxIterations));
2210 if (IterationCounter > MaxIterations && !Functions.empty()) {
2211 auto Remark = [&](OptimizationRemarkMissed ORM) {
2212 return ORM <<
"Attributor did not reach a fixpoint after "
2213 <<
ore::NV(
"Iterations", MaxIterations) <<
" iterations.";
2219 LLVM_DEBUG(
dbgs() <<
"\n[Attributor] Fixpoint iteration done after: "
2220 << IterationCounter <<
"/" << MaxIterations
2221 <<
" iterations\n");
2228 SmallPtrSet<AbstractAttribute *, 32> Visited;
2229 for (
unsigned u = 0;
u < ChangedAAs.size();
u++) {
2230 AbstractAttribute *ChangedAA = ChangedAAs[
u];
2231 if (!Visited.
insert(ChangedAA).second)
2234 AbstractState &State = ChangedAA->
getState();
2238 NumAttributesTimedOut++;
2241 for (
auto &DepIt : ChangedAA->
Deps)
2247 if (!Visited.
empty())
2248 dbgs() <<
"\n[Attributor] Finalized " << Visited.
size()
2249 <<
" abstract attributes.\n";
2255 "Non-query AAs should not be required to register for updates!");
2256 QueryAAsAwaitingUpdate.insert(&
AA);
2263 unsigned NumManifested = 0;
2264 unsigned NumAtFixpoint = 0;
2274 if (!
AA->isStateAtFixpoint())
2275 State.indicateOptimisticFixpoint();
2278 if (
AA->hasCallBaseContext())
2281 if (!State.isValidState())
2284 if (
AA->getCtxI() && !
isRunOn(*
AA->getAnchorScope()))
2288 bool UsedAssumedInformation =
false;
2299 AA->trackStatistics();
2300 LLVM_DEBUG(
dbgs() <<
"[Attributor] Manifest " << LocalChange <<
" : " << *
AA
2303 ManifestChange = ManifestChange | LocalChange;
2309 (void)NumManifested;
2310 (void)NumAtFixpoint;
2311 LLVM_DEBUG(
dbgs() <<
"\n[Attributor] Manifested " << NumManifested
2312 <<
" arguments while " << NumAtFixpoint
2313 <<
" were in a valid fixpoint state\n");
2315 NumAttributesManifested += NumManifested;
2316 NumAttributesValidFixpoint += NumAtFixpoint;
2321 for (
unsigned u = 0; u < NumFinalAAs; ++u)
2325 errs() <<
"Unexpected abstract attribute: "
2329 .getAssociatedValue()
2333 "remain unchanged!");
2336 for (
auto &It : AttrsMap) {
2337 AttributeList &
AL = It.getSecond();
2338 const IRPosition &IRP =
2341 : IRPosition::callsite_function(*
cast<CallBase>(It.getFirst()));
2348 return ManifestChange;
2351void Attributor::identifyDeadInternalFunctions() {
2353 if (!Configuration.DeleteFns)
2371 if (
F->hasLocalLinkage() &&
2375 SmallPtrSet<Function *, 8> LiveInternalFns;
2376 bool FoundLiveInternal =
true;
2377 while (FoundLiveInternal) {
2378 FoundLiveInternal =
false;
2383 bool UsedAssumedInformation =
false;
2385 [&](AbstractCallSite ACS) {
2387 return ToBeDeletedFunctions.count(Callee) ||
2388 (Functions.count(Callee) &&
Callee->hasLocalLinkage() &&
2389 !LiveInternalFns.
count(Callee));
2391 *
F,
true,
nullptr, UsedAssumedInformation)) {
2397 FoundLiveInternal =
true;
2403 ToBeDeletedFunctions.insert(
F);
2407 TimeTraceScope TimeScope(
"Attributor::cleanupIR");
2410 << ToBeDeletedFunctions.size() <<
" functions and "
2411 << ToBeDeletedBlocks.size() <<
" blocks and "
2412 << ToBeDeletedInsts.size() <<
" instructions and "
2413 << ToBeChangedValues.size() <<
" values and "
2414 << ToBeChangedUses.size() <<
" uses. To insert "
2415 << ToBeChangedToUnreachableInsts.size()
2416 <<
" unreachables.\n"
2417 <<
"Preserve manifest added " << ManifestAddedBlocks.size()
2423 auto ReplaceUse = [&](
Use *
U,
Value *NewV) {
2428 const auto &
Entry = ToBeChangedValues.lookup(NewV);
2436 "Cannot replace an instruction outside the current SCC!");
2442 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
2447 for (
auto &Arg : RI->getFunction()->args())
2448 Arg.removeAttr(Attribute::Returned);
2452 <<
" instead of " << *OldV <<
"\n");
2458 CGModifiedFunctions.insert(
I->getFunction());
2460 Configuration.CGUpdater.addReferences(*
I->getFunction(), *
C);
2463 if (!
isa<PHINode>(OldI) && !ToBeDeletedInsts.count(OldI) &&
2469 if (CB->isArgOperand(U)) {
2470 unsigned Idx = CB->getArgOperandNo(U);
2473 AttributeMask UBImplying = AttributeFuncs::getUBImplyingAttributes();
2474 CB->removeParamAttrs(Idx, UBImplying);
2476 if (Callee &&
Callee->arg_size() > Idx)
2477 Callee->removeParamAttrs(Idx, UBImplying);
2483 ToBeChangedToUnreachableInsts.insert(UserI);
2490 for (
auto &It : ToBeChangedUses) {
2492 Value *NewV = It.second;
2493 ReplaceUse(U, NewV);
2497 for (
auto &It : ToBeChangedValues) {
2498 Value *OldV = It.first;
2499 auto [NewV,
Done] = It.second;
2501 for (
auto &U : OldV->
uses())
2502 if (
Done || !
U.getUser()->isDroppable())
2504 for (Use *U :
Uses) {
2508 ReplaceUse(U, NewV);
2512 for (
const auto &
V : InvokeWithDeadSuccessor)
2515 "Cannot replace an invoke outside the current SCC!");
2516 bool UnwindBBIsDead =
II->hasFnAttr(Attribute::NoUnwind);
2517 bool NormalBBIsDead =
II->hasFnAttr(Attribute::NoReturn);
2518 bool Invoke2CallAllowed =
2520 assert((UnwindBBIsDead || NormalBBIsDead) &&
2521 "Invoke does not have dead successors!");
2524 if (UnwindBBIsDead) {
2526 if (Invoke2CallAllowed) {
2531 ToBeChangedToUnreachableInsts.insert(NormalNextIP);
2533 assert(NormalBBIsDead &&
"Broken invariant!");
2536 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->
front());
2539 for (Instruction *
I : TerminatorsToFold) {
2541 "Cannot replace a terminator outside the current SCC!");
2542 CGModifiedFunctions.insert(
I->getFunction());
2545 for (
const auto &
V : ToBeChangedToUnreachableInsts)
2550 "Cannot replace an instruction outside the current SCC!");
2551 CGModifiedFunctions.insert(
I->getFunction());
2555 for (
const auto &
V : ToBeDeletedInsts) {
2559 "Cannot delete an instruction outside the current SCC!");
2560 I->dropDroppableUses();
2561 CGModifiedFunctions.insert(
I->getFunction());
2562 if (!
I->getType()->isVoidTy())
2567 I->eraseFromParent();
2574 dbgs() <<
"[Attributor] DeadInsts size: " << DeadInsts.
size() <<
"\n";
2575 for (
auto &
I : DeadInsts)
2577 dbgs() <<
" - " << *
I <<
"\n";
2582 if (
unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
2583 SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
2584 ToBeDeletedBBs.
reserve(NumDeadBlocks);
2585 for (BasicBlock *BB : ToBeDeletedBlocks) {
2587 "Cannot delete a block outside the current SCC!");
2588 CGModifiedFunctions.insert(BB->
getParent());
2590 if (ManifestAddedBlocks.contains(BB))
2600 identifyDeadInternalFunctions();
2603 ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
2605 for (
Function *Fn : CGModifiedFunctions)
2606 if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn))
2607 Configuration.CGUpdater.reanalyzeFunction(*Fn);
2609 for (
Function *Fn : ToBeDeletedFunctions) {
2610 if (!Functions.count(Fn))
2612 Configuration.CGUpdater.removeFunction(*Fn);
2615 if (!ToBeChangedUses.empty())
2618 if (!ToBeChangedToUnreachableInsts.empty())
2621 if (!ToBeDeletedFunctions.empty())
2624 if (!ToBeDeletedBlocks.empty())
2627 if (!ToBeDeletedInsts.empty())
2630 if (!InvokeWithDeadSuccessor.empty())
2633 if (!DeadInsts.empty())
2636 NumFnDeleted += ToBeDeletedFunctions.size();
2638 LLVM_DEBUG(
dbgs() <<
"[Attributor] Deleted " << ToBeDeletedFunctions.size()
2639 <<
" functions after manifest.\n");
2641#ifdef EXPENSIVE_CHECKS
2643 if (ToBeDeletedFunctions.count(
F))
2649 return ManifestChange;
2654 AttributorCallGraph ACallGraph(*
this);
2656 if (
Opts.attributor_print_call_graph)
2659 Phase = AttributorPhase::UPDATE;
2663 if (
Opts.attributor_dump_dep_graph)
2664 DG.dumpGraph(
Opts.attributor_depgraph_dot_filename_prefix);
2666 if (
Opts.attributor_view_dep_graph)
2669 if (
Opts.attributor_print_dep)
2672 Phase = AttributorPhase::MANIFEST;
2675 Phase = AttributorPhase::CLEANUP;
2678 if (
Opts.attributor_print_call_graph)
2681 return ManifestChange | CleanupChange;
2685 std::optional<TimeTraceScope> TimeScope;
2686 if (TimeTraceEnabled) {
2687 TimeScope.emplace(
"updateAA", [&]() {
2688 return AA.getName().str() +
2689 std::to_string(
AA.getIRPosition().getPositionKind());
2693 assert(Phase == AttributorPhase::UPDATE &&
2694 "We can update AA only in the update stage!");
2697 DependenceVector DV;
2698 DependenceStack.push_back(&DV);
2702 bool UsedAssumedInformation =
false;
2714 RerunCS = AA.
update(*
this);
2720 AAState.indicateOptimisticFixpoint();
2724 rememberDependences();
2728 DependenceVector *PoppedDV = DependenceStack.pop_back_val();
2730 assert(PoppedDV == &DV &&
"Inconsistent usage of the dependence stack!");
2736 assert(!
F.isDeclaration() &&
"Cannot create a wrapper around a declaration!");
2745 M.getFunctionList().insert(
F.getIterator(),
Wrapper);
2750 assert(
F.use_empty() &&
"Uses remained after wrapper was created!");
2755 F.setComdat(
nullptr);
2759 F.getAllMetadata(MDs);
2760 for (
auto MDIt : MDs)
2761 Wrapper->addMetadata(MDIt.first, *MDIt.second);
2762 Wrapper->setAttributes(
F.getAttributes());
2770 Args.push_back(&Arg);
2771 Arg.setName((FArgIt++)->
getName());
2779 NumFnShallowWrappersCreated++;
2783 if (
F.isDeclaration() ||
F.hasLocalLinkage() ||
2799 return InternalizedFns[&
F];
2820 F->getName() +
".internalized");
2823 for (
auto &Arg :
F->args()) {
2824 auto ArgName = Arg.getName();
2825 NewFArgIt->setName(ArgName);
2826 VMap[&Arg] = &(*NewFArgIt++);
2841 F->getAllMetadata(MDs);
2842 for (
auto MDIt : MDs)
2846 M.getFunctionList().insert(
F->getIterator(), Copied);
2854 auto &InternalizedFn = FnMap[
F];
2855 auto IsNotInternalized = [&](
Use &U) ->
bool {
2857 return !FnMap.
lookup(CB->getCaller());
2860 F->replaceUsesWithIf(InternalizedFn, IsNotInternalized);
2869 if (!Configuration.RewriteSignatures)
2892 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite var-args functions\n");
2898 if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
2899 FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
2900 FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
2901 FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
2903 dbgs() <<
"[Attributor] Cannot rewrite due to complex attribute\n");
2908 bool UsedAssumedInformation =
false;
2910 UsedAssumedInformation,
2912 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite all call sites\n");
2918 return !CI->isMustTailCall();
2924 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
2926 nullptr, {Instruction::Call},
2927 UsedAssumedInformation)) {
2928 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite due to instructions\n");
2939 LLVM_DEBUG(
dbgs() <<
"[Attributor] Register new rewrite of " << Arg <<
" in "
2941 << ReplacementTypes.
size() <<
" replacements\n");
2943 "Cannot register an invalid rewrite");
2947 ArgumentReplacementMap[Fn];
2953 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.
getArgNo()];
2954 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.
size()) {
2955 LLVM_DEBUG(
dbgs() <<
"[Attributor] Existing rewrite is preferred\n");
2963 LLVM_DEBUG(
dbgs() <<
"[Attributor] Register new rewrite of " << Arg <<
" in "
2965 << ReplacementTypes.
size() <<
" replacements\n");
2969 std::move(CalleeRepairCB),
2970 std::move(ACSRepairCB)));
2978 if (
Opts.attributor_seed_allow_list.size() != 0)
2981 if (
Opts.attributor_function_seed_allow_list.size() != 0 && Fn)
2992 for (
auto &It : ArgumentReplacementMap) {
2996 if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
3009 if (
const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3010 ARIs[Arg.getArgNo()]) {
3011 NewArgumentTypes.
append(ARI->ReplacementTypes.begin(),
3012 ARI->ReplacementTypes.end());
3013 NewArgumentAttributes.
append(ARI->getNumReplacementArgs(),
3016 NewArgumentTypes.
push_back(Arg.getType());
3018 OldFnAttributeList.getParamAttrs(Arg.getArgNo()));
3023 for (
auto *
I : NewArgumentTypes)
3025 LargestVectorWidth =
3026 std::max(LargestVectorWidth,
3027 VT->getPrimitiveSizeInBits().getKnownMinValue());
3030 Type *RetTy = OldFnTy->getReturnType();
3033 FunctionType *NewFnTy =
3038 << *NewFnTy <<
"\n");
3043 Functions.insert(NewFn);
3056 Ctx, OldFnAttributeList.getFnAttrs(), OldFnAttributeList.getRetAttrs(),
3057 NewArgumentAttributes));
3058 AttributeFuncs::updateMinLegalVectorWidthAttr(*NewFn, LargestVectorWidth);
3066 return !
T->isPtrOrPtrVectorTy() ||
3082 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
3084 const AttributeList &OldCallAttributeList = OldCB->
getAttributes();
3087 SmallVector<Value *, 16> NewArgOperands;
3089 for (
unsigned OldArgNum = 0; OldArgNum < ARIs.
size(); ++OldArgNum) {
3090 unsigned NewFirstArgNum = NewArgOperands.
size();
3091 (void)NewFirstArgNum;
3092 if (
const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3094 if (ARI->ACSRepairCB)
3095 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
3096 assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
3097 NewArgOperands.
size() &&
3098 "ACS repair callback did not provide as many operand as new "
3099 "types were registered!");
3101 NewArgOperandAttributes.
append(ARI->ReplacementTypes.size(),
3106 OldCallAttributeList.getParamAttrs(OldArgNum));
3110 assert(NewArgOperands.
size() == NewArgOperandAttributes.
size() &&
3111 "Mismatch # argument operands vs. # argument operand attributes!");
3113 "Mismatch # argument operands vs. # function arguments!");
3122 II->getUnwindDest(), NewArgOperands,
3127 NewCI->setTailCallKind(
cast<CallInst>(OldCB)->getTailCallKind());
3136 Ctx, OldCallAttributeList.getFnAttrs(),
3137 OldCallAttributeList.getRetAttrs(), NewArgOperandAttributes));
3139 AttributeFuncs::updateMinLegalVectorWidthAttr(*NewCB->
getCaller(),
3140 LargestVectorWidth);
3142 CallSitePairs.
push_back({OldCB, NewCB});
3147 bool UsedAssumedInformation =
false;
3149 true,
nullptr, UsedAssumedInformation,
3152 assert(
Success &&
"Assumed call site replacement to succeed!");
3157 for (
unsigned OldArgNum = 0; OldArgNum < ARIs.
size();
3158 ++OldArgNum, ++OldFnArgIt) {
3159 if (
const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3161 if (ARI->CalleeRepairCB)
3162 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
3163 if (ARI->ReplacementTypes.empty())
3166 NewFnArgIt += ARI->ReplacementTypes.size();
3168 NewFnArgIt->
takeName(&*OldFnArgIt);
3175 for (
auto &CallSitePair : CallSitePairs) {
3176 CallBase &OldCB = *CallSitePair.first;
3177 CallBase &NewCB = *CallSitePair.second;
3179 "Cannot handle call sites with different types!");
3186 Configuration.CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
3190 if (ModifiedFns.
remove(OldFn))
3191 ModifiedFns.
insert(NewFn);
3201 Instruction::Call, Instruction::CallBr,
3202 Instruction::Invoke, Instruction::CleanupRet,
3203 Instruction::CatchSwitch, Instruction::AtomicRMW,
3204 Instruction::AtomicCmpXchg, Instruction::UncondBr,
3205 Instruction::CondBr, Instruction::Resume,
3206 Instruction::Ret, Instruction::Load,
3207 Instruction::Store, Instruction::Alloca,
3208 Instruction::AddrSpaceCast,
3211void InformationCache::initializeInformationCache(
const Function &CF,
3218 FI.IsKernel =
F.hasFnAttribute(
"kernel");
3225 bool IsInterestingOpcode =
false;
3226 bool MayReadOrWriteMemory =
false;
3233 switch (
I.getOpcode()) {
3236 "New call base instruction type needs to be known in the "
3239 case Instruction::VAArg:
3240 case Instruction::Fence:
3241 case Instruction::CatchPad:
3242 case Instruction::CatchRet:
3243 MayReadOrWriteMemory =
true;
3245 case Instruction::Call:
3252 FI.ContainsMustTailCall =
true;
3255 getFunctionInfo(*Callee).CalledViaMustTail =
true;
3258 case Instruction::CallBr:
3259 case Instruction::Invoke:
3261 IsInterestingOpcode =
true;
3263 case Instruction::AtomicRMW:
3264 case Instruction::AtomicCmpXchg:
3265 case Instruction::Load:
3267 case Instruction::Store:
3269 MayReadOrWriteMemory =
true;
3270 IsInterestingOpcode =
true;
3272 case Instruction::CleanupRet:
3273 case Instruction::CatchSwitch:
3274 case Instruction::UncondBr:
3275 case Instruction::CondBr:
3276 case Instruction::Resume:
3277 case Instruction::Ret:
3278 case Instruction::Alloca:
3279 case Instruction::AddrSpaceCast:
3280 IsInterestingOpcode =
true;
3282 assert(MayReadOrWriteMemory ==
I.mayReadOrWriteMemory() &&
3283 "Memory accessing opcode not handled");
3284 if (IsInterestingOpcode) {
3286 "Interesting opcode missing from InterestingOpcodes");
3287 auto *&Insts = FI.OpcodeInstMap[
I.getOpcode()];
3292 if (MayReadOrWriteMemory)
3293 FI.RWInsts.push_back(&
I);
3296 bool IsInlineable =
F.hasFnAttribute(Attribute::AlwaysInline) &&
3299 InlineableFunctions.insert(&
F);
3300 FI.IsExactOrInlineable = IsInlineable ||
F.hasExactDefinition();
3303void InformationCache::collectAssumeOnlyValues(FunctionInfo &FI) {
3304 FI.AssumeOnlyValuesCollected =
true;
3309 DenseMap<const Value *, std::optional<short>> AssumeUsesMap;
3314 auto AddToAssumeUsesMap = [&](
const Value &
V) ->
void {
3315 SmallVector<const Instruction *> Worklist;
3318 while (!Worklist.
empty()) {
3320 std::optional<short> &NumUses = AssumeUsesMap[
I];
3322 NumUses =
I->getNumUses();
3323 NumUses = *NumUses - 1;
3326 AssumeOnlyValues.insert(
I);
3333 AssumeOnlyValues.insert(Assume);
3334 AddToAssumeUsesMap(*
Assume->getArgOperand(0));
3338InformationCache::FunctionInfo::~FunctionInfo() {
3343 Insts->~InstructionVectorTy();
3349 assert(
A.isClosedWorldModule() &&
"Cannot see all indirect callees!");
3350 return IndirectlyCallableFunctions;
3356 return std::nullopt;
3367 if (DependenceStack.empty())
3371 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
3374void Attributor::rememberDependences() {
3375 assert(!DependenceStack.empty() &&
"No dependences to remember!");
3377 for (DepInfo &DI : *DependenceStack.back()) {
3380 "Expected required or optional dependence (1 bit)!");
3387template <Attribute::AttrKind AK,
typename AAType>
3388void Attributor::checkAndQueryIRAttr(
const IRPosition &IRP, AttributeSet Attrs,
3389 bool SkipHasAttrCheck) {
3391 if (SkipHasAttrCheck || !
Attrs.hasAttribute(AK))
3392 if (isAllowed<AAType>())
3395 getOrCreateAAFor<AAType>(IRP);
3401 if (!VisitedFunctions.insert(&
F).second)
3407 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(
F);
3409 for (
const Use &U :
F.uses())
3411 if (CB->isCallee(&U) && CB->isMustTailCall())
3412 FI.CalledViaMustTail =
true;
3417 auto Attrs =
F.getAttributes();
3418 auto FnAttrs = Attrs.getFnAttrs();
3430 if (
Opts.enable_heap_to_stack_conversion)
3434 checkAndQueryIRAttr<Attribute::MustProgress, AAMustProgress>(FPos, FnAttrs);
3437 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(FPos, FnAttrs);
3440 checkAndQueryIRAttr<Attribute::WillReturn, AAWillReturn>(FPos, FnAttrs);
3443 checkAndQueryIRAttr<Attribute::NoSync, AANoSync>(FPos, FnAttrs);
3448 if (IsIPOAmendable) {
3451 checkAndQueryIRAttr<Attribute::NoUnwind, AANoUnwind>(FPos, FnAttrs);
3454 checkAndQueryIRAttr<Attribute::NoReturn, AANoReturn>(FPos, FnAttrs);
3457 checkAndQueryIRAttr<Attribute::NoRecurse, AANoRecurse>(FPos, FnAttrs);
3460 if (Attrs.hasFnAttr(Attribute::Convergent))
3481 Type *ReturnType =
F.getReturnType();
3482 if (!ReturnType->isVoidTy()) {
3490 bool UsedAssumedInformation =
false;
3495 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(RetPos, RetAttrs);
3497 if (ReturnType->isPointerTy()) {
3503 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(RetPos, RetAttrs);
3506 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(RetPos, RetAttrs);
3511 }
else if (AttributeFuncs::isNoFPClassCompatibleType(ReturnType)) {
3519 auto ArgNo = Arg.getArgNo();
3522 if (!IsIPOAmendable) {
3523 if (Arg.getType()->isPointerTy())
3525 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(ArgPos, ArgAttrs);
3532 bool UsedAssumedInformation =
false;
3540 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(ArgPos, ArgAttrs);
3542 if (Arg.getType()->isPointerTy()) {
3544 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(ArgPos, ArgAttrs);
3547 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(ArgPos, ArgAttrs);
3556 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3557 ArgPos, ArgAttrs,
true);
3564 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(ArgPos, ArgAttrs);
3569 }
else if (AttributeFuncs::isNoFPClassCompatibleType(Arg.getType())) {
3596 if (!
Opts.attributor_annotate_decl_cs && Callee->isDeclaration() &&
3597 !Callee->hasMetadata(LLVMContext::MD_callback))
3600 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
3602 bool UsedAssumedInformation =
false;
3606 if (AttributeFuncs::isNoFPClassCompatibleType(Callee->getReturnType()))
3611 for (
int I = 0, E = CB.arg_size();
I < E; ++
I) {
3622 bool UsedAssumedInformation =
false;
3627 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(CBArgPos, CBArgAttrs);
3629 Type *ArgTy = CB.getArgOperand(
I)->getType();
3632 if (AttributeFuncs::isNoFPClassCompatibleType(ArgTy))
3639 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(CBArgPos, CBArgAttrs);
3642 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3643 CBArgPos, CBArgAttrs,
true);
3646 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(CBArgPos, CBArgAttrs);
3656 if (!CBAttrs.hasParamAttr(
I, Attribute::ReadNone))
3660 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(CBArgPos, CBArgAttrs);
3665 [[maybe_unused]]
bool Success;
3666 bool UsedAssumedInformation =
false;
3668 nullptr, FI.OpcodeInstMap, CallSitePred,
nullptr,
nullptr,
3669 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
3670 (unsigned)Instruction::Call},
3671 UsedAssumedInformation);
3672 assert(
Success &&
"Expected the check call to be successful!");
3677 if (
Opts.attributor_simplify_all_loads)
3682 if (InfoCache.getFlatAddressSpace().has_value()) {
3692 if (InfoCache.getFlatAddressSpace().has_value()) {
3700 nullptr, FI.OpcodeInstMap, LoadStorePred,
nullptr,
nullptr,
3701 {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
3702 UsedAssumedInformation);
3703 assert(
Success &&
"Expected the check call to be successful!");
3706 auto AAAllocationInfoPred = [&](
Instruction &
I) ->
bool {
3712 nullptr, FI.OpcodeInstMap, AAAllocationInfoPred,
nullptr,
nullptr,
3713 {(unsigned)Instruction::Alloca}, UsedAssumedInformation);
3714 assert(
Success &&
"Expected the check call to be successful!");
3718 return valueOr(
Opts.attributor_assume_closed_world,
3736 return OS <<
"fn_ret";
3738 return OS <<
"cs_ret";
3746 return OS <<
"cs_arg";
3768 return OS << static_cast<const AbstractState &>(S);
3782 OS <<
"set-state(< {";
3798 OS <<
"set-state(< {";
3804 OS <<
"@" <<
F->getName() <<
"[" << int(It.second) <<
"], ";
3806 OS << *It.first.getValue() <<
"[" << int(It.second) <<
"], ";
3819 OS <<
"] for CtxI ";
3826 OS <<
"<<null inst>>";
3835 for (
const auto &DepAA :
Deps) {
3836 auto *
AA = DepAA.getPointer();
3853 OS <<
" [ <unknown> ]";
3867 bool DeleteFns,
bool IsModulePass) {
3868 if (Functions.empty())
3873 dbgs() <<
"[Attributor] Run on module with " << Functions.size()
3882 AC.IsModulePass = IsModulePass;
3883 AC.DeleteFns = DeleteFns;
3887 AC.OREGetter = OREGetter;
3892 IndirectCalleeTrackingMap;
3893 if (Opts.attributor_max_specializations_per_call_base) {
3894 AC.IndirectCalleeSpecializationCallback =
3897 if (*Opts.attributor_max_specializations_per_call_base == 0)
3899 auto &Set = IndirectCalleeTrackingMap[&CB];
3901 Set = std::make_unique<SmallPtrSet<Function *, 8>>();
3902 if (Set->size() >= *Opts.attributor_max_specializations_per_call_base)
3903 return Set->contains(&Callee);
3904 Set->insert(&Callee);
3912 if (Opts.attributor_allow_shallow_wrappers)
3914 if (!
A.isFunctionIPOAmendable(*
F))
3921 if (Opts.attributor_allow_deep_wrappers) {
3922 unsigned FunSize = Functions.size();
3923 for (
unsigned u = 0; u < FunSize; u++) {
3925 if (!
F->isDeclaration() && !
F->isDefinitionExact() && !
F->use_empty() &&
3928 assert(NewF &&
"Could not internalize function.");
3929 Functions.insert(NewF);
3933 for (
const Use &U : NewF->
uses())
3935 auto *CallerF = CB->getCaller();
3943 if (
F->isDeclaration())
3946 if (
F->hasExactDefinition())
3947 NumFnWithExactDefinition++;
3949 NumFnWithoutExactDefinition++;
3954 if (
F->hasLocalLinkage()) {
3956 const auto *CB = dyn_cast<CallBase>(U.getUser());
3957 return CB && CB->isCallee(&U) &&
3958 Functions.count(const_cast<Function *>(CB->getCaller()));
3965 A.identifyDefaultAbstractAttributes(*
F);
3970 LLVM_DEBUG(
dbgs() <<
"[Attributor] Done with " << Functions.size()
3971 <<
" functions, result: " <<
Changed <<
".\n");
3979 bool IsModulePass) {
3980 if (Functions.empty())
3984 dbgs() <<
"[AttributorLight] Run on module with " << Functions.size()
3993 AC.IsModulePass = IsModulePass;
3994 AC.DeleteFns =
false;
4001 AC.Allowed = Allowed;
4002 AC.UseLiveness =
false;
4007 if (
F->isDeclaration())
4013 if (!
F->hasExactDefinition()) {
4014 NumFnWithoutExactDefinition++;
4017 NumFnWithExactDefinition++;
4022 if (AC.UseLiveness &&
F->hasLocalLinkage()) {
4024 const auto *CB = dyn_cast<CallBase>(U.getUser());
4025 return CB && CB->isCallee(&U) &&
4026 Functions.count(const_cast<Function *>(CB->getCaller()));
4033 A.identifyDefaultAbstractAttributes(*
F);
4056 for (
auto *U :
Changed.users()) {
4059 FAM.invalidate(*
Call->getFunction(), AttrOnlyPA);
4069 if (IRModified.contains(
Changed))
4075 LLVM_DEBUG(
dbgs() <<
"[Attributor] Done with " << Functions.size()
4076 <<
" functions, result: " <<
Changed <<
".\n");
4083 static std::atomic<int> CallTimes;
4086 if (!DotFileNamePrefix.
empty())
4087 Prefix = DotFileNamePrefix;
4089 Prefix =
"dep_graph";
4091 Prefix +
"_" + std::to_string(CallTimes.load()) +
".dot";
4093 outs() <<
"Dependency graph dump to " <<
Filename <<
".\n";
4117 Functions.insert(&
F);
4141 Functions.insert(&
N.getFunction());
4143 if (Functions.empty())
4146 Module &M = *Functions.back()->getParent();
4171 Functions.insert(&
F);
4198 Functions.
insert(&
N.getFunction());
4200 if (Functions.empty())
4203 Module &M = *Functions.back()->getParent();
4255 std::string AAString;
static unsigned getIntrinsicID(const SDNode *N)
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
bool canMarkAsVisited(const User *Usr)
#define VERBOSE_DEBUG_TYPE
static bool getPotentialCopiesOfMemoryValue(Attributor &A, Ty &I, SmallSetVector< Value *, 4 > &PotentialCopies, SmallSetVector< Instruction *, 4 > *PotentialValueOrigins, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact)
static bool runAttributorOnFunctions(InformationCache &InfoCache, SetVector< Function * > &Functions, CallGraphUpdater &CGUpdater, FunctionAnalysisManager &FAM, bool DeleteFns, bool IsModulePass)
}
static bool runAttributorLightOnFunctions(InformationCache &InfoCache, SetVector< Function * > &Functions, CallGraphUpdater &CGUpdater, FunctionAnalysisManager &FAM, bool IsModulePass)
static bool checkForAllInstructionsImpl(Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap, function_ref< bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA, const AAIsDead *LivenessAA, ArrayRef< unsigned > Opcodes, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, bool IncludeAssumedDead=false)
static bool isEqualOrWorse(const Attribute &New, const Attribute &Old)
Return true if New is equal or worse than Old.
static constexpr unsigned InterestingOpcodes[]
The opcodes of the instructions recorded in FunctionInfo::OpcodeInstMap.
static bool isAssumedReadOnlyOrReadNone(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool RequireReadNone, bool &IsKnown)
static Attribute getAttrToAdd(LLVMContext &Ctx, Attribute Attr, Attribute Existing, bool ForceReplace)
Return the attribute to add to a position to provide the information of Attr, given the attribute Exi...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static constexpr StringLiteral Filename
FunctionAnalysisManager FAM
This file defines the PointerIntPair class.
static StringRef getName(Value *V)
Remove Loads Into Fake Uses
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
void print(OutputBuffer &OB) const
A set of kinds of abstract attributes.
static constexpr AAKindSet get()
Return the set of the kinds of abstract attributes of types AATypes.
static constexpr const fltSemantics & IEEEsingle()
Class for arbitrary precision integers.
CallBase * getInstruction() const
Return the underlying instruction.
bool isCallbackCall() const
Return true if this ACS represents a callback call.
const Use & getCalleeUseForCallback() const
Return the use of the callee value in the underlying instruction.
static LLVM_ABI void getCallbackUses(const CallBase &CB, SmallVectorImpl< const Use * > &CallbackUses)
Add operand uses of CB that represent callback uses into CallbackUses.
bool isCallee(Value::const_user_iterator UI) const
Return true if UI is the use that defines the callee of this ACS.
Value * getCallArgOperand(Argument &Arg) const
Return the operand of the underlying instruction associated with Arg.
int getCallArgOperandNo(Argument &Arg) const
Return the operand index of the underlying instruction associated with Arg.
unsigned getNumArgOperands() const
Return the number of parameters of the callee.
Function * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
const Function * getParent() const
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
bool empty() const
Return true if the mask contains no attributes.
This class holds the attributes for a particular argument, parameter, function, or return value.
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
LLVM_ABI bool isEnumAttribute() const
Return true if the attribute is an Attribute::AttrKind type.
LLVM_ABI bool isIntAttribute() const
Return true if the attribute is an integer attribute.
LLVM_ABI uint64_t getValueAsInt() const
Return the attribute's value as an integer.
LLVM_ABI bool isConstantRangeAttribute() const
Return true if the attribute is a ConstantRange attribute.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
LLVM_ABI MemoryEffects getMemoryEffects() const
Returns memory effects.
static LLVM_ABI Attribute getWithMemoryEffects(LLVMContext &Context, MemoryEffects ME)
bool isValid() const
Return true if the attribute is any kind of attribute.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Represents analyses that only rely on functions' control flow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
CallingConv::ID getCallingConv() const
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
Wrapper to unify "old style" CallGraph and "new style" LazyCallGraph.
LLVM_ABI void replaceFunctionWith(Function &OldFn, Function &NewFn)
Replace OldFn in the call graph (and SCC) with NewFn.
LLVM_ABI void reanalyzeFunction(Function &Fn)
After an CGSCC pass changes a function in ways that affect the call graph, this method can be called ...
void initialize(LazyCallGraph &LCG, LazyCallGraph::SCC &SCC, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR)
Initializers for usage outside of a CGSCC pass, inside a CGSCC pass in the old and new pass manager (...
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setTailCall(bool IsTc=true)
A constant value that is initialized with an expression using other constant values.
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
static bool shouldExecute(CounterInfo &Counter)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
A proxy from a FunctionAnalysisManager to an SCC.
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
const BasicBlock & getEntryBlock() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
iterator_range< arg_iterator > args()
DISubprogram * getSubprogram() const
Get the attached subprogram.
MemoryEffects getMemoryEffects() const
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
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.
Type * getReturnType() const
Returns the type of the ret val.
void setMemoryEffects(MemoryEffects ME)
Argument * getArg(unsigned i) const
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
@ DefaultVisibility
The GV is visible.
void setVisibility(VisibilityTypes V)
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ InternalLinkage
Rename collisions when linking (static functions).
LLVM_ABI void copyProfileAndDebugMetadata(const Instruction &SrcInst)
Copy debug, profile, and memprof metadata from SrcInst to this instruction without copying alias-anal...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
A node in the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
An instruction for reading from memory.
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool doesAccessArgPointees() const
Whether this function may access argument memory.
static MemoryEffectsBase unknown()
static LLVM_ABI MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
static LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
A Module instance is used to store all the information related to an LLVM module.
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
The must-be-executed context of a program point, as returned by MustBeExecutedContextExplorer::getCon...
PointerIntPair - This class implements a pair of a pointer and small integer.
void * getOpaqueValue() const
PointerTy getPointer() const
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Return a value (possibly void), from a function.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
A vector that has set insertion semantics.
ArrayRef< value_type > getArrayRef() const
bool remove(const value_type &X)
Remove an item from the set vector.
size_type size() const
Determine the number of elements in the SetVector.
void reserve(size_type Size)
Reserve space in the SetVector if supported by the underlying containers.
void insert_range(Range &&R)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
typename vector_type::const_iterator iterator
void clear()
Completely clear the SetVector.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
A visitor class for IR positions.
LLVM_ABI SubsumingPositionIterator(const IRPosition &IRP)
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isVoidTy() const
Return true if this is 'void'.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
iterator insert(iterator where, pointer New)
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
LLVM_ABI bool isAssumedReadNone(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readnone.
LLVM_ABI bool isAssumedReadOnly(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readonly.
LLVM_ABI std::optional< Value * > combineOptionalValuesInAAValueLatice(const std::optional< Value * > &A, const std::optional< Value * > &B, Type *Ty)
Return the combination of A and B such that the result is a possible value of both.
LLVM_ABI bool isValidAtPosition(const ValueAndContext &VAC, InformationCache &InfoCache)
Return true if the value of VAC is a valid at the position of VAC, that is a constant,...
LLVM_ABI bool isAssumedThreadLocalObject(Attributor &A, Value &Obj, const AbstractAttribute &QueryingAA)
Return true if Obj is assumed to be a thread local object.
LLVM_ABI bool isGPUConstantAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU constant address space for the target triple...
LLVM_ABI bool isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA, const Value &V, bool ForAnalysisOnly=true)
Return true if V is dynamically unique, that is, there are no two "instances" of V at runtime with di...
LLVM_ABI bool getPotentialCopiesOfStoredValue(Attributor &A, StoreInst &SI, SmallSetVector< Value *, 4 > &PotentialCopies, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values of the one stored by SI into PotentialCopies.
LLVM_ABI bool isGPUSharedAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU shared address space for the target triple i...
LLVM_ABI Constant * getInitialValueForObj(Attributor &A, const AbstractAttribute &QueryingAA, Value &Obj, Type &Ty, const DataLayout &DL, RangeTy *RangePtr=nullptr)
Return the initial value of Obj with type Ty if that is a constant.
LLVM_ABI bool isGPULocalAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU local/private address space for the target t...
LLVM_ABI bool isPotentiallyAffectedByBarrier(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is potentially affected by a barrier.
SmallPtrSet< Instruction *, 4 > InstExclusionSetTy
LLVM_ABI bool isGPU(const Module &M)
Return true iff M target a GPU (and we can use GPU AS reasoning).
ValueScope
Flags to distinguish intra-procedural queries from potentially inter-procedural queries.
LLVM_ABI bool isValidInScope(const Value &V, const Function *Scope)
Return true if V is a valid value in Scope, that is a constant or an instruction/argument of Scope.
LLVM_ABI bool isPotentiallyReachable(Attributor &A, const Instruction &FromI, const Instruction &ToI, const AbstractAttribute &QueryingAA, const AA::InstExclusionSetTy *ExclusionSet=nullptr, std::function< bool(const Function &F)> GoBackwardsCB=nullptr)
Return true if ToI is potentially reachable from FromI without running into any instruction in Exclus...
LLVM_ABI bool isNoSyncInst(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is a nosync instruction.
bool hasAssumedIRAttr(Attributor &A, const AbstractAttribute *QueryingAA, const IRPosition &IRP, DepClassTy DepClass, bool &IsKnown, bool IgnoreSubsumingPositions=false, const AAType **AAPtr=nullptr)
Helper to avoid creating an AA for IR Attributes that might already be set.
LLVM_ABI bool getPotentiallyLoadedValues(Attributor &A, LoadInst &LI, SmallSetVector< Value *, 4 > &PotentialValues, SmallSetVector< Instruction *, 4 > &PotentialValueOrigins, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values LI could read into PotentialValues.
LLVM_ABI Value * getWithType(Value &V, Type &Ty)
Try to convert V to type Ty without introducing new instructions.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ BasicBlock
Various leaf nodes.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
LLVM_ABI 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...
RelativeUniformCounterPtr Values
APInt operator&(APInt a, const APInt &b)
LLVM_ABI void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
DenseMap< AssumeInst *, MinMax > Assume2KnowledgeMap
A mapping from intrinsics (=llvm.assume calls) to a value range (=knowledge) that is encoded in them.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool isa_and_nonnull(const Y &Val)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
LLVM_ABI InlineResult isInlineViable(Function &Callee)
Check if it is mechanically possible to inline the function Callee, based on the contents of the func...
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
LLVM_ABI bool shouldCreateAbstractAttribute()
Check the debug counter used to limit the number of AAs created.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
const IPOOptions & getIPOOptions(const LLVMContext &C)
LLVM_ABI 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.
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
PotentialValuesState< std::pair< AA::ValueAndContext, AA::ValueScope > > PotentialLLVMValuesState
@ Force
Turn off window algorithm.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
@ Success
The lock was released successfully.
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
PotentialValuesState< APInt > PotentialConstantIntValuesState
bool operator&=(SparseBitVector< ElementSize > *LHS, const SparseBitVector< ElementSize > &RHS)
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
LLVM_ABI bool isAllocationFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI 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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI void fillMapFromAssume(AssumeInst &Assume, RetainedKnowledgeMap &Result)
Insert into the map all the informations contained in the operand bundles of the llvm....
constexpr bool valueOr(BoolOrDefault X, bool Default)
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
@ OPTIONAL
The target may be valid if the source is not.
@ NONE
Do not track a dependence between source and target.
@ REQUIRED
The target cannot be valid if the source is not.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
APInt operator|(APInt a, const APInt &b)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
An abstract state for querying live call edges.
An abstract Attribute for specializing "dynamic" components of denormal_fpenv to a known denormal mod...
DepSetTy Deps
Set of dependency graph nodes which should be updated if this one is updated.
PointerIntPair< AADepGraphNode *, 1 > DepTy
The data structure for the dependency graph.
LLVM_ABI void viewGraph()
AADepGraphNode SyntheticRoot
There is no root node for the dependency graph.
LLVM_ABI void print()
Print dependency graph.
LLVM_ABI void dumpGraph(StringRef DotFileNamePrefix)
Dump graph to file.
AADepGraphNode * GetEntryNode()
An abstract interface to track if a value leaves it's defining function instance.
bool isAssumedUniqueForAnalysis() const
Return true if we assume that the underlying value is unique in its scope wrt.
An abstract Attribute for computing reachability between functions.
An abstract interface to determine reachability of point A to B.
An abstract interface for liveness abstract attribute.
virtual bool isKnownDead() const =0
Returns true if the underlying value is known dead.
virtual bool isAssumedDead() const =0
The query functions are protected such that other attributes need to go through the Attributor interf...
virtual bool isRemovableStore() const
Return true if the underlying value is a store that is known to be removable.
static bool mayCatchAsynchronousExceptions(const Function &F)
Determine if F might catch asynchronous exceptions.
An abstract interface for memory access kind related attributes (readnone/readonly/writeonly).
An abstract interface for all memory location attributes (readnone/argmemonly/inaccessiblememonly/ina...
An abstract interface for all nonnull attributes.
An abstract interface for all nocapture attributes.
An AbstractAttribute for nofree.
An abstract attribute for norecurse.
An AbstractAttribute for noreturn.
static LLVM_ABI bool isNonRelaxedAtomic(const Instruction *I)
Helper function used to determine whether an instruction is non-relaxed atomic.
An abstract interface for all nonnull attributes.
bool isWrittenValueUnknown() const
Return true if the value written cannot be determined at all.
std::optional< Value * > getContent() const
Return the written value which can be llvm::null if it is not yet determined.
bool isWriteOrAssumption() const
Return true if this is a write access.
bool isRead() const
Return true if this is a read access.
Value * getWrittenValue() const
Return the value writen, if any.
Instruction * getLocalInst() const
Return the instruction that causes the access with respect to the local scope of the associated attri...
Instruction * getRemoteInst() const
Return the actual instruction that causes the access.
bool isWrittenValueYetUndetermined() const
Return true if the value written is not known yet.
AccessKind getKind() const
Return the access kind.
An abstract interface for struct information.
static LLVM_ABI Value * getSingleValue(Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP, SmallVectorImpl< AA::ValueAndContext > &Values)
Extract the single value in Values if any.
An abstract attribute for getting all assumption underlying objects.
An abstract attribute for willreturn.
Helper to represent an access offset and size, with logic to deal with uncertainty and check for over...
bool offsetOrSizeAreUnknown() const
Return true if offset or size are unknown.
const Instruction * getCtxI() const
Base struct for all "concrete attribute" deductions.
ChangeStatus update(Attributor &A)
Hook for the Attributor to trigger an update of the internal state.
friend struct Attributor
}
virtual void printWithDeps(raw_ostream &OS) const
virtual bool isStateAtFixpoint() const
Return true if the state is at a fixpoint, like getState().isAtFixpoint() but with a single virtual c...
void print(raw_ostream &OS) const
Helper functions, for debug purposes only.
virtual StateType & getState()=0
Return the internal abstract state for inspection.
virtual const std::string getAsStr(Attributor *A) const =0
This function should return the "summarized" assumed state as string.
virtual bool isQueryAA() const
A query AA is always scheduled as long as we do updates because it does lazy computation that cannot ...
virtual ChangeStatus updateImpl(Attributor &A)=0
The actual update/transfer function which has to be implemented by the derived classes.
const IRPosition & getIRPosition() const
Return an IR position, see struct IRPosition.
An interface to query the internal state of an abstract attribute.
virtual ChangeStatus indicatePessimisticFixpoint()=0
Indicate that the abstract state should converge to the pessimistic state.
virtual bool isAtFixpoint() const =0
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
virtual bool isValidState() const =0
Return if this abstract state is in a valid state.
Wrapper for FunctionAnalysisManager.
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
void populateAll() const
Force populate the entire call graph.
Configuration for the Attributor.
std::optional< unsigned > MaxFixpointIterations
Maximum number of iterations to run until fixpoint.
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Helper struct used in the communication between an abstract attribute (AA) that wants to change the s...
std::function< void( const ArgumentReplacementInfo &, Function &, Function::arg_iterator)> CalleeRepairCBTy
Callee repair callback type.
std::function< void(const ArgumentReplacementInfo &, AbstractCallSite, SmallVectorImpl< Value * > &)> ACSRepairCBTy
Abstract call site (ACS) repair callback type.
The fixpoint analysis framework that orchestrates the attribute deduction.
LLVM_ABI bool registerFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type * > ReplacementTypes, ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB)
Register a rewrite for a function signature.
LLVM_ABI bool checkForAllCallees(function_ref< bool(ArrayRef< const Function * > Callees)> Pred, const AbstractAttribute &QueryingAA, const CallBase &CB)
Check Pred on all potential Callees of CB.
bool isModulePass() const
Return true if this is a module pass, false otherwise.
LLVM_ABI bool isValidFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type * > ReplacementTypes)
Check if we can rewrite a function signature.
static LLVM_ABI bool isInternalizable(Function &F)
Returns true if the function F can be internalized.
LLVM_ABI ChangeStatus removeAttrs(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AttrKinds)
Remove all AttrKinds attached to IRP.
void emitRemark(Instruction *I, StringRef RemarkName, RemarkCallBack &&RemarkCB) const
Emit a remark generically.
bool isRunOn(Function &Fn) const
Return true if we derive attributes for Fn.
LLVM_ABI bool isAssumedDead(const AbstractAttribute &AA, const AAIsDead *LivenessAA, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, DepClassTy DepClass=DepClassTy::OPTIONAL)
Return true if AA (or its context instruction) is assumed dead.
LLVM_ABI void recordDependence(const AbstractAttribute &FromAA, const AbstractAttribute &ToAA, DepClassTy DepClass)
Explicitly record a dependence from FromAA to ToAA, that is if FromAA changes ToAA should be updated ...
static LLVM_ABI void createShallowWrapper(Function &F)
Create a shallow wrapper for F such that F has internal linkage afterwards.
LLVM_ABI bool checkForAllInstructions(function_ref< bool(Instruction &)> Pred, const Function *Fn, const AbstractAttribute *QueryingAA, ArrayRef< unsigned > Opcodes, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, bool IncludeAssumedDead=false)
Check Pred on all instructions in Fn with an opcode present in Opcodes.
const AAType * getAAFor(const AbstractAttribute &QueryingAA, const IRPosition &IRP, DepClassTy DepClass)
Lookup an abstract attribute of type AAType at position IRP.
std::optional< Value * > getAssumedSimplified(const IRPosition &IRP, const AbstractAttribute &AA, bool &UsedAssumedInformation, AA::ValueScope S)
If V is assumed simplified, return it, if it is unclear yet, return std::nullopt, otherwise return nu...
static LLVM_ABI Function * internalizeFunction(Function &F, bool Force=false)
Make another copy of the function F such that the copied version has internal linkage afterwards and ...
bool isFunctionIPOAmendable(const Function &F)
Determine whether the function F is IPO amendable.
const AAType * getOrCreateAAFor(IRPosition IRP, const AbstractAttribute *QueryingAA, DepClassTy DepClass, bool ForceUpdate=false, bool UpdateAfterInit=true)
The version of getAAFor that allows to omit a querying abstract attribute.
LLVM_ABI bool checkForAllReadWriteInstructions(function_ref< bool(Instruction &)> Pred, AbstractAttribute &QueryingAA, bool &UsedAssumedInformation)
Check Pred on all Read/Write instructions.
LLVM_ABI bool checkForAllReturnedValues(function_ref< bool(Value &)> Pred, const AbstractAttribute &QueryingAA, AA::ValueScope S=AA::ValueScope::Intraprocedural, bool RecurseForSelectAndPHI=true)
Check Pred on all values potentially returned by the function associated with QueryingAA.
LLVM_ABI bool isClosedWorldModule() const
Return true if the module contains the whole world, thus, no outside functions exist.
LLVM_ABI std::optional< Constant * > getAssumedConstant(const IRPosition &IRP, const AbstractAttribute &AA, bool &UsedAssumedInformation)
If IRP is assumed to be a constant, return it, if it is unclear yet, return std::nullopt,...
LLVM_ABI Attributor(SetVector< Function * > &Functions, InformationCache &InfoCache, AttributorConfig Configuration)
Constructor.
LLVM_ABI void getAttrs(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AKs, SmallVectorImpl< Attribute > &Attrs, bool IgnoreSubsumingPositions=false)
Return the attributes of any kind in AKs existing in the IR at a position that will affect this one.
InformationCache & getInfoCache()
Return the internal information cache.
LLVM_ABI std::optional< Value * > translateArgumentToCallSiteContent(std::optional< Value * > V, CallBase &CB, const AbstractAttribute &AA, bool &UsedAssumedInformation)
Translate V from the callee context into the call site context.
LLVM_ABI bool checkForAllUses(function_ref< bool(const Use &, bool &)> Pred, const AbstractAttribute &QueryingAA, const Value &V, bool CheckBBLivenessOnly=false, DepClassTy LivenessDepClass=DepClassTy::OPTIONAL, bool IgnoreDroppableUses=true, function_ref< bool(const Use &OldU, const Use &NewU)> EquivalentUseCB=nullptr)
Check Pred on all (transitive) uses of V.
LLVM_ABI ChangeStatus manifestAttrs(const IRPosition &IRP, ArrayRef< Attribute > DeducedAttrs, bool ForceReplace=false)
Attach DeducedAttrs to IRP, if ForceReplace is set we do this even if the same attribute kind was alr...
LLVM_ABI bool hasAttr(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AKs, bool IgnoreSubsumingPositions=false, Attribute::AttrKind ImpliedAttributeKind=Attribute::None)
Return true if any kind in AKs existing in the IR at a position that will affect this one.
bool canUseBodyFor(const IRPosition &IRP)
Return true if the body of the associated function can be used to derive information for IRP.
LLVM_ABI void registerForUpdate(AbstractAttribute &AA)
Allows a query AA to request an update if a new query was received.
const Module & getModule()
Return the module.
std::function< bool(Attributor &, const AbstractAttribute *)> VirtualUseCallbackTy
LLVM_ABI void identifyDefaultAbstractAttributes(Function &F)
Determine opportunities to derive 'default' attributes in F and create abstract attribute objects for...
LLVM_ABI bool getAssumedSimplifiedValues(const IRPosition &IRP, const AbstractAttribute *AA, SmallVectorImpl< AA::ValueAndContext > &Values, AA::ValueScope S, bool &UsedAssumedInformation, bool RecurseForSelectAndPHI=true)
Try to simplify IRP and in the scope S.
BumpPtrAllocator & Allocator
The allocator used to allocate memory, e.g. for AbstractAttributes.
LLVM_ABI ChangeStatus run()
Run the analyses until a fixpoint is reached or enforced (timeout).
static LLVM_ABI bool internalizeFunctions(SmallPtrSetImpl< Function * > &FnSet, DenseMap< Function *, Function * > &FnMap)
Make copies of each function in the set FnSet such that the copied version has internal linkage after...
LLVM_ABI bool checkForAllCallSites(function_ref< bool(AbstractCallSite)> Pred, const AbstractAttribute &QueryingAA, bool RequireAllCallSites, bool &UsedAssumedInformation)
Check Pred on all function call sites.
LLVM_ABI bool getAttrsFromAssumes(const IRPosition &IRP, Attribute::AttrKind AK, SmallVectorImpl< Attribute > &Attrs)
Return the attributes of kind AK existing in the IR as operand bundles of an llvm....
bool isKnown(base_t BitsEncoding=BestState) const
Return true if the bits set in BitsEncoding are "known bits".
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
static std::string getNodeLabel(const AADepGraphNode *Node, const AADepGraph *DG)
DOTGraphTraits(bool isSimple=false)
DefaultDOTGraphTraits(bool simple=false)
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ Dynamic
Denormals have unknown treatment.
static NodeRef DepGetVal(const DepTy &DT)
PointerIntPair< AADepGraphNode *, 1 > DepTy
static ChildIteratorType child_end(NodeRef N)
static NodeRef getEntryNode(AADepGraphNode *DGN)
mapped_iterator< AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)> ChildIteratorType
PointerIntPair< AADepGraphNode *, 1 > EdgeRef
static ChildIteratorType child_begin(NodeRef N)
AADepGraphNode::DepSetTy::iterator ChildEdgeIteratorType
static NodeRef getEntryNode(AADepGraph *DG)
mapped_iterator< AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)> nodes_iterator
static nodes_iterator nodes_begin(AADepGraph *DG)
static nodes_iterator nodes_end(AADepGraph *DG)
typename AADepGraph *::UnknownGraphTypeError NodeRef
Helper to describe and deal with positions in the LLVM-IR.
Function * getAssociatedFunction() const
Return the associated function, if any.
void setAttrList(const AttributeList &AttrList) const
Update the attributes associated with this function or call site scope.
unsigned getAttrIdx() const
Return the index in the attribute list for this position.
bool hasCallBaseContext() const
Check if the position has any call base context.
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
static const IRPosition returned(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the returned value of F.
LLVM_ABI Argument * getAssociatedArgument() const
Return the associated argument, if any.
static const IRPosition value(const Value &V, const CallBaseContext *CBContext=nullptr)
Create a position describing the value of V.
AttributeList getAttrList() const
Return the attributes associated with this function or call site scope.
static const IRPosition inst(const Instruction &I, const CallBaseContext *CBContext=nullptr)
Create a position describing the instruction I.
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
Kind
The positions we distinguish in the IR.
@ IRP_ARGUMENT
An attribute for a function argument.
@ IRP_RETURNED
An attribute for the function return value.
@ IRP_CALL_SITE
An attribute for a call site (function scope).
@ IRP_CALL_SITE_RETURNED
An attribute for a call site return value.
@ IRP_FUNCTION
An attribute for a function (scope).
@ IRP_FLOAT
A position that is not associated with a spot suitable for attributes.
@ IRP_CALL_SITE_ARGUMENT
An attribute for a call site argument.
@ IRP_INVALID
An invalid position.
Instruction * getCtxI() const
Return the context instruction, if any.
static const IRPosition argument(const Argument &Arg, const CallBaseContext *CBContext=nullptr)
Create a position describing the argument Arg.
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
const CallBaseContext * getCallBaseContext() const
Get the call base context from the position.
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
Value * getAttrListAnchor() const
Return the value attributes are attached to.
int getCallSiteArgNo() const
Return the call site argument number of the associated value if it is an argument or call site argume...
Kind getPositionKind() const
Return the associated position kind.
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
State for an integer range.
ConstantRange getKnown() const
Return the known state encoding.
ConstantRange getAssumed() const
Return the assumed state encoding.
uint32_t getBitWidth() const
Return associated values' bit width.
A "must be executed context" for a given program point PP is the set of instructions,...
LLVM_ABI Context getContext(const Instruction *PP)
Return the context of PP, to answer a batch of queries about it.
bool undefIsContained() const
Returns whether this state contains an undef value or not.
bool isValidState() const override
Return if this abstract state is in a valid state.
const SetTy & getAssumedSet() const
Return this set.