16#include "llvm/IR/IntrinsicsAMDGPU.h"
17#include "llvm/IR/IntrinsicsR600.h"
21#define DEBUG_TYPE "amdgpu-attributor"
26 "amdgpu-indirect-call-specialization-threshold",
28 "A threshold controls whether an indirect call will be specialized"),
31#define AMDGPU_ATTRIBUTE(Name, Str) Name##_POS,
34#include "AMDGPUAttributes.def"
38#define AMDGPU_ATTRIBUTE(Name, Str) Name = 1 << Name##_POS,
42#include "AMDGPUAttributes.def"
46#define AMDGPU_ATTRIBUTE(Name, Str) {Name, Str},
47static constexpr std::pair<ImplicitArgumentMask, StringLiteral>
49#include "AMDGPUAttributes.def"
59 bool HasApertureRegs,
bool SupportsGetDoorBellID,
60 unsigned CodeObjectVersion) {
62 case Intrinsic::amdgcn_workitem_id_x:
65 case Intrinsic::amdgcn_workgroup_id_x:
67 return WORKGROUP_ID_X;
68 case Intrinsic::amdgcn_workitem_id_y:
69 case Intrinsic::r600_read_tidig_y:
71 case Intrinsic::amdgcn_workitem_id_z:
72 case Intrinsic::r600_read_tidig_z:
74 case Intrinsic::amdgcn_workgroup_id_y:
75 case Intrinsic::r600_read_tgid_y:
76 return WORKGROUP_ID_Y;
77 case Intrinsic::amdgcn_workgroup_id_z:
78 case Intrinsic::r600_read_tgid_z:
79 return WORKGROUP_ID_Z;
80 case Intrinsic::amdgcn_cluster_id_x:
83 case Intrinsic::amdgcn_cluster_id_y:
85 case Intrinsic::amdgcn_cluster_id_z:
87 case Intrinsic::amdgcn_lds_kernel_id:
89 case Intrinsic::amdgcn_dispatch_ptr:
91 case Intrinsic::amdgcn_dispatch_id:
93 case Intrinsic::amdgcn_implicitarg_ptr:
94 return IMPLICIT_ARG_PTR;
97 case Intrinsic::amdgcn_queue_ptr:
100 case Intrinsic::amdgcn_is_shared:
101 case Intrinsic::amdgcn_is_private:
109 case Intrinsic::trap:
110 case Intrinsic::debugtrap:
111 case Intrinsic::ubsantrap:
112 if (SupportsGetDoorBellID)
136 return F.hasFnAttribute(Attribute::SanitizeAddress) ||
137 F.hasFnAttribute(Attribute::SanitizeThread) ||
138 F.hasFnAttribute(Attribute::SanitizeMemory) ||
139 F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
140 F.hasFnAttribute(Attribute::SanitizeMemTag);
146 AMDGPUInformationCache(
const Module &M, AnalysisGetter &AG,
148 SetVector<Function *> *
CGSCC, TargetMachine &TM)
154 enum ConstantStatus : uint8_t {
157 ADDR_SPACE_CAST_PRIVATE_TO_FLAT = 1 << 1,
158 ADDR_SPACE_CAST_LOCAL_TO_FLAT = 1 << 2,
159 ADDR_SPACE_CAST_BOTH_TO_FLAT =
160 ADDR_SPACE_CAST_PRIVATE_TO_FLAT | ADDR_SPACE_CAST_LOCAL_TO_FLAT
164 bool hasApertureRegs(Function &
F) {
165 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
166 return ST.hasApertureRegs();
170 bool supportsGetDoorbellID(Function &
F) {
171 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
172 return ST.supportsGetDoorbellID();
175 std::optional<std::pair<unsigned, unsigned>>
176 getFlatWorkGroupSizeAttr(
const Function &
F)
const {
180 return std::make_pair(
R->first, *(
R->second));
183 std::pair<unsigned, unsigned>
184 getDefaultFlatWorkGroupSize(
const Function &
F)
const {
185 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
186 return ST.getDefaultFlatWorkGroupSize(
F.getCallingConv());
189 std::pair<unsigned, unsigned>
190 getMaximumFlatWorkGroupRange(
const Function &
F) {
191 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
192 return {
ST.getMinFlatWorkGroupSize(),
ST.getMaxFlatWorkGroupSize()};
195 SmallVector<unsigned> getMaxNumWorkGroups(
const Function &
F) {
196 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
197 return ST.getMaxNumWorkGroups(
F);
201 unsigned getCodeObjectVersion()
const {
return CodeObjectVersion; }
206 std::pair<unsigned, unsigned>
207 getWavesPerEU(
const Function &
F,
208 std::pair<unsigned, unsigned> FlatWorkGroupSize) {
209 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
210 return ST.getWavesPerEU(FlatWorkGroupSize, getLDSSize(
F),
F);
213 std::optional<std::pair<unsigned, unsigned>>
214 getWavesPerEUAttr(
const Function &
F) {
220 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
221 Val->second =
ST.getMaxWavesPerEU();
223 return std::make_pair(Val->first, *(Val->second));
227 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
228 return ST.getMaxWavesPerEU();
231 unsigned getMaxAddrSpace()
const override {
238 static uint8_t visitConstExpr(
const ConstantExpr *CE) {
239 uint8_t Status = NONE;
241 if (
CE->getOpcode() == Instruction::AddrSpaceCast) {
242 unsigned SrcAS =
CE->getOperand(0)->getType()->getPointerAddressSpace();
244 Status |= ADDR_SPACE_CAST_PRIVATE_TO_FLAT;
246 Status |= ADDR_SPACE_CAST_LOCAL_TO_FLAT;
254 static unsigned getLDSSize(
const Function &
F) {
256 {0, UINT32_MAX},
true)
261 uint8_t getConstantAccess(
const Constant *
C,
262 SmallPtrSetImpl<const Constant *> &Visited) {
263 auto It = ConstantStatus.find(
C);
264 if (It != ConstantStatus.end())
272 Result |= visitConstExpr(CE);
274 for (
const Use &U :
C->operands()) {
276 if (!OpC || !Visited.
insert(OpC).second)
279 Result |= getConstantAccess(OpC, Visited);
286 bool needsQueuePtr(
const Constant *
C, Function &Fn) {
288 bool HasAperture = hasApertureRegs(Fn);
291 if (!IsNonEntryFunc && HasAperture)
294 SmallPtrSet<const Constant *, 8> Visited;
295 uint8_t
Access = getConstantAccess(
C, Visited);
298 if (IsNonEntryFunc && (
Access & DS_GLOBAL))
301 return !HasAperture && (
Access & ADDR_SPACE_CAST_BOTH_TO_FLAT);
304 bool checkConstForAddrSpaceCastFromPrivate(
const Constant *
C) {
305 SmallPtrSet<const Constant *, 8> Visited;
306 uint8_t
Access = getConstantAccess(
C, Visited);
307 return Access & ADDR_SPACE_CAST_PRIVATE_TO_FLAT;
312 DenseMap<const Constant *, uint8_t> ConstantStatus;
313 const unsigned CodeObjectVersion;
316struct AAAMDAttributes
317 :
public StateWrapper<BitIntegerState<uint32_t, ALL_ARGUMENT_MASK, 0>,
319 using Base = StateWrapper<BitIntegerState<uint32_t, ALL_ARGUMENT_MASK, 0>,
322 AAAMDAttributes(
const IRPosition &IRP, Attributor &
A) : Base(IRP) {}
325 static AAAMDAttributes &createForPosition(
const IRPosition &IRP,
329 StringRef
getName()
const override {
return "AAAMDAttributes"; }
332 const char *getIdAddr()
const override {
return &ID; }
336 static bool classof(
const AbstractAttribute *AA) {
341 static const char ID;
343const char AAAMDAttributes::ID = 0;
345struct AAUniformWorkGroupSize
346 :
public StateWrapper<BooleanState, AbstractAttribute> {
347 using Base = StateWrapper<BooleanState, AbstractAttribute>;
348 AAUniformWorkGroupSize(
const IRPosition &IRP, Attributor &
A) : Base(IRP) {}
351 static AAUniformWorkGroupSize &createForPosition(
const IRPosition &IRP,
355 StringRef
getName()
const override {
return "AAUniformWorkGroupSize"; }
358 const char *getIdAddr()
const override {
return &ID; }
362 static bool classof(
const AbstractAttribute *AA) {
367 static const char ID;
369const char AAUniformWorkGroupSize::ID = 0;
371struct AAUniformWorkGroupSizeFunction :
public AAUniformWorkGroupSize {
372 AAUniformWorkGroupSizeFunction(
const IRPosition &IRP, Attributor &
A)
373 : AAUniformWorkGroupSize(IRP,
A) {}
377 CallingConv::ID CC =
F->getCallingConv();
379 if (CC != CallingConv::AMDGPU_KERNEL)
382 bool InitialValue =
false;
383 if (
F->hasFnAttribute(
"uniform-work-group-size"))
385 F->getFnAttribute(
"uniform-work-group-size").getValueAsString() ==
389 indicateOptimisticFixpoint();
391 indicatePessimisticFixpoint();
397 auto CheckCallSite = [&](AbstractCallSite CS) {
400 <<
"->" << getAssociatedFunction()->
getName() <<
"\n");
402 const auto *CallerInfo =
A.getAAFor<AAUniformWorkGroupSize>(
404 if (!CallerInfo || !CallerInfo->isValidState())
408 CallerInfo->getState());
413 bool AllCallSitesKnown =
true;
414 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
true, AllCallSitesKnown))
415 return indicatePessimisticFixpoint();
422 LLVMContext &Ctx = getAssociatedFunction()->getContext();
424 AttrList.
push_back(Attribute::get(Ctx,
"uniform-work-group-size",
425 getAssumed() ?
"true" :
"false"));
426 return A.manifestAttrs(getIRPosition(), AttrList,
430 bool isValidState()
const override {
435 const std::string getAsStr(Attributor *)
const override {
436 return "AMDWorkGroupSize[" + std::to_string(getAssumed()) +
"]";
440 void trackStatistics()
const override {}
443AAUniformWorkGroupSize &
444AAUniformWorkGroupSize::createForPosition(
const IRPosition &IRP,
447 return *
new (
A.Allocator) AAUniformWorkGroupSizeFunction(IRP,
A);
449 "AAUniformWorkGroupSize is only valid for function position");
452struct AAAMDAttributesFunction :
public AAAMDAttributes {
453 AAAMDAttributesFunction(
const IRPosition &IRP, Attributor &
A)
454 : AAAMDAttributes(IRP,
A) {}
466 if (HasSanitizerAttrs) {
467 removeAssumedBits(IMPLICIT_ARG_PTR);
468 removeAssumedBits(HOSTCALL_PTR);
469 removeAssumedBits(FLAT_SCRATCH_INIT);
473 if (HasSanitizerAttrs &&
474 (Attr.first == IMPLICIT_ARG_PTR || Attr.first == HOSTCALL_PTR ||
475 Attr.first == FLAT_SCRATCH_INIT))
478 if (
F->hasFnAttribute(Attr.second))
479 addKnownBits(Attr.first);
482 if (
F->isDeclaration())
488 indicatePessimisticFixpoint();
496 auto OrigAssumed = getAssumed();
499 const AACallEdges *AAEdges =
A.getAAFor<AACallEdges>(
500 *
this, this->getIRPosition(), DepClassTy::REQUIRED);
503 return indicatePessimisticFixpoint();
507 bool NeedsImplicit =
false;
508 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
509 bool HasApertureRegs = InfoCache.hasApertureRegs(*
F);
510 bool SupportsGetDoorbellID = InfoCache.supportsGetDoorbellID(*
F);
511 unsigned COV = InfoCache.getCodeObjectVersion();
516 const AAAMDAttributes *AAAMD =
A.getAAFor<AAAMDAttributes>(
518 if (!AAAMD || !AAAMD->isValidState())
519 return indicatePessimisticFixpoint();
524 bool NonKernelOnly =
false;
527 HasApertureRegs, SupportsGetDoorbellID, COV);
529 if ((IsNonEntryFunc || !NonKernelOnly))
530 removeAssumedBits(AttrMask);
536 removeAssumedBits(IMPLICIT_ARG_PTR);
538 if (isAssumed(QUEUE_PTR) && checkForQueuePtr(
A)) {
542 removeAssumedBits(IMPLICIT_ARG_PTR);
544 removeAssumedBits(QUEUE_PTR);
547 if (funcRetrievesMultigridSyncArg(
A, COV)) {
548 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
549 "multigrid_sync_arg needs implicitarg_ptr");
550 removeAssumedBits(MULTIGRID_SYNC_ARG);
553 if (funcRetrievesHostcallPtr(
A, COV)) {
554 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
"hostcall needs implicitarg_ptr");
555 removeAssumedBits(HOSTCALL_PTR);
558 if (funcRetrievesHeapPtr(
A, COV)) {
559 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
"heap_ptr needs implicitarg_ptr");
560 removeAssumedBits(HEAP_PTR);
563 if (isAssumed(QUEUE_PTR) && funcRetrievesQueuePtr(
A, COV)) {
564 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
"queue_ptr needs implicitarg_ptr");
565 removeAssumedBits(QUEUE_PTR);
568 if (isAssumed(LDS_KERNEL_ID) && funcRetrievesLDSKernelId(
A)) {
569 removeAssumedBits(LDS_KERNEL_ID);
572 if (isAssumed(DEFAULT_QUEUE) && funcRetrievesDefaultQueue(
A, COV))
573 removeAssumedBits(DEFAULT_QUEUE);
575 if (isAssumed(COMPLETION_ACTION) && funcRetrievesCompletionAction(
A, COV))
576 removeAssumedBits(COMPLETION_ACTION);
578 if (isAssumed(FLAT_SCRATCH_INIT) && needFlatScratchInit(
A))
579 removeAssumedBits(FLAT_SCRATCH_INIT);
581 return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED
582 : ChangeStatus::UNCHANGED;
587 LLVMContext &Ctx = getAssociatedFunction()->getContext();
590 if (isKnown(Attr.first))
591 AttrList.
push_back(Attribute::get(Ctx, Attr.second));
594 return A.manifestAttrs(getIRPosition(), AttrList,
598 const std::string getAsStr(Attributor *)
const override {
600 raw_string_ostream OS(Str);
603 if (isAssumed(Attr.first))
604 OS <<
' ' << Attr.second;
610 void trackStatistics()
const override {}
613 bool checkForQueuePtr(Attributor &
A) {
617 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
619 bool NeedsQueuePtr =
false;
622 unsigned SrcAS =
static_cast<AddrSpaceCastInst &
>(
I).getSrcAddressSpace();
624 NeedsQueuePtr =
true;
630 bool HasApertureRegs = InfoCache.hasApertureRegs(*
F);
636 if (!HasApertureRegs) {
637 bool UsedAssumedInformation =
false;
638 A.checkForAllInstructions(CheckAddrSpaceCasts, *
this,
639 {Instruction::AddrSpaceCast},
640 UsedAssumedInformation);
647 if (!IsNonEntryFunc && HasApertureRegs)
650 for (BasicBlock &BB : *
F) {
651 for (Instruction &
I : BB) {
652 for (
const Use &U :
I.operands()) {
654 if (InfoCache.needsQueuePtr(
C, *
F))
664 bool funcRetrievesMultigridSyncArg(Attributor &
A,
unsigned COV) {
666 AA::RangeTy
Range(Pos, 8);
667 return funcRetrievesImplicitKernelArg(
A,
Range);
670 bool funcRetrievesHostcallPtr(Attributor &
A,
unsigned COV) {
672 AA::RangeTy
Range(Pos, 8);
673 return funcRetrievesImplicitKernelArg(
A,
Range);
676 bool funcRetrievesDefaultQueue(Attributor &
A,
unsigned COV) {
678 AA::RangeTy
Range(Pos, 8);
679 return funcRetrievesImplicitKernelArg(
A,
Range);
682 bool funcRetrievesCompletionAction(Attributor &
A,
unsigned COV) {
684 AA::RangeTy
Range(Pos, 8);
685 return funcRetrievesImplicitKernelArg(
A,
Range);
688 bool funcRetrievesHeapPtr(Attributor &
A,
unsigned COV) {
692 return funcRetrievesImplicitKernelArg(
A,
Range);
695 bool funcRetrievesQueuePtr(Attributor &
A,
unsigned COV) {
699 return funcRetrievesImplicitKernelArg(
A,
Range);
702 bool funcRetrievesImplicitKernelArg(Attributor &
A, AA::RangeTy
Range) {
714 const auto *PointerInfoAA =
A.getAAFor<AAPointerInfo>(
716 if (!PointerInfoAA || !PointerInfoAA->getState().isValidState())
719 return PointerInfoAA->forallInterferingAccesses(
720 Range, [](
const AAPointerInfo::Access &Acc,
bool IsExact) {
725 bool UsedAssumedInformation =
false;
726 return !
A.checkForAllCallLikeInstructions(DoesNotLeadToKernelArgLoc, *
this,
727 UsedAssumedInformation);
730 bool funcRetrievesLDSKernelId(Attributor &
A) {
735 bool UsedAssumedInformation =
false;
736 return !
A.checkForAllCallLikeInstructions(DoesNotRetrieve, *
this,
737 UsedAssumedInformation);
742 bool needFlatScratchInit(Attributor &
A) {
743 assert(isAssumed(FLAT_SCRATCH_INIT));
752 bool UsedAssumedInformation =
false;
753 if (!
A.checkForAllInstructions(AddrSpaceCastNotFromPrivate, *
this,
754 {Instruction::AddrSpaceCast},
755 UsedAssumedInformation))
759 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
763 for (
const Use &U :
I.operands()) {
765 if (InfoCache.checkConstForAddrSpaceCastFromPrivate(
C))
787 return Callee->getIntrinsicID() !=
788 Intrinsic::amdgcn_addrspacecast_nonnull;
791 UsedAssumedInformation =
false;
795 return !
A.checkForAllCallLikeInstructions(CheckForNoFlatScratchInit, *
this,
796 UsedAssumedInformation);
800AAAMDAttributes &AAAMDAttributes::createForPosition(
const IRPosition &IRP,
803 return *
new (
A.Allocator) AAAMDAttributesFunction(IRP,
A);
808struct AAAMDSizeRangeAttribute
809 :
public StateWrapper<IntegerRangeState, AbstractAttribute, uint32_t> {
810 using Base = StateWrapper<IntegerRangeState, AbstractAttribute, uint32_t>;
814 AAAMDSizeRangeAttribute(
const IRPosition &IRP, Attributor &
A,
816 :
Base(IRP, 32), AttrName(AttrName) {}
819 void trackStatistics()
const override {}
821 template <
class AttributeImpl>
ChangeStatus updateImplImpl(Attributor &
A) {
824 auto CheckCallSite = [&](AbstractCallSite CS) {
827 <<
"->" << getAssociatedFunction()->
getName() <<
'\n');
829 const auto *CallerInfo =
A.getAAFor<AttributeImpl>(
831 if (!CallerInfo || !CallerInfo->isValidState())
840 bool AllCallSitesKnown =
true;
841 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
844 return indicatePessimisticFixpoint();
852 emitAttributeIfNotDefaultAfterClamp(Attributor &
A,
853 std::pair<unsigned, unsigned>
Default) {
855 unsigned Lower = getAssumed().getLower().getZExtValue();
856 unsigned Upper = getAssumed().getUpper().getZExtValue();
866 return ChangeStatus::UNCHANGED;
869 LLVMContext &Ctx =
F->getContext();
870 SmallString<10> Buffer;
871 raw_svector_ostream OS(Buffer);
873 return A.manifestAttrs(getIRPosition(),
874 {Attribute::get(Ctx, AttrName, OS.str())},
878 const std::string getAsStr(Attributor *)
const override {
880 raw_string_ostream OS(Str);
882 OS << getAssumed().getLower() <<
',' << getAssumed().getUpper() - 1;
889struct AAAMDFlatWorkGroupSize :
public AAAMDSizeRangeAttribute {
890 AAAMDFlatWorkGroupSize(
const IRPosition &IRP, Attributor &
A)
891 : AAAMDSizeRangeAttribute(IRP,
A,
"amdgpu-flat-work-group-size") {}
895 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
897 bool HasAttr =
false;
898 auto Range = InfoCache.getDefaultFlatWorkGroupSize(*
F);
899 auto MaxRange = InfoCache.getMaximumFlatWorkGroupRange(*
F);
901 if (
auto Attr = InfoCache.getFlatWorkGroupSizeAttr(*
F)) {
905 if (*Attr != MaxRange) {
913 if (
Range == MaxRange)
917 ConstantRange CR(APInt(32, Min), APInt(32, Max + 1));
918 IntegerRangeState IRS(CR);
922 indicateOptimisticFixpoint();
926 return updateImplImpl<AAAMDFlatWorkGroupSize>(
A);
930 static AAAMDFlatWorkGroupSize &createForPosition(
const IRPosition &IRP,
935 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
936 return emitAttributeIfNotDefaultAfterClamp(
937 A, InfoCache.getMaximumFlatWorkGroupRange(*
F));
941 StringRef
getName()
const override {
return "AAAMDFlatWorkGroupSize"; }
944 const char *getIdAddr()
const override {
return &
ID; }
948 static bool classof(
const AbstractAttribute *AA) {
953 static const char ID;
956const char AAAMDFlatWorkGroupSize::ID = 0;
958AAAMDFlatWorkGroupSize &
959AAAMDFlatWorkGroupSize::createForPosition(
const IRPosition &IRP,
962 return *
new (
A.Allocator) AAAMDFlatWorkGroupSize(IRP,
A);
964 "AAAMDFlatWorkGroupSize is only valid for function position");
967struct TupleDecIntegerRangeState :
public AbstractState {
968 DecIntegerState<uint32_t>
X,
Y, Z;
970 bool isValidState()
const override {
971 return X.isValidState() &&
Y.isValidState() &&
Z.isValidState();
974 bool isAtFixpoint()
const override {
975 return X.isAtFixpoint() &&
Y.isAtFixpoint() &&
Z.isAtFixpoint();
979 return X.indicateOptimisticFixpoint() |
Y.indicateOptimisticFixpoint() |
980 Z.indicateOptimisticFixpoint();
984 return X.indicatePessimisticFixpoint() |
Y.indicatePessimisticFixpoint() |
985 Z.indicatePessimisticFixpoint();
988 TupleDecIntegerRangeState
operator^=(
const TupleDecIntegerRangeState &
Other) {
999 TupleDecIntegerRangeState &getAssumed() {
return *
this; }
1000 const TupleDecIntegerRangeState &getAssumed()
const {
return *
this; }
1003using AAAMDMaxNumWorkgroupsState =
1004 StateWrapper<TupleDecIntegerRangeState, AbstractAttribute, uint32_t>;
1007struct AAAMDMaxNumWorkgroups
1008 :
public StateWrapper<TupleDecIntegerRangeState, AbstractAttribute> {
1009 using Base = StateWrapper<TupleDecIntegerRangeState, AbstractAttribute>;
1011 AAAMDMaxNumWorkgroups(
const IRPosition &IRP, Attributor &
A) :
Base(IRP) {}
1015 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
1017 SmallVector<unsigned> MaxNumWorkgroups = InfoCache.getMaxNumWorkGroups(*
F);
1019 X.takeKnownMinimum(MaxNumWorkgroups[0]);
1020 Y.takeKnownMinimum(MaxNumWorkgroups[1]);
1021 Z.takeKnownMinimum(MaxNumWorkgroups[2]);
1024 indicatePessimisticFixpoint();
1030 auto CheckCallSite = [&](AbstractCallSite CS) {
1033 <<
"->" << getAssociatedFunction()->
getName() <<
'\n');
1035 const auto *CallerInfo =
A.getAAFor<AAAMDMaxNumWorkgroups>(
1037 if (!CallerInfo || !CallerInfo->isValidState())
1045 bool AllCallSitesKnown =
true;
1046 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
1049 return indicatePessimisticFixpoint();
1055 static AAAMDMaxNumWorkgroups &createForPosition(
const IRPosition &IRP,
1060 LLVMContext &Ctx =
F->getContext();
1061 SmallString<32> Buffer;
1062 raw_svector_ostream OS(Buffer);
1063 OS <<
X.getAssumed() <<
',' <<
Y.getAssumed() <<
',' <<
Z.getAssumed();
1067 return A.manifestAttrs(
1069 {Attribute::get(Ctx,
"amdgpu-max-num-workgroups", OS.str())},
1073 StringRef
getName()
const override {
return "AAAMDMaxNumWorkgroups"; }
1075 const std::string getAsStr(Attributor *)
const override {
1076 std::string Buffer =
"AAAMDMaxNumWorkgroupsState[";
1077 raw_string_ostream OS(Buffer);
1078 OS <<
X.getAssumed() <<
',' <<
Y.getAssumed() <<
',' <<
Z.getAssumed()
1083 const char *getIdAddr()
const override {
return &
ID; }
1087 static bool classof(
const AbstractAttribute *AA) {
1091 void trackStatistics()
const override {}
1094 static const char ID;
1097const char AAAMDMaxNumWorkgroups::ID = 0;
1099AAAMDMaxNumWorkgroups &
1100AAAMDMaxNumWorkgroups::createForPosition(
const IRPosition &IRP, Attributor &
A) {
1102 return *
new (
A.Allocator) AAAMDMaxNumWorkgroups(IRP,
A);
1103 llvm_unreachable(
"AAAMDMaxNumWorkgroups is only valid for function position");
1107struct AAAMDWavesPerEU :
public AAAMDSizeRangeAttribute {
1108 AAAMDWavesPerEU(
const IRPosition &IRP, Attributor &
A)
1109 : AAAMDSizeRangeAttribute(IRP,
A,
"amdgpu-waves-per-eu") {}
1113 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
1116 if (
auto Attr = InfoCache.getWavesPerEUAttr(*
F)) {
1117 std::pair<unsigned, unsigned> MaxWavesPerEURange{
1118 1U, InfoCache.getMaxWavesPerEU(*
F)};
1119 if (*Attr != MaxWavesPerEURange) {
1120 auto [Min,
Max] = *Attr;
1121 ConstantRange
Range(APInt(32, Min), APInt(32, Max + 1));
1122 IntegerRangeState RangeState(
Range);
1123 this->getState() = RangeState;
1124 indicateOptimisticFixpoint();
1130 indicatePessimisticFixpoint();
1136 auto CheckCallSite = [&](AbstractCallSite CS) {
1140 <<
"->" <<
Func->getName() <<
'\n');
1143 const auto *CallerAA =
A.getAAFor<AAAMDWavesPerEU>(
1145 if (!CallerAA || !CallerAA->isValidState())
1148 ConstantRange Assumed = getAssumed();
1150 CallerAA->getAssumed().getLower().getZExtValue());
1152 CallerAA->getAssumed().getUpper().getZExtValue());
1153 ConstantRange
Range(APInt(32, Min), APInt(32, Max));
1154 IntegerRangeState RangeState(
Range);
1155 getState() = RangeState;
1156 Change |= getState() == Assumed ? ChangeStatus::UNCHANGED
1157 : ChangeStatus::CHANGED;
1162 bool AllCallSitesKnown =
true;
1163 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
true, AllCallSitesKnown))
1164 return indicatePessimisticFixpoint();
1170 static AAAMDWavesPerEU &createForPosition(
const IRPosition &IRP,
1175 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
1176 return emitAttributeIfNotDefaultAfterClamp(
1177 A, {1U, InfoCache.getMaxWavesPerEU(*
F)});
1181 StringRef
getName()
const override {
return "AAAMDWavesPerEU"; }
1184 const char *getIdAddr()
const override {
return &
ID; }
1188 static bool classof(
const AbstractAttribute *AA) {
1193 static const char ID;
1196const char AAAMDWavesPerEU::ID = 0;
1198AAAMDWavesPerEU &AAAMDWavesPerEU::createForPosition(
const IRPosition &IRP,
1201 return *
new (
A.Allocator) AAAMDWavesPerEU(IRP,
A);
1206static unsigned inlineAsmGetNumRequiredAGPRs(
const InlineAsm *IA,
1207 const CallBase &
Call) {
1210 unsigned AGPRDefCount = 0;
1211 unsigned AGPRUseCount = 0;
1212 unsigned MaxPhysReg = 0;
1216 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
1222 Ty = STy->getElementType(ResNo);
1237 for (StringRef Code : CI.Codes) {
1238 unsigned RegCount = 0;
1239 if (
Code.starts_with(
"a")) {
1250 MaxPhysReg = std::max(MaxPhysReg, std::min(RegIdx + NumRegs, 256u));
1260 AGPRDefCount =
alignTo(AGPRDefCount, RegCount);
1262 AGPRDefCount += RegCount;
1263 if (CI.isEarlyClobber) {
1264 AGPRUseCount =
alignTo(AGPRUseCount, RegCount);
1265 AGPRUseCount += RegCount;
1268 AGPRUseCount =
alignTo(AGPRUseCount, RegCount);
1269 AGPRUseCount += RegCount;
1274 unsigned MaxVirtReg = std::max(AGPRUseCount, AGPRDefCount);
1279 return std::min(MaxVirtReg + MaxPhysReg, 256u);
1282struct AAAMDGPUMinAGPRAlloc
1283 :
public StateWrapper<DecIntegerState<>, AbstractAttribute> {
1284 using Base = StateWrapper<DecIntegerState<>, AbstractAttribute>;
1285 AAAMDGPUMinAGPRAlloc(
const IRPosition &IRP, Attributor &
A) :
Base(IRP) {}
1287 static AAAMDGPUMinAGPRAlloc &createForPosition(
const IRPosition &IRP,
1290 return *
new (
A.Allocator) AAAMDGPUMinAGPRAlloc(IRP,
A);
1292 "AAAMDGPUMinAGPRAlloc is only valid for function position");
1297 auto [MinNumAGPR, MaxNumAGPR] =
1300 if (MinNumAGPR == 0)
1301 indicateOptimisticFixpoint();
1304 const std::string getAsStr(Attributor *
A)
const override {
1305 std::string Str =
"amdgpu-agpr-alloc=";
1306 raw_string_ostream OS(Str);
1311 void trackStatistics()
const override {}
1314 DecIntegerState<> Maximum;
1321 const Value *CalleeOp = CB.getCalledOperand();
1326 unsigned NumRegs = inlineAsmGetNumRequiredAGPRs(IA, CB);
1331 switch (CB.getIntrinsicID()) {
1334 case Intrinsic::write_register:
1335 case Intrinsic::read_register:
1336 case Intrinsic::read_volatile_register: {
1341 auto [
Kind, RegIdx, NumRegs] =
1355 auto *CBEdges =
A.getAAFor<AACallEdges>(
1357 if (!CBEdges || CBEdges->hasUnknownCallee()) {
1362 for (
const Function *PossibleCallee : CBEdges->getOptimisticEdges()) {
1363 const auto *CalleeInfo =
A.getAAFor<AAAMDGPUMinAGPRAlloc>(
1365 if (!CalleeInfo || !CalleeInfo->isValidState()) {
1376 bool UsedAssumedInformation =
false;
1377 if (!
A.checkForAllCallLikeInstructions(CheckForMinAGPRAllocs, *
this,
1378 UsedAssumedInformation))
1379 return indicatePessimisticFixpoint();
1385 LLVMContext &Ctx = getAssociatedFunction()->getContext();
1386 SmallString<4> Buffer;
1387 raw_svector_ostream OS(Buffer);
1390 return A.manifestAttrs(
1391 getIRPosition(), {Attribute::get(Ctx,
"amdgpu-agpr-alloc", OS.str())});
1394 StringRef
getName()
const override {
return "AAAMDGPUMinAGPRAlloc"; }
1395 const char *getIdAddr()
const override {
return &
ID; }
1399 static bool classof(
const AbstractAttribute *AA) {
1403 static const char ID;
1406const char AAAMDGPUMinAGPRAlloc::ID = 0;
1410struct AAAMDGPUClusterDims
1411 :
public StateWrapper<BooleanState, AbstractAttribute> {
1412 using Base = StateWrapper<BooleanState, AbstractAttribute>;
1413 AAAMDGPUClusterDims(
const IRPosition &IRP, Attributor &
A) :
Base(IRP) {}
1416 static AAAMDGPUClusterDims &createForPosition(
const IRPosition &IRP,
1420 StringRef
getName()
const override {
return "AAAMDGPUClusterDims"; }
1423 const char *getIdAddr()
const override {
return &
ID; }
1427 static bool classof(
const AbstractAttribute *AA) {
1431 virtual const AMDGPU::ClusterDimsAttr &getClusterDims()
const = 0;
1434 static const char ID;
1437const char AAAMDGPUClusterDims::ID = 0;
1439struct AAAMDGPUClusterDimsFunction :
public AAAMDGPUClusterDims {
1440 AAAMDGPUClusterDimsFunction(
const IRPosition &IRP, Attributor &
A)
1441 : AAAMDGPUClusterDims(IRP,
A) {}
1445 assert(
F &&
"empty associated function");
1452 indicatePessimisticFixpoint();
1454 indicateOptimisticFixpoint();
1458 const std::string getAsStr(Attributor *
A)
const override {
1468 void trackStatistics()
const override {}
1471 auto OldState = Attr;
1473 auto CheckCallSite = [&](AbstractCallSite CS) {
1474 const auto *CallerAA =
A.getAAFor<AAAMDGPUClusterDims>(
1476 DepClassTy::REQUIRED);
1477 if (!CallerAA || !CallerAA->isValidState())
1480 return merge(CallerAA->getClusterDims());
1483 bool UsedAssumedInformation =
false;
1484 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
1486 UsedAssumedInformation))
1487 return indicatePessimisticFixpoint();
1489 return OldState == Attr ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED;
1494 return ChangeStatus::UNCHANGED;
1495 return A.manifestAttrs(
1497 {Attribute::get(getAssociatedFunction()->
getContext(), AttrName,
1502 const AMDGPU::ClusterDimsAttr &getClusterDims()
const override {
1507 bool merge(
const AMDGPU::ClusterDimsAttr &
Other) {
1522 if (
Other.isUnknown())
1547 AMDGPU::ClusterDimsAttr Attr;
1549 static constexpr char AttrName[] =
"amdgpu-cluster-dims";
1552AAAMDGPUClusterDims &
1553AAAMDGPUClusterDims::createForPosition(
const IRPosition &IRP, Attributor &
A) {
1555 return *
new (
A.Allocator) AAAMDGPUClusterDimsFunction(IRP,
A);
1556 llvm_unreachable(
"AAAMDGPUClusterDims is only valid for function position");
1559static bool runImpl(
Module &M, AnalysisGetter &AG, TargetMachine &TM,
1560 AMDGPUAttributorOptions
Options,
1562 SetVector<Function *> Functions;
1563 for (Function &
F : M) {
1564 if (!
F.isIntrinsic())
1568 CallGraphUpdater CGUpdater;
1570 AMDGPUInformationCache InfoCache(M, AG,
Allocator,
nullptr, TM);
1571 DenseSet<const char *>
Allowed(
1572 {&AAAMDAttributes::ID, &AAUniformWorkGroupSize::ID,
1574 &AAAMDMaxNumWorkgroups::ID, &AAAMDWavesPerEU::ID,
1580 AttributorConfig AC(CGUpdater);
1581 AC.IsClosedWorldModule =
Options.IsClosedWorld;
1583 AC.IsModulePass =
true;
1584 AC.DefaultInitializeLiveInternals =
false;
1585 AC.IndirectCalleeSpecializationCallback =
1586 [](Attributor &
A,
const AbstractAttribute &AA, CallBase &CB,
1591 AC.IPOAmendableCB = [](
const Function &
F) {
1592 return F.getCallingConv() == CallingConv::AMDGPU_KERNEL;
1595 Attributor
A(Functions, InfoCache, AC);
1598 StringRef LTOPhaseStr =
to_string(LTOPhase);
1599 dbgs() <<
"[AMDGPUAttributor] Running at phase " << LTOPhaseStr <<
'\n'
1600 <<
"[AMDGPUAttributor] Module " <<
M.getName() <<
" is "
1601 << (AC.IsClosedWorldModule ?
"" :
"not ")
1602 <<
"assumed to be a closed world.\n";
1605 for (
auto *
F : Functions) {
1609 CallingConv::ID CC =
F->getCallingConv();
1616 if (!
F->isDeclaration() &&
ST.hasClusters())
1619 if (
ST.hasGFX90AInsts())
1623 Value *Ptr =
nullptr;
1625 Ptr = LI->getPointerOperand();
1627 Ptr =
SI->getPointerOperand();
1629 Ptr = RMW->getPointerOperand();
1631 Ptr = CmpX->getPointerOperand();
1637 if (
II->getIntrinsicID() == Intrinsic::amdgcn_make_buffer_rsrc)
1644 return A.run() == ChangeStatus::CHANGED;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isDSAddress(const Constant *C)
static constexpr std::pair< ImplicitArgumentMask, StringLiteral > ImplicitAttrs[]
static cl::opt< unsigned > IndirectCallSpecializationThreshold("amdgpu-indirect-call-specialization-threshold", cl::desc("A threshold controls whether an indirect call will be specialized"), cl::init(3))
static ImplicitArgumentMask intrinsicToAttrMask(Intrinsic::ID ID, bool &NonKernelOnly, bool &NeedsImplicit, bool HasApertureRegs, bool SupportsGetDoorBellID, unsigned CodeObjectVersion)
static bool hasSanitizerAttributes(const Function &F)
Returns true if sanitizer attributes are present on a function.
ImplicitArgumentPositions
static bool castRequiresQueuePtr(unsigned SrcAS)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static bool runImpl(Function &F, const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
AMD GCN specific subclass of TargetSubtarget.
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
Machine Check Debug Module
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
static StringRef getName(Value *V)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ClusterDimsAttr get(const Function &F)
std::string to_string() const
bool isVariableDims() const
uint64_t getZExtValue() const
Get zero extended value.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
This is an important base class in LLVM.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
A Module instance is used to store all the information related to an LLVM module.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
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.
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
std::string str() const
str - Get the contents as an std::string.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Type * getType() const
All values are typed, get the type of this value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ PRIVATE_ADDRESS
Address space for private memory.
unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI)
unsigned getAMDHSACodeObjectVersion(const Module &M)
unsigned getDefaultQueueImplicitArgPosition(unsigned CodeObjectVersion)
std::tuple< char, unsigned, unsigned > parseAsmPhysRegName(StringRef RegName)
Returns a valid charcode or 0 in the first entry if this is a valid physical register name.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
std::tuple< char, unsigned, unsigned > parseAsmConstraintPhysReg(StringRef Constraint)
Returns a valid charcode or 0 in the first entry if this is a valid physical register constraint.
unsigned getHostcallImplicitArgPosition(unsigned CodeObjectVersion)
unsigned getCompletionActionImplicitArgPosition(unsigned CodeObjectVersion)
std::pair< unsigned, unsigned > getIntegerPairAttribute(const Function &F, StringRef Name, std::pair< unsigned, unsigned > Default, bool OnlyFirstRequired)
LLVM_READNONE constexpr bool isGraphics(CallingConv::ID CC)
unsigned getMultigridSyncArgImplicitArgPosition(unsigned CodeObjectVersion)
E & operator^=(E &LHS, E RHS)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
NodeAddr< CodeNode * > Code
NodeAddr< FuncNode * > Func
Context & getContext() const
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
const char * to_string(ThinOrFullLTOPhase Phase)
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R)
Helper function to clamp a state S of type StateType with the information in R and indicate/return if...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual const SetVector< Function * > & getOptimisticEdges() const =0
Get the optimistic edges.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual bool hasNonAsmUnknownCallee() const =0
Is there any call with a unknown callee, excluding any inline asm.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
Instruction * getRemoteInst() const
Return the actual instruction that causes the access.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual const char * getIdAddr() const =0
This function should return the address of the ID of the AbstractAttribute.
Wrapper for FunctionAnalysisManager.
The fixpoint analysis framework that orchestrates the attribute deduction.
DecIntegerState & takeAssumedMaximum(base_t Value)
Take maximum of assumed and Value.
Helper to describe and deal with positions in the LLVM-IR.
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
static const IRPosition value(const Value &V, const CallBaseContext *CBContext=nullptr)
Create a position describing the value of V.
@ IRP_FUNCTION
An attribute for a function (scope).
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
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.
bool isValidState() const override
See AbstractState::isValidState() NOTE: For now we simply pretend that the worst possible state is in...
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
Helper to tie a abstract state implementation to an abstract attribute.