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");
71STATISTIC(NumFnDeleted,
"Number of function deleted");
73 "Number of functions with exact definitions");
75 "Number of functions without exact definitions");
76STATISTIC(NumFnShallowWrappersCreated,
"Number of shallow wrappers created");
78 "Number of abstract attributes timed out before fixpoint");
80 "Number of abstract attributes in a valid fixpoint state");
82 "Number of abstract attributes manifested in IR");
94 cl::desc(
"Maximal number of fixpoint iterations."),
100 cl::desc(
"Maximal number of callees specialized for "
105 "attributor-max-initialization-chain-length",
cl::Hidden,
107 "Maximal number of chained initializations (to avoid stack overflows)"),
113 cl::desc(
"Annotate call sites of function declarations."),
cl::init(
false));
120 cl::desc(
"Allow the Attributor to create shallow "
121 "wrappers for non-exact definitions."),
126 cl::desc(
"Allow the Attributor to use IP information "
127 "derived from non-exact functions via cloning"),
134 cl::desc(
"Comma separated list of attribute names that are "
135 "allowed to be seeded."),
139 "attributor-function-seed-allow-list",
cl::Hidden,
140 cl::desc(
"Comma separated list of function names that are "
141 "allowed to be seeded."),
147 cl::desc(
"Dump the dependency graph to dot files."),
151 "attributor-depgraph-dot-filename-prefix",
cl::Hidden,
152 cl::desc(
"The prefix used for the CallGraph dot file names."));
155 cl::desc(
"View the dependency graph."),
159 cl::desc(
"Print attribute dependencies"),
163 "attributor-enable-call-site-specific-deduction",
cl::Hidden,
164 cl::desc(
"Allow the Attributor to do call site specific analysis"),
169 cl::desc(
"Print Attributor's internal call graph"),
174 cl::desc(
"Try to simplify all loads."),
179 cl::desc(
"Should a closed world be assumed, or not. Default if not set."));
185 return L == ChangeStatus::CHANGED ? L : R;
192 return L == ChangeStatus::UNCHANGED ? L : R;
202 return T.isAMDGPU() ||
T.isNVPTX();
208 if (
const auto *CB = dyn_cast<CallBase>(&
I)) {
209 if (CB->hasFnAttr(Attribute::NoSync))
213 if (!CB->isConvergent() && !CB->mayReadOrWriteMemory())
220 return AA::hasAssumedIRAttr<Attribute::NoSync>(
222 DepClassTy::OPTIONAL, IsKnownNoSync);
225 if (!
I.mayReadOrWriteMemory())
232 const Value &V,
bool ForAnalysisOnly) {
234 if (!ForAnalysisOnly)
245 if (isa<AllocaInst>(Obj))
249 auto *GV = dyn_cast<GlobalVariable>(&Obj);
253 bool UsedAssumedInformation =
false;
255 if (
A.hasGlobalVariableSimplificationCallback(*GV)) {
256 auto AssumedGV =
A.getAssumedInitializerFromCallBack(
257 *GV, &QueryingAA, UsedAssumedInformation);
258 Initializer = *AssumedGV;
262 if (!GV->hasLocalLinkage() &&
263 (GV->isInterposable() || !(GV->isConstant() && GV->hasInitializer())))
265 if (!GV->hasInitializer())
269 Initializer = GV->getInitializer();
281 if (isa<Constant>(V))
283 if (
auto *
I = dyn_cast<Instruction>(&V))
284 return I->getFunction() == Scope;
285 if (
auto *
A = dyn_cast<Argument>(&V))
286 return A->getParent() == Scope;
292 if (isa<Constant>(VAC.getValue()) || VAC.getValue() == VAC.getCtxI())
298 if (
auto *
A = dyn_cast<Argument>(VAC.getValue()))
299 return A->getParent() == Scope;
300 if (
auto *
I = dyn_cast<Instruction>(VAC.getValue())) {
301 if (
I->getFunction() == Scope) {
307 if (CtxI &&
I->getParent() == CtxI->
getParent())
310 [&](
const Instruction &AfterI) { return &AfterI == CtxI; });
317 if (V.getType() == &Ty)
319 if (isa<PoisonValue>(V))
321 if (isa<UndefValue>(V))
323 if (
auto *
C = dyn_cast<Constant>(&V)) {
324 if (
C->isNullValue())
338std::optional<Value *>
340 const std::optional<Value *> &
B,
353 Ty = (*A)->getType();
354 if (isa_and_nonnull<UndefValue>(*
A))
356 if (isa<UndefValue>(*
B))
363template <
bool IsLoad,
typename Ty>
369 LLVM_DEBUG(
dbgs() <<
"Trying to determine the potential copies of " <<
I
370 <<
" (only exact: " << OnlyExact <<
")\n";);
381 A.getInfoCache().getTargetLibraryInfoForFunction(*
I.getFunction());
383 auto Pred = [&](
Value &Obj) {
385 if (isa<UndefValue>(&Obj))
387 if (isa<ConstantPointerNull>(&Obj)) {
391 Ptr.getType()->getPointerAddressSpace()) &&
392 A.getAssumedSimplified(
Ptr, QueryingAA, UsedAssumedInformation,
396 dbgs() <<
"Underlying object is a valid nullptr, giving up.\n";);
400 if (!isa<AllocaInst>(&Obj) && !isa<GlobalVariable>(&Obj) &&
402 LLVM_DEBUG(
dbgs() <<
"Underlying object is not supported yet: " << Obj
406 if (
auto *GV = dyn_cast<GlobalVariable>(&Obj))
407 if (!GV->hasLocalLinkage() &&
408 !(GV->isConstant() && GV->hasInitializer())) {
410 "linkage, not supported yet: "
415 bool NullOnly =
true;
416 bool NullRequired =
false;
417 auto CheckForNullOnlyAndUndef = [&](std::optional<Value *> V,
419 if (!V || *V ==
nullptr)
421 else if (isa<UndefValue>(*V))
423 else if (isa<Constant>(*V) && cast<Constant>(*V)->isNullValue())
424 NullRequired = !IsExact;
433 LLVM_DEBUG(
dbgs() <<
"Underlying object written but stored value "
434 "cannot be converted to read type: "
447 if (PotentialValueOrigins && !isa<AssumeInst>(Acc.
getRemoteInst()))
451 if (NewCopies.
count(V)) {
456 if (
Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand()))
457 if (NewCopies.
count(V)) {
470 CheckForNullOnlyAndUndef(Acc.
getContent(), IsExact);
471 if (OnlyExact && !IsExact && !NullOnly &&
477 if (NullRequired && !NullOnly) {
478 LLVM_DEBUG(
dbgs() <<
"Required all `null` accesses due to non exact "
479 "one, however found non-null one: "
484 assert(isa<LoadInst>(
I) &&
"Expected load or store instruction only!");
490 if (PotentialValueOrigins)
496 LLVM_DEBUG(
dbgs() <<
"Underlying object written through a non-store "
497 "instruction not supported yet: "
501 Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand());
505 if (PotentialValueOrigins)
506 NewCopyOrigins.
insert(SI);
508 assert(isa<StoreInst>(
I) &&
"Expected load or store instruction only!");
510 if (!LI && OnlyExact) {
512 "instruction not supported yet: "
523 bool HasBeenWrittenTo =
false;
528 if (!PI || !PI->forallInterferingAccesses(
531 !IsLoad, CheckAccess,
532 HasBeenWrittenTo,
Range, SkipCB)) {
535 <<
"Failed to verify all interfering accesses for underlying object: "
540 if (IsLoad && !HasBeenWrittenTo && !
Range.isUnassigned()) {
543 A, QueryingAA, Obj, *
I.getType(), TLI,
DL, &
Range);
545 LLVM_DEBUG(
dbgs() <<
"Could not determine required initial value of "
546 "underlying object, abort!\n");
549 CheckForNullOnlyAndUndef(InitialValue,
true);
550 if (NullRequired && !NullOnly) {
551 LLVM_DEBUG(
dbgs() <<
"Non exact access but initial value that is not "
552 "null or undef, abort!\n");
556 NewCopies.
insert(InitialValue);
557 if (PotentialValueOrigins)
558 NewCopyOrigins.
insert(
nullptr);
568 if (!AAUO || !AAUO->forallUnderlyingObjects(Pred)) {
570 dbgs() <<
"Underlying objects stored into could not be determined\n";);
577 for (
const auto *PI : PIs) {
578 if (!PI->getState().isAtFixpoint())
579 UsedAssumedInformation =
true;
580 A.recordDependence(*PI, QueryingAA, DepClassTy::OPTIONAL);
583 if (PotentialValueOrigins)
584 PotentialValueOrigins->
insert(NewCopyOrigins.
begin(), NewCopyOrigins.
end());
595 A, LI, PotentialValues, &PotentialValueOrigins, QueryingAA,
596 UsedAssumedInformation, OnlyExact);
604 A, SI, PotentialCopies,
nullptr, QueryingAA, UsedAssumedInformation,
610 bool RequireReadNone,
bool &IsKnown) {
611 if (RequireReadNone) {
612 if (AA::hasAssumedIRAttr<Attribute::ReadNone>(
613 A, &QueryingAA, IRP, DepClassTy::OPTIONAL, IsKnown,
616 }
else if (AA::hasAssumedIRAttr<Attribute::ReadOnly>(
617 A, &QueryingAA, IRP, DepClassTy::OPTIONAL, IsKnown,
623 const auto *MemLocAA =
625 if (MemLocAA && MemLocAA->isAssumedReadNone()) {
626 IsKnown = MemLocAA->isKnownReadNone();
628 A.recordDependence(*MemLocAA, QueryingAA, DepClassTy::OPTIONAL);
633 const auto *MemBehaviorAA =
636 (MemBehaviorAA->isAssumedReadNone() ||
637 (!RequireReadNone && MemBehaviorAA->isAssumedReadOnly()))) {
638 IsKnown = RequireReadNone ? MemBehaviorAA->isKnownReadNone()
639 : MemBehaviorAA->isKnownReadOnly();
641 A.recordDependence(*MemBehaviorAA, QueryingAA, DepClassTy::OPTIONAL);
664 std::function<
bool(
const Function &
F)> GoBackwardsCB) {
666 dbgs() <<
"[AA] isPotentiallyReachable @" << ToFn.
getName() <<
" from "
667 << FromI <<
" [GBCB: " <<
bool(GoBackwardsCB) <<
"][#ExS: "
668 << (ExclusionSet ? std::to_string(ExclusionSet->
size()) :
"none")
671 for (
auto *ES : *ExclusionSet)
672 dbgs() << *ES <<
"\n";
680 if (GoBackwardsCB && &ToFn != FromI.
getFunction() &&
683 LLVM_DEBUG(
dbgs() <<
"[AA] assume kernel cannot be reached from within the "
684 "module; success\n";);
693 if (!GoBackwardsCB && !ExclusionSet) {
695 <<
" is not checked backwards and does not have an "
696 "exclusion set, abort\n");
704 while (!Worklist.
empty()) {
706 if (!Visited.
insert(CurFromI).second)
710 if (FromFn == &ToFn) {
713 LLVM_DEBUG(
dbgs() <<
"[AA] check " << *ToI <<
" from " << *CurFromI
714 <<
" intraprocedurally\n");
717 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
718 A, *CurFromI, *ToI, ExclusionSet);
720 << (Result ?
"can potentially " :
"cannot ") <<
"reach "
721 << *ToI <<
" [Intra]\n");
731 Result = !ToReachabilityAA || ToReachabilityAA->isAssumedReachable(
732 A, EntryI, *ToI, ExclusionSet);
734 <<
" " << (Result ?
"can potentially " :
"cannot ")
735 <<
"reach @" << *ToI <<
" [ToFn]\n");
743 Result = !FnReachabilityAA || FnReachabilityAA->instructionCanReach(
744 A, *CurFromI, ToFn, ExclusionSet);
746 <<
" " << (Result ?
"can potentially " :
"cannot ")
747 <<
"reach @" << ToFn.
getName() <<
" [FromFn]\n");
756 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
757 A, *CurFromI, Ret, ExclusionSet);
759 << (Result ?
"can potentially " :
"cannot ") <<
"reach "
760 << Ret <<
" [Intra]\n");
765 bool UsedAssumedInformation =
false;
766 if (
A.checkForAllInstructions(ReturnInstCB, FromFn, &QueryingAA,
767 {Instruction::Ret}, UsedAssumedInformation)) {
772 if (!GoBackwardsCB) {
774 <<
" is not checked backwards, abort\n");
780 if (!GoBackwardsCB(*FromFn))
787 CallBase *CB = ACS.getInstruction();
791 if (isa<InvokeInst>(CB))
799 Result = !
A.checkForAllCallSites(CheckCallSite, *FromFn,
801 &QueryingAA, UsedAssumedInformation);
803 LLVM_DEBUG(
dbgs() <<
"[AA] stepping back to call sites from " << *CurFromI
804 <<
" in @" << FromFn->
getName()
805 <<
" failed, give up\n");
809 LLVM_DEBUG(
dbgs() <<
"[AA] stepped back to call sites from " << *CurFromI
810 <<
" in @" << FromFn->
getName()
811 <<
" worklist size is: " << Worklist.
size() <<
"\n");
820 std::function<
bool(
const Function &
F)> GoBackwardsCB) {
822 return ::isPotentiallyReachable(
A, FromI, &ToI, *ToFn, QueryingAA,
823 ExclusionSet, GoBackwardsCB);
830 std::function<
bool(
const Function &
F)> GoBackwardsCB) {
831 return ::isPotentiallyReachable(
A, FromI,
nullptr, ToFn, QueryingAA,
832 ExclusionSet, GoBackwardsCB);
837 if (isa<UndefValue>(Obj))
839 if (isa<AllocaInst>(Obj)) {
843 dbgs() <<
"[AA] Object '" << Obj
844 <<
"' is thread local; stack objects are thread local.\n");
847 bool IsKnownNoCapture;
848 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::NoCapture>(
852 << (IsAssumedNoCapture ?
"" :
"not") <<
" thread local; "
853 << (IsAssumedNoCapture ?
"non-" :
"")
854 <<
"captured stack object.\n");
855 return IsAssumedNoCapture;
857 if (
auto *GV = dyn_cast<GlobalVariable>(&Obj)) {
858 if (GV->isConstant()) {
860 <<
"' is thread local; constant global\n");
863 if (GV->isThreadLocal()) {
865 <<
"' is thread local; thread local global\n");
870 if (
A.getInfoCache().targetIsGPU()) {
872 (
int)AA::GPUAddressSpace::Local) {
874 <<
"' is thread local; GPU local memory\n");
878 (
int)AA::GPUAddressSpace::Constant) {
880 <<
"' is thread local; GPU constant memory\n");
885 LLVM_DEBUG(
dbgs() <<
"[AA] Object '" << Obj <<
"' is not thread local\n");
891 if (!
I.mayHaveSideEffects() && !
I.mayReadFromMemory())
896 auto AddLocationPtr = [&](std::optional<MemoryLocation> Loc) {
897 if (!Loc || !Loc->Ptr) {
899 dbgs() <<
"[AA] Access to unknown location; -> requires barriers\n");
928 auto Pred = [&](
Value &Obj) {
932 <<
"'; -> requires barrier\n");
938 if (!UnderlyingObjsAA || !UnderlyingObjsAA->forallUnderlyingObjects(Pred))
963 AB.addAttribute(Kind);
977 if (!ForceReplace && Kind == Attribute::Memory) {
981 AB.addMemoryAttr(ME);
988 AB.addAttribute(Attr);
1009 std::optional<Argument *> CBCandidateArg;
1013 for (
const Use *U : CallbackUses) {
1027 "ACS mapped into var-args arguments!");
1028 if (CBCandidateArg) {
1029 CBCandidateArg =
nullptr;
1037 if (CBCandidateArg && *CBCandidateArg)
1038 return *CBCandidateArg;
1042 auto *Callee = dyn_cast_if_present<Function>(CB.getCalledOperand());
1043 if (Callee && Callee->arg_size() >
unsigned(ArgNo))
1044 return Callee->getArg(ArgNo);
1058 LLVM_DEBUG(
dbgs() <<
"[Attributor] Update " << HasChanged <<
" " << *
this
1068 InfoCache(InfoCache), Configuration(Configuration) {
1072 if (Fn->hasAddressTaken(
nullptr,
1078 InfoCache.IndirectlyCallableFunctions.push_back(Fn);
1085 "Did expect a valid position!");
1102 unsigned AttrsSize = Attrs.size();
1105 for (
const auto &It : A2K)
1108 return AttrsSize != Attrs.size();
1111template <
typename DescTy>
1117 if (AttrDescs.
empty())
1129 auto It = AttrsMap.find(AttrListAnchor);
1130 if (It == AttrsMap.end())
1133 AL = It->getSecond();
1142 for (
const DescTy &AttrDesc : AttrDescs)
1143 if (CB(AttrDesc, AS, AM, AB))
1149 AL = AL.removeAttributesAtIndex(Ctx, AttrIdx, AM);
1150 AL = AL.addAttributesAtIndex(Ctx, AttrIdx, AB);
1151 AttrsMap[AttrListAnchor] = AL;
1157 bool IgnoreSubsumingPositions,
1159 bool Implied =
false;
1160 bool HasAttr =
false;
1163 if (AttrSet.hasAttribute(Kind)) {
1164 Implied |= Kind != ImpliedAttributeKind;
1170 updateAttrMap<Attribute::AttrKind>(EquivIRP, AttrKinds, HasAttrCB);
1176 if (IgnoreSubsumingPositions)
1193 ImpliedAttributeKind)});
1200 bool IgnoreSubsumingPositions) {
1204 if (AttrSet.hasAttribute(Kind))
1205 Attrs.push_back(AttrSet.getAttribute(Kind));
1209 updateAttrMap<Attribute::AttrKind>(EquivIRP, AttrKinds, CollectAttrCB);
1213 if (IgnoreSubsumingPositions)
1224 if (!AttrSet.hasAttribute(Kind))
1226 AM.addAttribute(Kind);
1229 return updateAttrMap<Attribute::AttrKind>(IRP, AttrKinds, RemoveAttrCB);
1236 if (!AttrSet.hasAttribute(Attr))
1238 AM.addAttribute(Attr);
1242 return updateAttrMap<StringRef>(IRP, Attrs, RemoveAttrCB);
1247 bool ForceReplace) {
1253 return updateAttrMap<Attribute>(IRP, Attrs, AddAttrCB);
1261 IRPositions.emplace_back(IRP);
1265 auto CanIgnoreOperandBundles = [](
const CallBase &CB) {
1266 return (isa<IntrinsicInst>(CB) &&
1267 cast<IntrinsicInst>(CB).getIntrinsicID() == Intrinsic ::assume);
1281 assert(CB &&
"Expected call site!");
1284 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
1285 if (
auto *Callee = dyn_cast_if_present<Function>(CB->getCalledOperand()))
1289 assert(CB &&
"Expected call site!");
1292 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1294 dyn_cast_if_present<Function>(CB->getCalledOperand())) {
1297 for (
const Argument &Arg : Callee->args())
1298 if (Arg.hasReturnedAttr()) {
1299 IRPositions.emplace_back(
1301 IRPositions.emplace_back(
1310 assert(CB &&
"Expected call site!");
1313 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1314 auto *Callee = dyn_cast_if_present<Function>(CB->getCalledOperand());
1327void IRPosition::verify() {
1328#ifdef EXPENSIVE_CHECKS
1331 assert((CBContext ==
nullptr) &&
1332 "Invalid position must not have CallBaseContext!");
1334 "Expected a nullptr for an invalid position!");
1338 "Expected specialized kind for argument values!");
1341 assert(isa<Function>(getAsValuePtr()) &&
1342 "Expected function for a 'returned' position!");
1344 "Associated value mismatch!");
1347 assert((CBContext ==
nullptr) &&
1348 "'call site returned' position must not have CallBaseContext!");
1349 assert((isa<CallBase>(getAsValuePtr())) &&
1350 "Expected call base for 'call site returned' position!");
1352 "Associated value mismatch!");
1355 assert((CBContext ==
nullptr) &&
1356 "'call site function' position must not have CallBaseContext!");
1357 assert((isa<CallBase>(getAsValuePtr())) &&
1358 "Expected call base for 'call site function' position!");
1360 "Associated value mismatch!");
1363 assert(isa<Function>(getAsValuePtr()) &&
1364 "Expected function for a 'function' position!");
1366 "Associated value mismatch!");
1369 assert(isa<Argument>(getAsValuePtr()) &&
1370 "Expected argument for a 'argument' position!");
1372 "Associated value mismatch!");
1375 assert((CBContext ==
nullptr) &&
1376 "'call site argument' position must not have CallBaseContext!");
1377 Use *U = getAsUsePtr();
1379 assert(U &&
"Expected use for a 'call site argument' position!");
1380 assert(isa<CallBase>(U->getUser()) &&
1381 "Expected call base user for a 'call site argument' position!");
1382 assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
1383 "Expected call base argument operand for a 'call site argument' "
1385 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
1387 "Argument number mismatch!");
1395std::optional<Constant *>
1398 bool &UsedAssumedInformation) {
1402 for (
auto &CB : SimplificationCallbacks.lookup(IRP)) {
1403 std::optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
1405 return std::nullopt;
1406 if (isa_and_nonnull<Constant>(*SimplifiedV))
1407 return cast<Constant>(*SimplifiedV);
1415 UsedAssumedInformation)) {
1417 return std::nullopt;
1418 if (
auto *
C = dyn_cast_or_null<Constant>(
1431 for (
auto &CB : SimplificationCallbacks.lookup(IRP))
1432 return CB(IRP, AA, UsedAssumedInformation);
1438 return std::nullopt;
1451 bool &UsedAssumedInformation,
bool RecurseForSelectAndPHI) {
1455 while (!Worklist.
empty()) {
1461 int NV = Values.
size();
1462 const auto &SimplificationCBs = SimplificationCallbacks.lookup(IRP);
1463 for (
const auto &CB : SimplificationCBs) {
1464 std::optional<Value *> CBResult = CB(IRP, AA, UsedAssumedInformation);
1465 if (!CBResult.has_value())
1467 Value *V = *CBResult;
1476 if (SimplificationCBs.empty()) {
1479 const auto *PotentialValuesAA =
1481 if (PotentialValuesAA && PotentialValuesAA->getAssumedSimplifiedValues(*
this, Values, S)) {
1482 UsedAssumedInformation |= !PotentialValuesAA->isAtFixpoint();
1491 if (!RecurseForSelectAndPHI)
1494 for (
int I = NV, E = Values.
size();
I < E; ++
I) {
1495 Value *V = Values[
I].getValue();
1496 if (!isa<PHINode>(V) && !isa<SelectInst>(V))
1498 if (!Seen.
insert(V).second)
1501 Values[
I] = Values[E - 1];
1515 bool &UsedAssumedInformation) {
1518 if (*V ==
nullptr || isa<Constant>(*V))
1520 if (
auto *Arg = dyn_cast<Argument>(*V))
1523 if (!Arg->hasPointeeInMemoryValueAttr())
1533 for (
auto &It : AAMap) {
1541 bool &UsedAssumedInformation,
1542 bool CheckBBLivenessOnly,
DepClassTy DepClass) {
1548 return isAssumedDead(IRP, &AA, FnLivenessAA, UsedAssumedInformation,
1549 CheckBBLivenessOnly, DepClass);
1555 bool &UsedAssumedInformation,
1556 bool CheckBBLivenessOnly,
DepClassTy DepClass) {
1559 Instruction *UserI = dyn_cast<Instruction>(U.getUser());
1562 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1564 if (
auto *CB = dyn_cast<CallBase>(UserI)) {
1567 if (CB->isArgOperand(&U)) {
1571 UsedAssumedInformation, CheckBBLivenessOnly,
1574 }
else if (
ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
1577 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1578 }
else if (
PHINode *
PHI = dyn_cast<PHINode>(UserI)) {
1581 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1582 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
1583 if (!CheckBBLivenessOnly && SI->getPointerOperand() != U.get()) {
1591 UsedAssumedInformation =
true;
1598 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1604 bool &UsedAssumedInformation,
1605 bool CheckBBLivenessOnly,
DepClassTy DepClass,
1606 bool CheckForDeadStore) {
1612 if (ManifestAddedBlocks.contains(
I.getParent()))
1621 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1625 if (CheckBBLivenessOnly ? FnLivenessAA->
isAssumedDead(
I.getParent())
1630 UsedAssumedInformation =
true;
1634 if (CheckBBLivenessOnly)
1642 if (!IsDeadAA || QueryingAA == IsDeadAA)
1649 UsedAssumedInformation =
true;
1657 UsedAssumedInformation =
true;
1667 bool &UsedAssumedInformation,
1668 bool CheckBBLivenessOnly,
DepClassTy DepClass) {
1680 isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
1685 if (CheckBBLivenessOnly)
1691 IsDeadAA = getOrCreateAAFor<AAIsDead>(
1698 if (!IsDeadAA || QueryingAA == IsDeadAA)
1705 UsedAssumedInformation =
true;
1724 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1740 return Pred(Callee);
1742 const auto *CallEdgesAA = getAAFor<AACallEdges>(
1744 if (!CallEdgesAA || CallEdgesAA->hasUnknownCallee())
1747 const auto &Callees = CallEdgesAA->getOptimisticEdges();
1748 return Pred(Callees.getArrayRef());
1752 return isa<PHINode>(Usr) || !isa<Instruction>(Usr);
1758 bool CheckBBLivenessOnly,
DepClassTy LivenessDepClass,
1759 bool IgnoreDroppableUses,
1764 if (!CB(*
this, &QueryingAA))
1775 auto AddUsers = [&](
const Value &V,
const Use *OldUse) {
1776 for (
const Use &UU : V.uses()) {
1777 if (OldUse && EquivalentUseCB && !EquivalentUseCB(*OldUse, UU)) {
1779 "rejected by the equivalence call back: "
1789 AddUsers(V,
nullptr);
1792 <<
" initial uses to check\n");
1795 const auto *LivenessAA =
1800 while (!Worklist.
empty()) {
1805 if (
auto *Fn = dyn_cast<Function>(U->getUser()))
1806 dbgs() <<
"[Attributor] Check use: " << **U <<
" in " << Fn->getName()
1809 dbgs() <<
"[Attributor] Check use: " << **U <<
" in " << *U->getUser()
1812 bool UsedAssumedInformation =
false;
1813 if (
isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation,
1814 CheckBBLivenessOnly, LivenessDepClass)) {
1816 dbgs() <<
"[Attributor] Dead use, skip!\n");
1819 if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
1821 dbgs() <<
"[Attributor] Droppable user, skip!\n");
1825 if (
auto *SI = dyn_cast<StoreInst>(U->getUser())) {
1826 if (&SI->getOperandUse(0) == U) {
1827 if (!Visited.
insert(U).second)
1831 *
this, *SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
1835 <<
"[Attributor] Value is stored, continue with "
1836 << PotentialCopies.
size()
1837 <<
" potential copies instead!\n");
1838 for (
Value *PotentialCopy : PotentialCopies)
1839 if (!AddUsers(*PotentialCopy, U))
1846 bool Follow =
false;
1847 if (!Pred(*U, Follow))
1852 User &Usr = *U->getUser();
1853 AddUsers(Usr,
nullptr);
1861 bool RequireAllCallSites,
1862 bool &UsedAssumedInformation) {
1868 if (!AssociatedFunction) {
1869 LLVM_DEBUG(
dbgs() <<
"[Attributor] No function associated with " << IRP
1875 &QueryingAA, UsedAssumedInformation);
1880 bool RequireAllCallSites,
1882 bool &UsedAssumedInformation,
1883 bool CheckPotentiallyDead) {
1887 <<
"[Attributor] Function " << Fn.
getName()
1888 <<
" has no internal linkage, hence not all call sites are known\n");
1893 if (!CB(*
this, QueryingAA))
1897 for (
unsigned u = 0; u <
Uses.size(); ++u) {
1900 if (
auto *Fn = dyn_cast<Function>(U))
1901 dbgs() <<
"[Attributor] Check use: " << Fn->
getName() <<
" in "
1902 << *U.getUser() <<
"\n";
1904 dbgs() <<
"[Attributor] Check use: " << *U <<
" in " << *U.getUser()
1907 if (!CheckPotentiallyDead &&
1908 isAssumedDead(U, QueryingAA,
nullptr, UsedAssumedInformation,
1911 dbgs() <<
"[Attributor] Dead use, skip!\n");
1914 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
1915 if (CE->isCast() && CE->getType()->isPointerTy()) {
1917 dbgs() <<
"[Attributor] Use, is constant cast expression, add "
1918 << CE->getNumUses() <<
" uses of that expression instead!\n";
1920 for (
const Use &CEU : CE->uses())
1921 Uses.push_back(&CEU);
1929 <<
" has non call site use " << *U.get() <<
" in "
1930 << *U.getUser() <<
"\n");
1932 if (isa<BlockAddress>(U.getUser()))
1937 const Use *EffectiveUse =
1940 if (!RequireAllCallSites) {
1941 LLVM_DEBUG(
dbgs() <<
"[Attributor] User " << *EffectiveUse->getUser()
1942 <<
" is not a call of " << Fn.
getName()
1946 LLVM_DEBUG(
dbgs() <<
"[Attributor] User " << *EffectiveUse->getUser()
1947 <<
" is an invalid use of " << Fn.
getName() <<
"\n");
1955 unsigned MinArgsParams =
1957 for (
unsigned u = 0; u < MinArgsParams; ++u) {
1961 dbgs() <<
"[Attributor] Call site / callee argument type mismatch ["
1962 << u <<
"@" << Fn.
getName() <<
": "
1972 LLVM_DEBUG(
dbgs() <<
"[Attributor] Call site callback failed for "
1980bool Attributor::shouldPropagateCallBaseContext(
const IRPosition &IRP) {
1990 bool RecurseForSelectAndPHI) {
1994 if (!AssociatedFunction)
1997 bool UsedAssumedInformation =
false;
2001 UsedAssumedInformation, RecurseForSelectAndPHI))
2005 return Pred(*VAC.getValue());
2013 bool &UsedAssumedInformation,
bool CheckBBLivenessOnly =
false,
2014 bool CheckPotentiallyDead =
false) {
2015 for (
unsigned Opcode : Opcodes) {
2017 auto *Insts = OpcodeInstMap.
lookup(Opcode);
2023 if (
A && !CheckPotentiallyDead &&
2025 UsedAssumedInformation, CheckBBLivenessOnly)) {
2027 dbgs() <<
"[Attributor] Instruction " << *
I
2028 <<
" is potentially dead, skip!\n";);
2043 bool &UsedAssumedInformation,
2044 bool CheckBBLivenessOnly,
2045 bool CheckPotentiallyDead) {
2051 const auto *LivenessAA =
2052 CheckPotentiallyDead && QueryingAA
2058 LivenessAA, Opcodes, UsedAssumedInformation,
2059 CheckBBLivenessOnly, CheckPotentiallyDead))
2068 bool &UsedAssumedInformation,
2069 bool CheckBBLivenessOnly,
2070 bool CheckPotentiallyDead) {
2074 UsedAssumedInformation, CheckBBLivenessOnly,
2075 CheckPotentiallyDead);
2080 bool &UsedAssumedInformation) {
2083 const Function *AssociatedFunction =
2085 if (!AssociatedFunction)
2089 const auto *LivenessAA =
2096 UsedAssumedInformation))
2106void Attributor::runTillFixpoint() {
2110 <<
" abstract attributes.\n");
2115 unsigned IterationCounter = 1;
2116 unsigned MaxIterations =
2126 LLVM_DEBUG(
dbgs() <<
"\n\n[Attributor] #Iteration: " << IterationCounter
2127 <<
", Worklist size: " << Worklist.
size() <<
"\n");
2132 for (
unsigned u = 0; u < InvalidAAs.
size(); ++u) {
2137 dbgs() <<
"[Attributor] InvalidAA: " << *InvalidAA
2138 <<
" has " << InvalidAA->
Deps.
size()
2139 <<
" required & optional dependences\n");
2140 for (
auto &DepIt : InvalidAA->
Deps) {
2144 dbgs() <<
" - recompute: " << *DepAA);
2149 <<
" - invalidate: " << *DepAA);
2153 InvalidAAs.
insert(DepAA);
2163 for (
auto &DepIt : ChangedAA->Deps)
2164 Worklist.
insert(cast<AbstractAttribute>(DepIt.getPointer()));
2165 ChangedAA->Deps.clear();
2168 LLVM_DEBUG(
dbgs() <<
"[Attributor] #Iteration: " << IterationCounter
2169 <<
", Worklist+Dependent size: " << Worklist.
size()
2179 const auto &AAState = AA->getState();
2180 if (!AAState.isAtFixpoint())
2182 ChangedAAs.push_back(AA);
2186 if (!AAState.isValidState())
2198 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
2199 Worklist.insert(QueryAAsAwaitingUpdate.begin(),
2200 QueryAAsAwaitingUpdate.end());
2201 QueryAAsAwaitingUpdate.clear();
2203 }
while (!Worklist.empty() && (IterationCounter++ < MaxIterations));
2205 if (IterationCounter > MaxIterations && !Functions.
empty()) {
2207 return ORM <<
"Attributor did not reach a fixpoint after "
2208 <<
ore::NV(
"Iterations", MaxIterations) <<
" iterations.";
2211 emitRemark<OptimizationRemarkMissed>(
F,
"FixedPoint",
Remark);
2214 LLVM_DEBUG(
dbgs() <<
"\n[Attributor] Fixpoint iteration done after: "
2215 << IterationCounter <<
"/" << MaxIterations
2216 <<
" iterations\n");
2224 for (
unsigned u = 0;
u < ChangedAAs.size();
u++) {
2226 if (!Visited.
insert(ChangedAA).second)
2233 NumAttributesTimedOut++;
2236 for (
auto &DepIt : ChangedAA->
Deps)
2237 ChangedAAs.push_back(cast<AbstractAttribute>(DepIt.getPointer()));
2242 if (!Visited.
empty())
2243 dbgs() <<
"\n[Attributor] Finalized " << Visited.
size()
2244 <<
" abstract attributes.\n";
2250 "Non-query AAs should not be required to register for updates!");
2251 QueryAAsAwaitingUpdate.insert(&AA);
2258 unsigned NumManifested = 0;
2259 unsigned NumAtFixpoint = 0;
2283 bool UsedAssumedInformation =
false;
2295 LLVM_DEBUG(
dbgs() <<
"[Attributor] Manifest " << LocalChange <<
" : " << *AA
2298 ManifestChange = ManifestChange | LocalChange;
2304 (void)NumManifested;
2305 (void)NumAtFixpoint;
2306 LLVM_DEBUG(
dbgs() <<
"\n[Attributor] Manifested " << NumManifested
2307 <<
" arguments while " << NumAtFixpoint
2308 <<
" were in a valid fixpoint state\n");
2310 NumAttributesManifested += NumManifested;
2311 NumAttributesValidFixpoint += NumAtFixpoint;
2316 for (
unsigned u = 0; u < NumFinalAAs; ++u)
2320 errs() <<
"Unexpected abstract attribute: "
2321 << cast<AbstractAttribute>(DepIt->getPointer()) <<
" :: "
2322 << cast<AbstractAttribute>(DepIt->getPointer())
2324 .getAssociatedValue()
2328 "remain unchanged!");
2331 for (
auto &It : AttrsMap) {
2334 isa<Function>(It.getFirst())
2340 return ManifestChange;
2343void Attributor::identifyDeadInternalFunctions() {
2364 if (
F->hasLocalLinkage() && (
isModulePass() || !TLI->getLibFunc(*
F, LF)))
2368 bool FoundLiveInternal =
true;
2369 while (FoundLiveInternal) {
2370 FoundLiveInternal =
false;
2375 bool UsedAssumedInformation =
false;
2379 return ToBeDeletedFunctions.count(Callee) ||
2380 (Functions.count(Callee) &&
Callee->hasLocalLinkage() &&
2381 !LiveInternalFns.
count(Callee));
2383 *
F,
true,
nullptr, UsedAssumedInformation)) {
2389 FoundLiveInternal =
true;
2395 ToBeDeletedFunctions.insert(
F);
2402 << ToBeDeletedFunctions.size() <<
" functions and "
2403 << ToBeDeletedBlocks.size() <<
" blocks and "
2404 << ToBeDeletedInsts.size() <<
" instructions and "
2405 << ToBeChangedValues.size() <<
" values and "
2406 << ToBeChangedUses.size() <<
" uses. To insert "
2407 << ToBeChangedToUnreachableInsts.size()
2408 <<
" unreachables.\n"
2409 <<
"Preserve manifest added " << ManifestAddedBlocks.size()
2415 auto ReplaceUse = [&](
Use *
U,
Value *NewV) {
2420 const auto &
Entry = ToBeChangedValues.lookup(NewV);
2423 NewV = get<0>(Entry);
2428 "Cannot replace an instruction outside the current SCC!");
2432 if (
auto *RI = dyn_cast_or_null<ReturnInst>(
I)) {
2434 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
2438 if (!isa<Argument>(NewV))
2439 for (
auto &Arg : RI->getFunction()->args())
2440 Arg.removeAttr(Attribute::Returned);
2444 <<
" instead of " << *OldV <<
"\n");
2448 CGModifiedFunctions.insert(
I->getFunction());
2449 if (!isa<PHINode>(
I) && !ToBeDeletedInsts.count(
I) &&
2453 if (isa<UndefValue>(NewV) && isa<CallBase>(
U->getUser())) {
2454 auto *CB = cast<CallBase>(
U->getUser());
2455 if (CB->isArgOperand(U)) {
2456 unsigned Idx = CB->getArgOperandNo(U);
2457 CB->removeParamAttr(
Idx, Attribute::NoUndef);
2458 auto *
Callee = dyn_cast_if_present<Function>(CB->getCalledOperand());
2460 Callee->removeParamAttr(
Idx, Attribute::NoUndef);
2463 if (isa<Constant>(NewV) && isa<BranchInst>(
U->getUser())) {
2465 if (isa<UndefValue>(NewV)) {
2466 ToBeChangedToUnreachableInsts.insert(UserI);
2473 for (
auto &It : ToBeChangedUses) {
2475 Value *NewV = It.second;
2476 ReplaceUse(U, NewV);
2480 for (
auto &It : ToBeChangedValues) {
2481 Value *OldV = It.first;
2482 auto [NewV,
Done] = It.second;
2484 for (
auto &U : OldV->
uses())
2485 if (
Done || !
U.getUser()->isDroppable())
2488 if (
auto *
I = dyn_cast<Instruction>(
U->getUser()))
2491 ReplaceUse(U, NewV);
2495 for (
const auto &V : InvokeWithDeadSuccessor)
2496 if (
InvokeInst *
II = dyn_cast_or_null<InvokeInst>(V)) {
2498 "Cannot replace an invoke outside the current SCC!");
2499 bool UnwindBBIsDead =
II->hasFnAttr(Attribute::NoUnwind);
2500 bool NormalBBIsDead =
II->hasFnAttr(Attribute::NoReturn);
2501 bool Invoke2CallAllowed =
2503 assert((UnwindBBIsDead || NormalBBIsDead) &&
2504 "Invoke does not have dead successors!");
2507 if (UnwindBBIsDead) {
2509 if (Invoke2CallAllowed) {
2514 ToBeChangedToUnreachableInsts.insert(NormalNextIP);
2516 assert(NormalBBIsDead &&
"Broken invariant!");
2519 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->
front());
2524 "Cannot replace a terminator outside the current SCC!");
2525 CGModifiedFunctions.insert(
I->getFunction());
2528 for (
const auto &V : ToBeChangedToUnreachableInsts)
2529 if (
Instruction *
I = dyn_cast_or_null<Instruction>(V)) {
2533 "Cannot replace an instruction outside the current SCC!");
2534 CGModifiedFunctions.insert(
I->getFunction());
2538 for (
const auto &V : ToBeDeletedInsts) {
2539 if (
Instruction *
I = dyn_cast_or_null<Instruction>(V)) {
2540 assert((!isa<CallBase>(
I) || isa<IntrinsicInst>(
I) ||
2542 "Cannot delete an instruction outside the current SCC!");
2543 I->dropDroppableUses();
2544 CGModifiedFunctions.insert(
I->getFunction());
2545 if (!
I->getType()->isVoidTy())
2550 I->eraseFromParent();
2557 dbgs() <<
"[Attributor] DeadInsts size: " << DeadInsts.
size() <<
"\n";
2558 for (
auto &
I : DeadInsts)
2560 dbgs() <<
" - " << *
I <<
"\n";
2565 if (
unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
2567 ToBeDeletedBBs.
reserve(NumDeadBlocks);
2570 "Cannot delete a block outside the current SCC!");
2571 CGModifiedFunctions.insert(BB->
getParent());
2573 if (ManifestAddedBlocks.contains(BB))
2583 identifyDeadInternalFunctions();
2586 ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
2588 for (
Function *Fn : CGModifiedFunctions)
2589 if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn))
2592 for (
Function *Fn : ToBeDeletedFunctions) {
2593 if (!Functions.count(Fn))
2598 if (!ToBeChangedUses.empty())
2601 if (!ToBeChangedToUnreachableInsts.empty())
2604 if (!ToBeDeletedFunctions.empty())
2607 if (!ToBeDeletedBlocks.empty())
2610 if (!ToBeDeletedInsts.empty())
2613 if (!InvokeWithDeadSuccessor.empty())
2616 if (!DeadInsts.empty())
2619 NumFnDeleted += ToBeDeletedFunctions.size();
2621 LLVM_DEBUG(
dbgs() <<
"[Attributor] Deleted " << ToBeDeletedFunctions.size()
2622 <<
" functions after manifest.\n");
2624#ifdef EXPENSIVE_CHECKS
2626 if (ToBeDeletedFunctions.count(
F))
2632 return ManifestChange;
2642 Phase = AttributorPhase::UPDATE;
2655 Phase = AttributorPhase::MANIFEST;
2658 Phase = AttributorPhase::CLEANUP;
2664 return ManifestChange | CleanupChange;
2671 assert(Phase == AttributorPhase::UPDATE &&
2672 "We can update AA only in the update stage!");
2675 DependenceVector DV;
2676 DependenceStack.push_back(&DV);
2680 bool UsedAssumedInformation =
false;
2692 RerunCS = AA.
update(*
this);
2698 AAState.indicateOptimisticFixpoint();
2701 if (!AAState.isAtFixpoint())
2702 rememberDependences();
2706 DependenceVector *PoppedDV = DependenceStack.pop_back_val();
2708 assert(PoppedDV == &DV &&
"Inconsistent usage of the dependence stack!");
2714 assert(!
F.isDeclaration() &&
"Cannot create a wrapper around a declaration!");
2723 M.getFunctionList().insert(
F.getIterator(),
Wrapper);
2725 Wrapper->IsNewDbgInfoFormat = M.IsNewDbgInfoFormat;
2730 assert(
F.use_empty() &&
"Uses remained after wrapper was created!");
2735 F.setComdat(
nullptr);
2739 F.getAllMetadata(MDs);
2740 for (
auto MDIt : MDs)
2741 Wrapper->addMetadata(MDIt.first, *MDIt.second);
2742 Wrapper->setAttributes(
F.getAttributes());
2750 Args.push_back(&Arg);
2751 Arg.setName((FArgIt++)->
getName());
2759 NumFnShallowWrappersCreated++;
2763 if (
F.isDeclaration() ||
F.hasLocalLinkage() ||
2779 return InternalizedFns[&
F];
2797 F->getName() +
".internalized");
2800 for (
auto &Arg :
F->args()) {
2802 NewFArgIt->setName(ArgName);
2803 VMap[&Arg] = &(*NewFArgIt++);
2820 F->getAllMetadata(MDs);
2821 for (
auto MDIt : MDs)
2825 M.getFunctionList().insert(
F->getIterator(), Copied);
2833 auto &InternalizedFn = FnMap[
F];
2834 auto IsNotInternalized = [&](
Use &U) ->
bool {
2835 if (
auto *CB = dyn_cast<CallBase>(U.getUser()))
2836 return !FnMap.
lookup(CB->getCaller());
2839 F->replaceUsesWithIf(InternalizedFn, IsNotInternalized);
2860 if (cast<CallBase>(ACS.
getInstruction())->getCalledOperand()->getType() !=
2871 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite var-args functions\n");
2882 dbgs() <<
"[Attributor] Cannot rewrite due to complex attribute\n");
2887 bool UsedAssumedInformation =
false;
2889 UsedAssumedInformation,
2891 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite all call sites\n");
2896 if (
auto *CI = dyn_cast<CallInst>(&
I))
2897 return !CI->isMustTailCall();
2905 nullptr, {Instruction::Call},
2906 UsedAssumedInformation)) {
2907 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite due to instructions\n");
2918 LLVM_DEBUG(
dbgs() <<
"[Attributor] Register new rewrite of " << Arg <<
" in "
2920 << ReplacementTypes.
size() <<
" replacements\n");
2922 "Cannot register an invalid rewrite");
2926 ArgumentReplacementMap[Fn];
2932 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.
getArgNo()];
2933 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.
size()) {
2934 LLVM_DEBUG(
dbgs() <<
"[Attributor] Existing rewrite is preferred\n");
2942 LLVM_DEBUG(
dbgs() <<
"[Attributor] Register new rewrite of " << Arg <<
" in "
2944 << ReplacementTypes.
size() <<
" replacements\n");
2948 std::move(CalleeRepairCB),
2949 std::move(ACSRepairCB)));
2970 for (
auto &It : ArgumentReplacementMap) {
2974 if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
2987 if (
const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2988 ARIs[Arg.getArgNo()]) {
2989 NewArgumentTypes.
append(ARI->ReplacementTypes.begin(),
2990 ARI->ReplacementTypes.end());
2991 NewArgumentAttributes.
append(ARI->getNumReplacementArgs(),
2994 NewArgumentTypes.
push_back(Arg.getType());
3001 for (
auto *
I : NewArgumentTypes)
3002 if (
auto *VT = dyn_cast<llvm::VectorType>(
I))
3003 LargestVectorWidth =
3004 std::max(LargestVectorWidth,
3005 VT->getPrimitiveSizeInBits().getKnownMinValue());
3016 << *NewFnTy <<
"\n");
3021 Functions.insert(NewFn);
3037 NewArgumentAttributes));
3046 return !
T->isPtrOrPtrVectorTy() ||
3060 if (
auto *BA = dyn_cast<BlockAddress>(U))
3062 for (
auto *BA : BlockAddresses)
3077 for (
unsigned OldArgNum = 0; OldArgNum < ARIs.
size(); ++OldArgNum) {
3078 unsigned NewFirstArgNum = NewArgOperands.
size();
3079 (void)NewFirstArgNum;
3080 if (
const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3082 if (ARI->ACSRepairCB)
3083 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
3084 assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
3085 NewArgOperands.
size() &&
3086 "ACS repair callback did not provide as many operand as new "
3087 "types were registered!");
3089 NewArgOperandAttributes.
append(ARI->ReplacementTypes.size(),
3098 assert(NewArgOperands.
size() == NewArgOperandAttributes.
size() &&
3099 "Mismatch # argument operands vs. # argument operand attributes!");
3101 "Mismatch # argument operands vs. # function arguments!");
3110 II->getUnwindDest(), NewArgOperands,
3115 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
3120 NewCB->
copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
3125 OldCallAttributeList.
getRetAttrs(), NewArgOperandAttributes));
3128 LargestVectorWidth);
3130 CallSitePairs.
push_back({OldCB, NewCB});
3135 bool UsedAssumedInformation =
false;
3137 true,
nullptr, UsedAssumedInformation,
3140 assert(
Success &&
"Assumed call site replacement to succeed!");
3145 for (
unsigned OldArgNum = 0; OldArgNum < ARIs.
size();
3146 ++OldArgNum, ++OldFnArgIt) {
3147 if (
const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3149 if (ARI->CalleeRepairCB)
3150 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
3151 if (ARI->ReplacementTypes.empty())
3154 NewFnArgIt += ARI->ReplacementTypes.size();
3156 NewFnArgIt->
takeName(&*OldFnArgIt);
3163 for (
auto &CallSitePair : CallSitePairs) {
3164 CallBase &OldCB = *CallSitePair.first;
3165 CallBase &NewCB = *CallSitePair.second;
3167 "Cannot handle call sites with different types!");
3178 if (ModifiedFns.
remove(OldFn))
3179 ModifiedFns.
insert(NewFn);
3187void InformationCache::initializeInformationCache(
const Function &CF,
3203 auto AddToAssumeUsesMap = [&](
const Value &
V) ->
void {
3205 if (
auto *
I = dyn_cast<Instruction>(&V))
3207 while (!Worklist.
empty()) {
3209 std::optional<short> &NumUses = AssumeUsesMap[
I];
3211 NumUses =
I->getNumUses();
3212 NumUses = *NumUses - 1;
3215 AssumeOnlyValues.insert(
I);
3216 for (
const Value *
Op :
I->operands())
3217 if (
auto *OpI = dyn_cast<Instruction>(
Op))
3223 bool IsInterestingOpcode =
false;
3230 switch (
I.getOpcode()) {
3233 "New call base instruction type needs to be known in the "
3236 case Instruction::Call:
3240 if (
auto *Assume = dyn_cast<AssumeInst>(&
I)) {
3241 AssumeOnlyValues.insert(Assume);
3243 AddToAssumeUsesMap(*
Assume->getArgOperand(0));
3244 }
else if (cast<CallInst>(
I).isMustTailCall()) {
3245 FI.ContainsMustTailCall =
true;
3246 if (
auto *Callee = dyn_cast_if_present<Function>(
3247 cast<CallInst>(
I).getCalledOperand()))
3248 getFunctionInfo(*Callee).CalledViaMustTail =
true;
3251 case Instruction::CallBr:
3252 case Instruction::Invoke:
3253 case Instruction::CleanupRet:
3254 case Instruction::CatchSwitch:
3255 case Instruction::AtomicRMW:
3256 case Instruction::AtomicCmpXchg:
3257 case Instruction::Br:
3258 case Instruction::Resume:
3259 case Instruction::Ret:
3260 case Instruction::Load:
3262 case Instruction::Store:
3264 case Instruction::Alloca:
3265 case Instruction::AddrSpaceCast:
3266 IsInterestingOpcode =
true;
3268 if (IsInterestingOpcode) {
3269 auto *&Insts = FI.OpcodeInstMap[
I.getOpcode()];
3274 if (
I.mayReadOrWriteMemory())
3275 FI.RWInsts.push_back(&
I);
3278 if (
F.hasFnAttribute(Attribute::AlwaysInline) &&
3280 InlineableFunctions.insert(&
F);
3283InformationCache::FunctionInfo::~FunctionInfo() {
3286 for (
auto &It : OpcodeInstMap)
3287 It.getSecond()->~InstructionVectorTy();
3292 assert(
A.isClosedWorldModule() &&
"Cannot see all indirect callees!");
3293 return IndirectlyCallableFunctions;
3299 return std::nullopt;
3310 if (DependenceStack.empty())
3314 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
3317void Attributor::rememberDependences() {
3318 assert(!DependenceStack.empty() &&
"No dependences to remember!");
3320 for (DepInfo &DI : *DependenceStack.back()) {
3323 "Expected required or optional dependence (1 bit)!");
3330template <Attribute::AttrKind AK,
typename AAType>
3331void Attributor::checkAndQueryIRAttr(
const IRPosition &IRP,
3334 if (!
Attrs.hasAttribute(AK))
3338 getOrCreateAAFor<AAType>(IRP);
3342 if (!VisitedFunctions.insert(&
F).second)
3344 if (
F.isDeclaration())
3350 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(
F);
3352 for (
const Use &U :
F.uses())
3353 if (
const auto *CB = dyn_cast<CallBase>(U.getUser()))
3354 if (CB->isCallee(&U) && CB->isMustTailCall())
3355 FI.CalledViaMustTail =
true;
3360 auto Attrs =
F.getAttributes();
3361 auto FnAttrs = Attrs.getFnAttrs();
3366 getOrCreateAAFor<AAIsDead>(FPos);
3370 getOrCreateAAFor<AAUndefinedBehavior>(FPos);
3374 getOrCreateAAFor<AAHeapToStack>(FPos);
3377 checkAndQueryIRAttr<Attribute::MustProgress, AAMustProgress>(FPos, FnAttrs);
3380 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(FPos, FnAttrs);
3383 checkAndQueryIRAttr<Attribute::WillReturn, AAWillReturn>(FPos, FnAttrs);
3386 checkAndQueryIRAttr<Attribute::NoSync, AANoSync>(FPos, FnAttrs);
3391 if (IsIPOAmendable) {
3394 checkAndQueryIRAttr<Attribute::NoUnwind, AANoUnwind>(FPos, FnAttrs);
3397 checkAndQueryIRAttr<Attribute::NoReturn, AANoReturn>(FPos, FnAttrs);
3400 checkAndQueryIRAttr<Attribute::NoRecurse, AANoRecurse>(FPos, FnAttrs);
3403 if (Attrs.hasFnAttr(Attribute::Convergent))
3404 getOrCreateAAFor<AANonConvergent>(FPos);
3407 getOrCreateAAFor<AAMemoryBehavior>(FPos);
3410 getOrCreateAAFor<AAMemoryLocation>(FPos);
3413 getOrCreateAAFor<AAAssumptionInfo>(FPos);
3421 getOrCreateAAFor<AADenormalFPMath>(FPos);
3424 Type *ReturnType =
F.getReturnType();
3425 if (!ReturnType->isVoidTy()) {
3430 getOrCreateAAFor<AAIsDead>(RetPos);
3433 bool UsedAssumedInformation =
false;
3438 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(RetPos, RetAttrs);
3440 if (ReturnType->isPointerTy()) {
3443 getOrCreateAAFor<AAAlign>(RetPos);
3446 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(RetPos, RetAttrs);
3449 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(RetPos, RetAttrs);
3453 getOrCreateAAFor<AADereferenceable>(RetPos);
3455 getOrCreateAAFor<AANoFPClass>(RetPos);
3462 auto ArgNo = Arg.getArgNo();
3465 if (!IsIPOAmendable) {
3466 if (Arg.getType()->isPointerTy())
3468 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(ArgPos, ArgAttrs);
3475 bool UsedAssumedInformation =
false;
3480 getOrCreateAAFor<AAIsDead>(ArgPos);
3483 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(ArgPos, ArgAttrs);
3485 if (Arg.getType()->isPointerTy()) {
3487 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(ArgPos, ArgAttrs);
3490 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(ArgPos, ArgAttrs);
3493 getOrCreateAAFor<AADereferenceable>(ArgPos);
3496 getOrCreateAAFor<AAAlign>(ArgPos);
3499 checkAndQueryIRAttr<Attribute::NoCapture, AANoCapture>(ArgPos, ArgAttrs);
3503 getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
3506 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(ArgPos, ArgAttrs);
3510 getOrCreateAAFor<AAPrivatizablePtr>(ArgPos);
3512 getOrCreateAAFor<AANoFPClass>(ArgPos);
3517 auto &CB = cast<CallBase>(
I);
3523 getOrCreateAAFor<AAIsDead>(CBInstPos);
3525 Function *Callee = dyn_cast_if_present<Function>(CB.getCalledOperand());
3529 getOrCreateAAFor<AAIndirectCallInfo>(CBFnPos);
3534 getOrCreateAAFor<AAAssumptionInfo>(CBFnPos);
3539 !Callee->hasMetadata(LLVMContext::MD_callback))
3542 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
3544 bool UsedAssumedInformation =
false;
3549 getOrCreateAAFor<AANoFPClass>(CBInstPos);
3553 for (
int I = 0, E = CB.arg_size();
I < E; ++
I) {
3559 getOrCreateAAFor<AAIsDead>(CBArgPos);
3564 bool UsedAssumedInformation =
false;
3569 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(CBArgPos, CBArgAttrs);
3571 Type *ArgTy = CB.getArgOperand(
I)->getType();
3575 getOrCreateAAFor<AANoFPClass>(CBArgPos);
3581 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(CBArgPos, CBArgAttrs);
3584 checkAndQueryIRAttr<Attribute::NoCapture, AANoCapture>(CBArgPos,
3588 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(CBArgPos, CBArgAttrs);
3591 getOrCreateAAFor<AADereferenceable>(CBArgPos);
3594 getOrCreateAAFor<AAAlign>(CBArgPos);
3599 getOrCreateAAFor<AAMemoryBehavior>(CBArgPos);
3602 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(CBArgPos, CBArgAttrs);
3608 [[maybe_unused]]
bool Success;
3609 bool UsedAssumedInformation =
false;
3611 nullptr, OpcodeInstMap, CallSitePred,
nullptr,
nullptr,
3612 {(
unsigned)Instruction::Invoke, (
unsigned)Instruction::CallBr,
3614 UsedAssumedInformation);
3615 assert(
Success &&
"Expected the check call to be successful!");
3618 if (
auto *LI = dyn_cast<LoadInst>(&
I)) {
3623 getOrCreateAAFor<AAAddressSpace>(
3626 auto &SI = cast<StoreInst>(
I);
3631 getOrCreateAAFor<AAAddressSpace>(
3637 nullptr, OpcodeInstMap, LoadStorePred,
nullptr,
nullptr,
3638 {(
unsigned)Instruction::Load, (
unsigned)Instruction::Store},
3639 UsedAssumedInformation);
3640 assert(
Success &&
"Expected the check call to be successful!");
3643 auto AAAllocationInfoPred = [&](
Instruction &
I) ->
bool {
3649 nullptr, OpcodeInstMap, AAAllocationInfoPred,
nullptr,
nullptr,
3650 {(
unsigned)Instruction::Alloca}, UsedAssumedInformation);
3651 assert(
Success &&
"Expected the check call to be successful!");
3674 return OS <<
"fn_ret";
3676 return OS <<
"cs_ret";
3684 return OS <<
"cs_arg";
3706 return OS << static_cast<const AbstractState &>(S);
3720 OS <<
"set-state(< {";
3736 OS <<
"set-state(< {";
3741 if (
auto *
F = dyn_cast<Function>(It.first.getValue()))
3742 OS <<
"@" <<
F->getName() <<
"[" << int(It.second) <<
"], ";
3744 OS << *It.first.getValue() <<
"[" << int(It.second) <<
"], ";
3757 OS <<
"] for CtxI ";
3764 OS <<
"<<null inst>>";
3773 for (
const auto &DepAA :
Deps) {
3774 auto *AA = DepAA.getPointer();
3791 OS <<
" [ <unknown> ]";
3805 bool DeleteFns,
bool IsModulePass) {
3806 if (Functions.
empty())
3810 dbgs() <<
"[Attributor] Run on module with " << Functions.
size()
3819 AC.IsModulePass = IsModulePass;
3820 AC.DeleteFns = DeleteFns;
3824 IndirectCalleeTrackingMap;
3826 AC.IndirectCalleeSpecializationCallback =
3831 auto &Set = IndirectCalleeTrackingMap[&CB];
3833 Set = std::make_unique<SmallPtrSet<Function *, 8>>();
3835 return Set->contains(&Callee);
3836 Set->insert(&Callee);
3846 if (!
A.isFunctionIPOAmendable(*
F))
3854 unsigned FunSize = Functions.
size();
3855 for (
unsigned u = 0; u < FunSize; u++) {
3857 if (!
F->isDeclaration() && !
F->isDefinitionExact() &&
F->getNumUses() &&
3860 assert(NewF &&
"Could not internalize function.");
3865 for (
const Use &U : NewF->
uses())
3866 if (
CallBase *CB = dyn_cast<CallBase>(U.getUser())) {
3867 auto *CallerF = CB->getCaller();
3875 if (
F->hasExactDefinition())
3876 NumFnWithExactDefinition++;
3878 NumFnWithoutExactDefinition++;
3883 if (
F->hasLocalLinkage()) {
3885 const auto *CB = dyn_cast<CallBase>(U.getUser());
3886 return CB && CB->isCallee(&U) &&
3887 Functions.count(const_cast<Function *>(CB->getCaller()));
3894 A.identifyDefaultAbstractAttributes(*
F);
3900 <<
" functions, result: " << Changed <<
".\n");
3909 bool IsModulePass) {
3910 if (Functions.
empty())
3914 dbgs() <<
"[AttributorLight] Run on module with " << Functions.
size()
3923 AC.IsModulePass = IsModulePass;
3924 AC.DeleteFns =
false;
3931 AC.Allowed = &Allowed;
3932 AC.UseLiveness =
false;
3937 if (
F->hasExactDefinition())
3938 NumFnWithExactDefinition++;
3940 NumFnWithoutExactDefinition++;
3945 if (AC.UseLiveness &&
F->hasLocalLinkage()) {
3947 const auto *CB = dyn_cast<CallBase>(U.getUser());
3948 return CB && CB->isCallee(&U) &&
3949 Functions.count(const_cast<Function *>(CB->getCaller()));
3956 A.identifyDefaultAbstractAttributes(*
F);
3967 for (
Function *Changed :
A.getModifiedFunctions()) {
3973 for (
auto *U : Changed->users()) {
3974 if (
auto *Call = dyn_cast<CallBase>(U)) {
3975 if (Call->getCalledFunction() == Changed)
3982 <<
" functions, result: " << Changed <<
".\n");
3989 static std::atomic<int> CallTimes;
3995 Prefix =
"dep_graph";
3996 std::string Filename =
3997 Prefix +
"_" + std::to_string(CallTimes.load()) +
".dot";
3999 outs() <<
"Dependency graph dump to " << Filename <<
".\n";
4012 cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(
outs());
4045 Functions.
insert(&
N.getFunction());
4047 if (Functions.
empty())
4101 Functions.
insert(&
N.getFunction());
4103 if (Functions.
empty())
4158 std::string AAString;
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...
static cl::opt< bool > AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden, cl::desc("Allow the Attributor to create shallow " "wrappers for non-exact definitions."), cl::init(false))
bool canMarkAsVisited(const User *Usr)
#define VERBOSE_DEBUG_TYPE
static cl::opt< bool > EnableHeapToStack("enable-heap-to-stack-conversion", cl::init(true), cl::Hidden)
static cl::list< std::string > SeedAllowList("attributor-seed-allow-list", cl::Hidden, cl::desc("Comma separated list of attribute names that are " "allowed to be seeded."), cl::CommaSeparated)
static bool runAttributorOnFunctions(InformationCache &InfoCache, SetVector< Function * > &Functions, AnalysisGetter &AG, CallGraphUpdater &CGUpdater, bool DeleteFns, bool IsModulePass)
}
static bool isPotentiallyReachable(Attributor &A, const Instruction &FromI, const Instruction *ToI, const Function &ToFn, const AbstractAttribute &QueryingAA, const AA::InstExclusionSetTy *ExclusionSet, std::function< bool(const Function &F)> GoBackwardsCB)
static bool getPotentialCopiesOfMemoryValue(Attributor &A, Ty &I, SmallSetVector< Value *, 4 > &PotentialCopies, SmallSetVector< Instruction *, 4 > *PotentialValueOrigins, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact)
static bool runAttributorLightOnFunctions(InformationCache &InfoCache, SetVector< Function * > &Functions, AnalysisGetter &AG, CallGraphUpdater &CGUpdater, FunctionAnalysisManager &FAM, bool IsModulePass)
static cl::opt< unsigned, true > MaxInitializationChainLengthX("attributor-max-initialization-chain-length", cl::Hidden, cl::desc("Maximal number of chained initializations (to avoid stack overflows)"), cl::location(MaxInitializationChainLength), cl::init(1024))
static cl::opt< unsigned > MaxSpecializationPerCB("attributor-max-specializations-per-call-base", cl::Hidden, cl::desc("Maximal number of callees specialized for " "a call base"), cl::init(UINT32_MAX))
static cl::opt< bool > SimplifyAllLoads("attributor-simplify-all-loads", cl::Hidden, cl::desc("Try to simplify all loads."), cl::init(true))
static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, AttributeSet AttrSet, bool ForceReplace, AttrBuilder &AB)
Return true if the information provided by Attr was added to the attribute set AttrSet.
static cl::opt< bool > ViewDepGraph("attributor-view-dep-graph", cl::Hidden, cl::desc("View the dependency graph."), cl::init(false))
static bool isEqualOrWorse(const Attribute &New, const Attribute &Old)
Return true if New is equal or worse than Old.
static cl::opt< bool > AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden, cl::desc("Allow the Attributor to use IP information " "derived from non-exact functions via cloning"), cl::init(false))
static cl::opt< bool > DumpDepGraph("attributor-dump-dep-graph", cl::Hidden, cl::desc("Dump the dependency graph to dot files."), cl::init(false))
static cl::opt< bool > PrintCallGraph("attributor-print-call-graph", cl::Hidden, cl::desc("Print Attributor's internal call graph"), cl::init(false))
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 CheckPotentiallyDead=false)
static cl::opt< bool > PrintDependencies("attributor-print-dep", cl::Hidden, cl::desc("Print attribute dependencies"), cl::init(false))
static bool isAssumedReadOnlyOrReadNone(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool RequireReadNone, bool &IsKnown)
static cl::opt< std::string > DepGraphDotFileNamePrefix("attributor-depgraph-dot-filename-prefix", cl::Hidden, cl::desc("The prefix used for the CallGraph dot file names."))
static cl::opt< bool > AnnotateDeclarationCallSites("attributor-annotate-decl-cs", cl::Hidden, cl::desc("Annotate call sites of function declarations."), cl::init(false))
static cl::opt< unsigned > SetFixpointIterations("attributor-max-iterations", cl::Hidden, cl::desc("Maximal number of fixpoint iterations."), cl::init(32))
static cl::list< std::string > FunctionSeedAllowList("attributor-function-seed-allow-list", cl::Hidden, cl::desc("Comma separated list of function names that are " "allowed to be seeded."), cl::CommaSeparated)
static cl::opt< bool > EnableCallSiteSpecific("attributor-enable-call-site-specific-deduction", cl::Hidden, cl::desc("Allow the Attributor to do call site specific analysis"), cl::init(false))
static cl::opt< bool > CloseWorldAssumption("attributor-assume-closed-world", cl::Hidden, cl::desc("Should a closed world be assumed, or not. Default if not set."))
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
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...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
static Function * getFunction(Constant *C)
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
FunctionAnalysisManager FAM
This file defines the PointerIntPair class.
static StringRef getName(Value *V)
Remove Loads Into Fake Uses
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isSimple(Instruction *I)
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)
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 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 <a particular IR unit>" (e....
A container for analyses that lazily runs them and caches their results.
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
MemoryEffects getMemoryEffects() const
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
bool isEnumAttribute() const
Return true if the attribute is an Attribute::AttrKind type.
bool isIntAttribute() const
Return true if the attribute is an integer attribute.
uint64_t getValueAsInt() const
Return the attribute's value as an integer.
StringRef getKindAsString() const
Return the attribute's kind as a string.
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
MemoryEffects getMemoryEffects() const
Returns memory effects.
StringRef getValueAsString() const
Return the attribute's value as a string.
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 Instruction & front() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Allocate memory in an ever growing pool, as if by bump-pointer.
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.
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
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.
Function * getCaller()
Helper to get the caller (the parent function).
Wrapper to unify "old style" CallGraph and "new style" LazyCallGraph.
void removeFunction(Function &Fn)
Remove Fn from the call graph.
void replaceFunctionWith(Function &OldFn, Function &NewFn)
Replace OldFn in the call graph (and SCC) with NewFn.
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 Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
void print(raw_ostream &OS) const
Print out the bounds to a stream.
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
static bool shouldExecute(unsigned CounterName)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Implements a dense probed hash-table based set.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
A proxy from a FunctionAnalysisManager to an SCC.
Class to represent function types.
static 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.
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
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.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
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 value has any metadata attached to it.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
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).
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
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)
Create MemoryEffectsBase that can only access argument memory.
bool doesAccessArgPointees() const
Whether this function may access argument memory.
static MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
static 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).
PointerIntPair - This class implements a pair of a pointer and small integer.
void * getOpaqueValue() const
static 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.
void preserveSet()
Mark an analysis set as preserved.
void 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.
const value_type & front() const
Return the first element of the SetVector.
const value_type & back() const
Return the last element of the SetVector.
typename vector_type::const_iterator iterator
iterator end()
Get an iterator to the end of the SetVector.
void clear()
Completely clear the SetVector.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
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.
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.
StringRef - Represent a constant reference to a string, i.e.
A visitor class for IR positions.
SubsumingPositionIterator(const IRPosition &IRP)
Provides information about what library functions are available for the current target.
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.
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
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.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
static 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.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< use_iterator > uses()
StringRef getName() const
Return a constant reference to the value's name.
void takeName(Value *V)
Transfer the name from V to this value.
Value handle that is nullable, but tries to track the Value.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
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.
bool isAssumedReadNone(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readnone.
bool isAssumedReadOnly(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readonly.
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.
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,...
bool isAssumedThreadLocalObject(Attributor &A, Value &Obj, const AbstractAttribute &QueryingAA)
Return true if Obj is assumed to be a thread local object.
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...
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.
bool isPotentiallyAffectedByBarrier(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is potentially affected by a barrier.
bool isGPU(const Module &M)
Return true iff M target a GPU (and we can use GPU AS reasoning).
Constant * getInitialValueForObj(Attributor &A, const AbstractAttribute &QueryingAA, Value &Obj, Type &Ty, const TargetLibraryInfo *TLI, const DataLayout &DL, RangeTy *RangePtr=nullptr)
Return the initial value of Obj with type Ty if that is a constant.
ValueScope
Flags to distinguish intra-procedural queries from potentially inter-procedural queries.
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.
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...
bool isNoSyncInst(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is a nosync instruction.
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.
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.
bool isNoFPClassCompatibleType(Type *Ty)
Returns true if this is a type legal for the 'nofpclass' attribute.
void updateMinLegalVectorWidthAttr(Function &Fn, uint64_t Width)
Update min-legal-vector-width if it is in Attribute and less than Width.
@ C
The default llvm calling convention, compatible with C.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Assume
Do not drop type tests (default).
DiagnosticInfoOptimizationBase::Argument NV
@ 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.
Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
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.
unsigned MaxInitializationChainLength
The value passed to the line option that defines the maximal initialization chain length.
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...
APInt operator&(APInt a, const APInt &b)
void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
InlineResult isInlineViable(Function &Callee)
Minimal filter to detect invalid constructs for inlining.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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.
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...
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool AreStatisticsEnabled()
Check if statistics are enabled.
Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
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...
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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...
bool operator&=(SparseBitVector< ElementSize > *LHS, const SparseBitVector< ElementSize > &RHS)
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)
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 isAllocationFn(const Value *V, const TargetLibraryInfo *TLI)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void fillMapFromAssume(AssumeInst &Assume, RetainedKnowledgeMap &Result)
Insert into the map all the informations contained in the operand bundles of the llvm....
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
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.
APInt operator|(APInt a, const APInt &b)
static const char ID
Unique ID (due to the unique address)
DepSetTy Deps
Set of dependency graph nodes which should be updated if this one is updated.
The data structure for the dependency graph.
AADepGraphNode SyntheticRoot
There is no root node for the dependency graph.
void print()
Print dependency graph.
void dumpGraph()
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.
static const char ID
Unique ID (due to the unique address)
An abstract interface to determine reachability of point A to B.
static const char ID
Unique ID (due to the unique address)
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).
static const char ID
Unique ID (due to the unique address)
An abstract interface for all memory location attributes (readnone/argmemonly/inaccessiblememonly/ina...
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
static bool isNonRelaxedAtomic(const Instruction *I)
Helper function used to determine whether an instruction is non-relaxed atomic.
static bool isNoSyncIntrinsic(const Instruction *I)
Helper function specific for intrinsics which are potentially volatile.
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
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 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.
static const char ID
Unique ID (due to the unique address)
static const char ID
Unique ID (due to the unique address)
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.
static const fltSemantics & IEEEsingle() LLVM_READNONE
Base struct for all "concrete attribute" deductions.
ChangeStatus update(Attributor &A)
Hook for the Attributor to trigger an update of the internal state.
virtual ChangeStatus manifest(Attributor &A)
Hook for the Attributor to trigger the manifestation of the information represented by the abstract a...
virtual void printWithDeps(raw_ostream &OS) const
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 getName() const =0
This function should return the name of the AbstractAttribute.
virtual ~AbstractAttribute()=default
Virtual destructor.
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.
virtual void trackStatistics() const =0
Hook to enable custom statistic tracking, called after manifest that resulted in a change if statisti...
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.
virtual ChangeStatus indicateOptimisticFixpoint()=0
Indicate that the abstract state should converge to the optimistic state.
Wrapper for FunctionAnalysisManager.
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
void populateAll() const
Force populate the entire call graph.
Configuration for the Attributor.
bool UseLiveness
Flag to determine if we should skip all liveness checks early on.
std::optional< unsigned > MaxFixpointIterations
Maximum number of iterations to run until fixpoint.
DenseSet< const char * > * Allowed
If not null, a set limiting the attribute opportunities.
bool RewriteSignatures
Flag to determine if we rewrite function signatures.
bool DeleteFns
Flag to determine if we can delete functions or keep dead ones around.
bool IsClosedWorldModule
Flag to indicate if the entire world is contained in this module, that is, no outside functions exist...
CallGraphUpdater & CGUpdater
Helper to update an underlying call graph and to delete functions.
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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 &, AbstractCallSite, SmallVectorImpl< Value * > &)> ACSRepairCBTy
Abstract call site (ACS) repair callback type.
std::function< void(const ArgumentReplacementInfo &, Function &, Function::arg_iterator)> CalleeRepairCBTy
Callee repair callback type.
The fixpoint analysis framework that orchestrates the attribute deduction.
bool registerFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type * > ReplacementTypes, ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB)
Register a rewrite for a function signature.
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.
bool isValidFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type * > ReplacementTypes)
Check if we can rewrite a function signature.
static bool isInternalizable(Function &F)
Returns true if the function F can be internalized.
ChangeStatus removeAttrs(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AttrKinds)
Remove all AttrKinds attached to IRP.
bool isRunOn(Function &Fn) const
Return true if we derive attributes for Fn.
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.
bool checkForAllInstructions(function_ref< bool(Instruction &)> Pred, const Function *Fn, const AbstractAttribute *QueryingAA, ArrayRef< unsigned > Opcodes, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, bool CheckPotentiallyDead=false)
Check Pred on all instructions in Fn with an opcode present in Opcodes.
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 void createShallowWrapper(Function &F)
Create a shallow wrapper for F such that F has internal linkage afterwards.
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 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.
bool checkForAllReadWriteInstructions(function_ref< bool(Instruction &)> Pred, AbstractAttribute &QueryingAA, bool &UsedAssumedInformation)
Check Pred on all Read/Write instructions.
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.
bool isClosedWorldModule() const
Return true if the module contains the whole world, thus, no outside functions exist.
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,...
Attributor(SetVector< Function * > &Functions, InformationCache &InfoCache, AttributorConfig Configuration)
Constructor.
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.
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.
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.
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...
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.
void registerForUpdate(AbstractAttribute &AA)
Allows a query AA to request an update if a new query was received.
void identifyDefaultAbstractAttributes(Function &F)
Determine opportunities to derive 'default' attributes in F and create abstract attribute objects for...
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.
std::function< bool(Attributor &, const AbstractAttribute *)> VirtualUseCallbackTy
ChangeStatus run()
Run the analyses until a fixpoint is reached or enforced (timeout).
static 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...
bool checkForAllCallSites(function_ref< bool(AbstractCallSite)> Pred, const AbstractAttribute &QueryingAA, bool RequireAllCallSites, bool &UsedAssumedInformation)
Check Pred on all function call sites.
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)
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ Dynamic
Denormals have unknown treatment.
An information struct used to provide DenseMap with the various necessary components for a given valu...
static NodeRef DepGetVal(const DepTy &DT)
static ChildIteratorType child_end(NodeRef N)
static NodeRef getEntryNode(AADepGraphNode *DGN)
static ChildIteratorType child_begin(NodeRef N)
AADepGraphNode::DepSetTy::iterator ChildEdgeIteratorType
static NodeRef getEntryNode(AADepGraph *DG)
static nodes_iterator nodes_begin(AADepGraph *DG)
static nodes_iterator nodes_end(AADepGraph *DG)
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.
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.
static const IRPosition TombstoneKey
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 EmptyKey
Special DenseMap key values.
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,...
iterator & end()
Return an universal end iterator.
bool findInContextOf(const Instruction *I, const Instruction *PP)
Helper to look for I in the context of PP.
iterator & begin(const Instruction *PP)
Return an iterator to explore the context around PP.
bool undefIsContained() const
Returns whether this state contains an undef value or not.
bool isValidState() const override
See AbstractState::isValidState(...)
const SetTy & getAssumedSet() const
Return this set.