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"
47#define AMDGPU_ATTRIBUTE(Name, Str) {Name, Str},
48static constexpr std::pair<ImplicitArgumentMask, StringLiteral>
50#include "AMDGPUAttributes.def"
60 bool HasApertureRegs,
bool SupportsGetDoorBellID,
61 unsigned CodeObjectVersion) {
63 case Intrinsic::amdgcn_workitem_id_x:
66 case Intrinsic::amdgcn_workgroup_id_x:
68 return WORKGROUP_ID_X;
69 case Intrinsic::amdgcn_workitem_id_y:
70 case Intrinsic::r600_read_tidig_y:
72 case Intrinsic::amdgcn_workitem_id_z:
73 case Intrinsic::r600_read_tidig_z:
75 case Intrinsic::amdgcn_workgroup_id_y:
76 case Intrinsic::r600_read_tgid_y:
77 return WORKGROUP_ID_Y;
78 case Intrinsic::amdgcn_workgroup_id_z:
79 case Intrinsic::r600_read_tgid_z:
80 return WORKGROUP_ID_Z;
81 case Intrinsic::amdgcn_cluster_id_x:
84 case Intrinsic::amdgcn_cluster_id_y:
86 case Intrinsic::amdgcn_cluster_id_z:
88 case Intrinsic::amdgcn_lds_kernel_id:
90 case Intrinsic::amdgcn_dispatch_ptr:
92 case Intrinsic::amdgcn_dispatch_id:
94 case Intrinsic::amdgcn_implicitarg_ptr:
95 return IMPLICIT_ARG_PTR;
98 case Intrinsic::amdgcn_queue_ptr:
101 case Intrinsic::amdgcn_is_shared:
102 case Intrinsic::amdgcn_is_private:
110 case Intrinsic::trap:
111 case Intrinsic::debugtrap:
112 case Intrinsic::ubsantrap:
113 if (SupportsGetDoorBellID)
137 return F.hasFnAttribute(Attribute::SanitizeAddress) ||
138 F.hasFnAttribute(Attribute::SanitizeThread) ||
139 F.hasFnAttribute(Attribute::SanitizeMemory) ||
140 F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
141 F.hasFnAttribute(Attribute::SanitizeMemTag);
147 AMDGPUInformationCache(
const Module &M, AnalysisGetter &AG,
149 SetVector<Function *> *
CGSCC, TargetMachine &TM)
155 enum ConstantStatus : uint8_t {
158 ADDR_SPACE_CAST_PRIVATE_TO_FLAT = 1 << 1,
159 ADDR_SPACE_CAST_LOCAL_TO_FLAT = 1 << 2,
160 ADDR_SPACE_CAST_BOTH_TO_FLAT =
161 ADDR_SPACE_CAST_PRIVATE_TO_FLAT | ADDR_SPACE_CAST_LOCAL_TO_FLAT
165 bool hasApertureRegs(Function &
F) {
166 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
167 return ST.hasApertureRegs();
171 bool supportsGetDoorbellID(Function &
F) {
172 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
173 return ST.supportsGetDoorbellID();
176 std::optional<std::pair<unsigned, unsigned>>
177 getFlatWorkGroupSizeAttr(
const Function &
F)
const {
181 return std::make_pair(
R->first, *(
R->second));
184 std::pair<unsigned, unsigned>
185 getDefaultFlatWorkGroupSize(
const Function &
F)
const {
186 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
187 return ST.getDefaultFlatWorkGroupSize(
F.getCallingConv());
190 std::pair<unsigned, unsigned>
191 getMaximumFlatWorkGroupRange(
const Function &
F) {
192 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
193 return {
ST.getMinFlatWorkGroupSize(),
ST.getMaxFlatWorkGroupSize()};
196 SmallVector<unsigned> getMaxNumWorkGroups(
const Function &
F) {
197 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
198 return ST.getMaxNumWorkGroups(
F);
202 unsigned getCodeObjectVersion()
const {
return CodeObjectVersion; }
207 std::pair<unsigned, unsigned>
208 getWavesPerEU(
const Function &
F,
209 std::pair<unsigned, unsigned> FlatWorkGroupSize) {
210 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
211 return ST.getWavesPerEU(FlatWorkGroupSize, getLDSSize(
F),
F);
214 std::optional<std::pair<unsigned, unsigned>>
215 getWavesPerEUAttr(
const Function &
F) {
221 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
222 Val->second =
ST.getMaxWavesPerEU();
224 return std::make_pair(Val->first, *(Val->second));
227 std::pair<unsigned, unsigned>
228 getEffectiveWavesPerEU(
const Function &
F,
229 std::pair<unsigned, unsigned> WavesPerEU,
230 std::pair<unsigned, unsigned> FlatWorkGroupSize) {
231 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
232 return ST.getEffectiveWavesPerEU(WavesPerEU, FlatWorkGroupSize,
237 const GCNSubtarget &
ST = TM.getSubtarget<GCNSubtarget>(
F);
238 return ST.getMaxWavesPerEU();
241 unsigned getMaxAddrSpace()
const override {
248 static uint8_t visitConstExpr(
const ConstantExpr *CE) {
249 uint8_t Status = NONE;
251 if (
CE->getOpcode() == Instruction::AddrSpaceCast) {
252 unsigned SrcAS =
CE->getOperand(0)->getType()->getPointerAddressSpace();
254 Status |= ADDR_SPACE_CAST_PRIVATE_TO_FLAT;
256 Status |= ADDR_SPACE_CAST_LOCAL_TO_FLAT;
264 static unsigned getLDSSize(
const Function &
F) {
266 {0, UINT32_MAX},
true)
271 uint8_t getConstantAccess(
const Constant *
C,
272 SmallPtrSetImpl<const Constant *> &Visited) {
273 auto It = ConstantStatus.find(
C);
274 if (It != ConstantStatus.end())
282 Result |= visitConstExpr(CE);
284 for (
const Use &U :
C->operands()) {
286 if (!OpC || !Visited.
insert(OpC).second)
289 Result |= getConstantAccess(OpC, Visited);
296 bool needsQueuePtr(
const Constant *
C, Function &Fn) {
298 bool HasAperture = hasApertureRegs(Fn);
301 if (!IsNonEntryFunc && HasAperture)
304 SmallPtrSet<const Constant *, 8> Visited;
305 uint8_t
Access = getConstantAccess(
C, Visited);
308 if (IsNonEntryFunc && (
Access & DS_GLOBAL))
311 return !HasAperture && (
Access & ADDR_SPACE_CAST_BOTH_TO_FLAT);
314 bool checkConstForAddrSpaceCastFromPrivate(
const Constant *
C) {
315 SmallPtrSet<const Constant *, 8> Visited;
316 uint8_t
Access = getConstantAccess(
C, Visited);
317 return Access & ADDR_SPACE_CAST_PRIVATE_TO_FLAT;
322 DenseMap<const Constant *, uint8_t> ConstantStatus;
323 const unsigned CodeObjectVersion;
326struct AAAMDAttributes
327 :
public StateWrapper<BitIntegerState<uint32_t, ALL_ARGUMENT_MASK, 0>,
329 using Base = StateWrapper<BitIntegerState<uint32_t, ALL_ARGUMENT_MASK, 0>,
332 AAAMDAttributes(
const IRPosition &IRP, Attributor &
A) : Base(IRP) {}
335 static AAAMDAttributes &createForPosition(
const IRPosition &IRP,
339 StringRef
getName()
const override {
return "AAAMDAttributes"; }
342 const char *getIdAddr()
const override {
return &ID; }
346 static bool classof(
const AbstractAttribute *AA) {
351 static const char ID;
353const char AAAMDAttributes::ID = 0;
355struct AAUniformWorkGroupSize
356 :
public StateWrapper<BooleanState, AbstractAttribute> {
357 using Base = StateWrapper<BooleanState, AbstractAttribute>;
358 AAUniformWorkGroupSize(
const IRPosition &IRP, Attributor &
A) : Base(IRP) {}
361 static AAUniformWorkGroupSize &createForPosition(
const IRPosition &IRP,
365 StringRef
getName()
const override {
return "AAUniformWorkGroupSize"; }
368 const char *getIdAddr()
const override {
return &ID; }
372 static bool classof(
const AbstractAttribute *AA) {
377 static const char ID;
379const char AAUniformWorkGroupSize::ID = 0;
381struct AAUniformWorkGroupSizeFunction :
public AAUniformWorkGroupSize {
382 AAUniformWorkGroupSizeFunction(
const IRPosition &IRP, Attributor &
A)
383 : AAUniformWorkGroupSize(IRP,
A) {}
387 CallingConv::ID CC =
F->getCallingConv();
389 if (CC != CallingConv::AMDGPU_KERNEL)
392 bool InitialValue =
false;
393 if (
F->hasFnAttribute(
"uniform-work-group-size"))
395 F->getFnAttribute(
"uniform-work-group-size").getValueAsString() ==
399 indicateOptimisticFixpoint();
401 indicatePessimisticFixpoint();
407 auto CheckCallSite = [&](AbstractCallSite CS) {
410 <<
"->" << getAssociatedFunction()->
getName() <<
"\n");
412 const auto *CallerInfo =
A.getAAFor<AAUniformWorkGroupSize>(
414 if (!CallerInfo || !CallerInfo->isValidState())
418 CallerInfo->getState());
423 bool AllCallSitesKnown =
true;
424 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
true, AllCallSitesKnown))
425 return indicatePessimisticFixpoint();
432 LLVMContext &Ctx = getAssociatedFunction()->getContext();
434 AttrList.
push_back(Attribute::get(Ctx,
"uniform-work-group-size",
435 getAssumed() ?
"true" :
"false"));
436 return A.manifestAttrs(getIRPosition(), AttrList,
440 bool isValidState()
const override {
445 const std::string getAsStr(Attributor *)
const override {
446 return "AMDWorkGroupSize[" + std::to_string(getAssumed()) +
"]";
450 void trackStatistics()
const override {}
453AAUniformWorkGroupSize &
454AAUniformWorkGroupSize::createForPosition(
const IRPosition &IRP,
457 return *
new (
A.Allocator) AAUniformWorkGroupSizeFunction(IRP,
A);
459 "AAUniformWorkGroupSize is only valid for function position");
462struct AAAMDAttributesFunction :
public AAAMDAttributes {
463 AAAMDAttributesFunction(
const IRPosition &IRP, Attributor &
A)
464 : AAAMDAttributes(IRP,
A) {}
476 if (HasSanitizerAttrs) {
477 removeAssumedBits(IMPLICIT_ARG_PTR);
478 removeAssumedBits(HOSTCALL_PTR);
479 removeAssumedBits(FLAT_SCRATCH_INIT);
483 if (HasSanitizerAttrs &&
484 (Attr.first == IMPLICIT_ARG_PTR || Attr.first == HOSTCALL_PTR ||
485 Attr.first == FLAT_SCRATCH_INIT))
488 if (
F->hasFnAttribute(Attr.second))
489 addKnownBits(Attr.first);
492 if (
F->isDeclaration())
498 indicatePessimisticFixpoint();
506 auto OrigAssumed = getAssumed();
509 const AACallEdges *AAEdges =
A.getAAFor<AACallEdges>(
510 *
this, this->getIRPosition(), DepClassTy::REQUIRED);
513 return indicatePessimisticFixpoint();
517 bool NeedsImplicit =
false;
518 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
519 bool HasApertureRegs = InfoCache.hasApertureRegs(*
F);
520 bool SupportsGetDoorbellID = InfoCache.supportsGetDoorbellID(*
F);
521 unsigned COV = InfoCache.getCodeObjectVersion();
526 const AAAMDAttributes *AAAMD =
A.getAAFor<AAAMDAttributes>(
528 if (!AAAMD || !AAAMD->isValidState())
529 return indicatePessimisticFixpoint();
534 bool NonKernelOnly =
false;
537 HasApertureRegs, SupportsGetDoorbellID, COV);
548 if (!
Callee->hasFnAttribute(Attribute::NoCallback))
549 return indicatePessimisticFixpoint();
554 if ((IsNonEntryFunc || !NonKernelOnly))
555 removeAssumedBits(AttrMask);
561 removeAssumedBits(IMPLICIT_ARG_PTR);
563 if (isAssumed(QUEUE_PTR) && checkForQueuePtr(
A)) {
567 removeAssumedBits(IMPLICIT_ARG_PTR);
569 removeAssumedBits(QUEUE_PTR);
572 if (funcRetrievesMultigridSyncArg(
A, COV)) {
573 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
574 "multigrid_sync_arg needs implicitarg_ptr");
575 removeAssumedBits(MULTIGRID_SYNC_ARG);
578 if (funcRetrievesHostcallPtr(
A, COV)) {
579 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
"hostcall needs implicitarg_ptr");
580 removeAssumedBits(HOSTCALL_PTR);
583 if (funcRetrievesHeapPtr(
A, COV)) {
584 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
"heap_ptr needs implicitarg_ptr");
585 removeAssumedBits(HEAP_PTR);
588 if (isAssumed(QUEUE_PTR) && funcRetrievesQueuePtr(
A, COV)) {
589 assert(!isAssumed(IMPLICIT_ARG_PTR) &&
"queue_ptr needs implicitarg_ptr");
590 removeAssumedBits(QUEUE_PTR);
593 if (isAssumed(LDS_KERNEL_ID) && funcRetrievesLDSKernelId(
A)) {
594 removeAssumedBits(LDS_KERNEL_ID);
597 if (isAssumed(DEFAULT_QUEUE) && funcRetrievesDefaultQueue(
A, COV))
598 removeAssumedBits(DEFAULT_QUEUE);
600 if (isAssumed(COMPLETION_ACTION) && funcRetrievesCompletionAction(
A, COV))
601 removeAssumedBits(COMPLETION_ACTION);
603 if (isAssumed(FLAT_SCRATCH_INIT) && needFlatScratchInit(
A))
604 removeAssumedBits(FLAT_SCRATCH_INIT);
606 return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED
607 : ChangeStatus::UNCHANGED;
612 LLVMContext &Ctx = getAssociatedFunction()->getContext();
615 if (isKnown(Attr.first))
616 AttrList.
push_back(Attribute::get(Ctx, Attr.second));
619 return A.manifestAttrs(getIRPosition(), AttrList,
623 const std::string getAsStr(Attributor *)
const override {
625 raw_string_ostream OS(Str);
628 if (isAssumed(Attr.first))
629 OS <<
' ' << Attr.second;
635 void trackStatistics()
const override {}
638 bool checkForQueuePtr(Attributor &
A) {
642 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
644 bool NeedsQueuePtr =
false;
647 unsigned SrcAS =
static_cast<AddrSpaceCastInst &
>(
I).getSrcAddressSpace();
649 NeedsQueuePtr =
true;
655 bool HasApertureRegs = InfoCache.hasApertureRegs(*
F);
661 if (!HasApertureRegs) {
662 bool UsedAssumedInformation =
false;
663 A.checkForAllInstructions(CheckAddrSpaceCasts, *
this,
664 {Instruction::AddrSpaceCast},
665 UsedAssumedInformation);
672 if (!IsNonEntryFunc && HasApertureRegs)
675 for (BasicBlock &BB : *
F) {
676 for (Instruction &
I : BB) {
677 for (
const Use &U :
I.operands()) {
679 if (InfoCache.needsQueuePtr(
C, *
F))
689 bool funcRetrievesMultigridSyncArg(Attributor &
A,
unsigned COV) {
691 AA::RangeTy
Range(Pos, 8);
692 return funcRetrievesImplicitKernelArg(
A,
Range);
695 bool funcRetrievesHostcallPtr(Attributor &
A,
unsigned COV) {
697 AA::RangeTy
Range(Pos, 8);
698 return funcRetrievesImplicitKernelArg(
A,
Range);
701 bool funcRetrievesDefaultQueue(Attributor &
A,
unsigned COV) {
703 AA::RangeTy
Range(Pos, 8);
704 return funcRetrievesImplicitKernelArg(
A,
Range);
707 bool funcRetrievesCompletionAction(Attributor &
A,
unsigned COV) {
709 AA::RangeTy
Range(Pos, 8);
710 return funcRetrievesImplicitKernelArg(
A,
Range);
713 bool funcRetrievesHeapPtr(Attributor &
A,
unsigned COV) {
717 return funcRetrievesImplicitKernelArg(
A,
Range);
720 bool funcRetrievesQueuePtr(Attributor &
A,
unsigned COV) {
724 return funcRetrievesImplicitKernelArg(
A,
Range);
727 bool funcRetrievesImplicitKernelArg(Attributor &
A, AA::RangeTy
Range) {
739 const auto *PointerInfoAA =
A.getAAFor<AAPointerInfo>(
741 if (!PointerInfoAA || !PointerInfoAA->getState().isValidState())
744 return PointerInfoAA->forallInterferingAccesses(
745 Range, [](
const AAPointerInfo::Access &Acc,
bool IsExact) {
750 bool UsedAssumedInformation =
false;
751 return !
A.checkForAllCallLikeInstructions(DoesNotLeadToKernelArgLoc, *
this,
752 UsedAssumedInformation);
755 bool funcRetrievesLDSKernelId(Attributor &
A) {
760 bool UsedAssumedInformation =
false;
761 return !
A.checkForAllCallLikeInstructions(DoesNotRetrieve, *
this,
762 UsedAssumedInformation);
767 bool needFlatScratchInit(Attributor &
A) {
768 assert(isAssumed(FLAT_SCRATCH_INIT));
777 bool UsedAssumedInformation =
false;
778 if (!
A.checkForAllInstructions(AddrSpaceCastNotFromPrivate, *
this,
779 {Instruction::AddrSpaceCast},
780 UsedAssumedInformation))
784 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
788 for (
const Use &U :
I.operands()) {
790 if (InfoCache.checkConstForAddrSpaceCastFromPrivate(
C))
812 return Callee->getIntrinsicID() !=
813 Intrinsic::amdgcn_addrspacecast_nonnull;
816 UsedAssumedInformation =
false;
820 return !
A.checkForAllCallLikeInstructions(CheckForNoFlatScratchInit, *
this,
821 UsedAssumedInformation);
825AAAMDAttributes &AAAMDAttributes::createForPosition(
const IRPosition &IRP,
828 return *
new (
A.Allocator) AAAMDAttributesFunction(IRP,
A);
833struct AAAMDSizeRangeAttribute
834 :
public StateWrapper<IntegerRangeState, AbstractAttribute, uint32_t> {
835 using Base = StateWrapper<IntegerRangeState, AbstractAttribute, uint32_t>;
839 AAAMDSizeRangeAttribute(
const IRPosition &IRP, Attributor &
A,
841 :
Base(IRP, 32), AttrName(AttrName) {}
844 void trackStatistics()
const override {}
846 template <
class AttributeImpl>
ChangeStatus updateImplImpl(Attributor &
A) {
849 auto CheckCallSite = [&](AbstractCallSite CS) {
852 <<
"->" << getAssociatedFunction()->
getName() <<
'\n');
854 const auto *CallerInfo =
A.getAAFor<AttributeImpl>(
856 if (!CallerInfo || !CallerInfo->isValidState())
865 bool AllCallSitesKnown =
true;
866 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
869 return indicatePessimisticFixpoint();
877 emitAttributeIfNotDefaultAfterClamp(Attributor &
A,
878 std::pair<unsigned, unsigned>
Default) {
880 unsigned Lower = getAssumed().getLower().getZExtValue();
881 unsigned Upper = getAssumed().getUpper().getZExtValue();
891 return ChangeStatus::UNCHANGED;
894 LLVMContext &Ctx =
F->getContext();
895 SmallString<10> Buffer;
896 raw_svector_ostream OS(Buffer);
898 return A.manifestAttrs(getIRPosition(),
899 {Attribute::get(Ctx, AttrName, OS.str())},
903 const std::string getAsStr(Attributor *)
const override {
905 raw_string_ostream OS(Str);
907 OS << getAssumed().getLower() <<
',' << getAssumed().getUpper() - 1;
914struct AAAMDFlatWorkGroupSize :
public AAAMDSizeRangeAttribute {
915 AAAMDFlatWorkGroupSize(
const IRPosition &IRP, Attributor &
A)
916 : AAAMDSizeRangeAttribute(IRP,
A,
"amdgpu-flat-work-group-size") {}
920 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
922 bool HasAttr =
false;
923 auto Range = InfoCache.getDefaultFlatWorkGroupSize(*
F);
924 auto MaxRange = InfoCache.getMaximumFlatWorkGroupRange(*
F);
926 if (
auto Attr = InfoCache.getFlatWorkGroupSizeAttr(*
F)) {
930 if (*Attr != MaxRange) {
938 if (
Range == MaxRange)
942 ConstantRange CR(APInt(32, Min), APInt(32, Max + 1));
943 IntegerRangeState IRS(CR);
947 indicateOptimisticFixpoint();
951 return updateImplImpl<AAAMDFlatWorkGroupSize>(
A);
955 static AAAMDFlatWorkGroupSize &createForPosition(
const IRPosition &IRP,
960 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
961 return emitAttributeIfNotDefaultAfterClamp(
962 A, InfoCache.getMaximumFlatWorkGroupRange(*
F));
966 StringRef
getName()
const override {
return "AAAMDFlatWorkGroupSize"; }
969 const char *getIdAddr()
const override {
return &
ID; }
973 static bool classof(
const AbstractAttribute *AA) {
978 static const char ID;
981const char AAAMDFlatWorkGroupSize::ID = 0;
983AAAMDFlatWorkGroupSize &
984AAAMDFlatWorkGroupSize::createForPosition(
const IRPosition &IRP,
987 return *
new (
A.Allocator) AAAMDFlatWorkGroupSize(IRP,
A);
989 "AAAMDFlatWorkGroupSize is only valid for function position");
992struct TupleDecIntegerRangeState :
public AbstractState {
993 DecIntegerState<uint32_t>
X,
Y, Z;
995 bool isValidState()
const override {
996 return X.isValidState() &&
Y.isValidState() &&
Z.isValidState();
999 bool isAtFixpoint()
const override {
1000 return X.isAtFixpoint() &&
Y.isAtFixpoint() &&
Z.isAtFixpoint();
1004 return X.indicateOptimisticFixpoint() |
Y.indicateOptimisticFixpoint() |
1005 Z.indicateOptimisticFixpoint();
1009 return X.indicatePessimisticFixpoint() |
Y.indicatePessimisticFixpoint() |
1010 Z.indicatePessimisticFixpoint();
1013 TupleDecIntegerRangeState
operator^=(
const TupleDecIntegerRangeState &
Other) {
1024 TupleDecIntegerRangeState &getAssumed() {
return *
this; }
1025 const TupleDecIntegerRangeState &getAssumed()
const {
return *
this; }
1028using AAAMDMaxNumWorkgroupsState =
1029 StateWrapper<TupleDecIntegerRangeState, AbstractAttribute, uint32_t>;
1032struct AAAMDMaxNumWorkgroups
1033 :
public StateWrapper<TupleDecIntegerRangeState, AbstractAttribute> {
1034 using Base = StateWrapper<TupleDecIntegerRangeState, AbstractAttribute>;
1036 AAAMDMaxNumWorkgroups(
const IRPosition &IRP, Attributor &
A) :
Base(IRP) {}
1040 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
1042 SmallVector<unsigned> MaxNumWorkgroups = InfoCache.getMaxNumWorkGroups(*
F);
1044 X.takeKnownMinimum(MaxNumWorkgroups[0]);
1045 Y.takeKnownMinimum(MaxNumWorkgroups[1]);
1046 Z.takeKnownMinimum(MaxNumWorkgroups[2]);
1049 indicatePessimisticFixpoint();
1055 auto CheckCallSite = [&](AbstractCallSite CS) {
1058 <<
"->" << getAssociatedFunction()->
getName() <<
'\n');
1060 const auto *CallerInfo =
A.getAAFor<AAAMDMaxNumWorkgroups>(
1062 if (!CallerInfo || !CallerInfo->isValidState())
1070 bool AllCallSitesKnown =
true;
1071 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
1074 return indicatePessimisticFixpoint();
1080 static AAAMDMaxNumWorkgroups &createForPosition(
const IRPosition &IRP,
1085 LLVMContext &Ctx =
F->getContext();
1086 SmallString<32> Buffer;
1087 raw_svector_ostream OS(Buffer);
1088 OS <<
X.getAssumed() <<
',' <<
Y.getAssumed() <<
',' <<
Z.getAssumed();
1092 return A.manifestAttrs(
1094 {Attribute::get(Ctx,
"amdgpu-max-num-workgroups", OS.str())},
1098 StringRef
getName()
const override {
return "AAAMDMaxNumWorkgroups"; }
1100 const std::string getAsStr(Attributor *)
const override {
1101 std::string Buffer =
"AAAMDMaxNumWorkgroupsState[";
1102 raw_string_ostream OS(Buffer);
1103 OS <<
X.getAssumed() <<
',' <<
Y.getAssumed() <<
',' <<
Z.getAssumed()
1108 const char *getIdAddr()
const override {
return &
ID; }
1112 static bool classof(
const AbstractAttribute *AA) {
1116 void trackStatistics()
const override {}
1119 static const char ID;
1122const char AAAMDMaxNumWorkgroups::ID = 0;
1124AAAMDMaxNumWorkgroups &
1125AAAMDMaxNumWorkgroups::createForPosition(
const IRPosition &IRP, Attributor &
A) {
1127 return *
new (
A.Allocator) AAAMDMaxNumWorkgroups(IRP,
A);
1128 llvm_unreachable(
"AAAMDMaxNumWorkgroups is only valid for function position");
1132struct AAAMDWavesPerEU :
public AAAMDSizeRangeAttribute {
1133 AAAMDWavesPerEU(
const IRPosition &IRP, Attributor &
A)
1134 : AAAMDSizeRangeAttribute(IRP,
A,
"amdgpu-waves-per-eu") {}
1138 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
1141 if (
auto Attr = InfoCache.getWavesPerEUAttr(*
F)) {
1142 std::pair<unsigned, unsigned> MaxWavesPerEURange{
1143 1U, InfoCache.getMaxWavesPerEU(*
F)};
1144 if (*Attr != MaxWavesPerEURange) {
1145 auto [Min,
Max] = *Attr;
1146 ConstantRange
Range(APInt(32, Min), APInt(32, Max + 1));
1147 IntegerRangeState RangeState(
Range);
1148 this->getState() = RangeState;
1149 indicateOptimisticFixpoint();
1155 indicatePessimisticFixpoint();
1161 auto CheckCallSite = [&](AbstractCallSite CS) {
1165 <<
"->" <<
Func->getName() <<
'\n');
1168 const auto *CallerAA =
A.getAAFor<AAAMDWavesPerEU>(
1170 if (!CallerAA || !CallerAA->isValidState())
1173 ConstantRange Assumed = getAssumed();
1175 CallerAA->getAssumed().getLower().getZExtValue());
1177 CallerAA->getAssumed().getUpper().getZExtValue());
1178 ConstantRange
Range(APInt(32, Min), APInt(32, Max));
1179 IntegerRangeState RangeState(
Range);
1180 getState() = RangeState;
1181 Change |= getState() == Assumed ? ChangeStatus::UNCHANGED
1182 : ChangeStatus::CHANGED;
1187 bool AllCallSitesKnown =
true;
1188 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
true, AllCallSitesKnown))
1189 return indicatePessimisticFixpoint();
1195 static AAAMDWavesPerEU &createForPosition(
const IRPosition &IRP,
1200 auto &InfoCache =
static_cast<AMDGPUInformationCache &
>(
A.getInfoCache());
1201 return emitAttributeIfNotDefaultAfterClamp(
1202 A, {1U, InfoCache.getMaxWavesPerEU(*
F)});
1206 StringRef
getName()
const override {
return "AAAMDWavesPerEU"; }
1209 const char *getIdAddr()
const override {
return &
ID; }
1213 static bool classof(
const AbstractAttribute *AA) {
1218 static const char ID;
1221const char AAAMDWavesPerEU::ID = 0;
1223AAAMDWavesPerEU &AAAMDWavesPerEU::createForPosition(
const IRPosition &IRP,
1226 return *
new (
A.Allocator) AAAMDWavesPerEU(IRP,
A);
1231static unsigned inlineAsmGetNumRequiredAGPRs(
const InlineAsm *IA,
1232 const CallBase &
Call) {
1235 unsigned AGPRDefCount = 0;
1236 unsigned AGPRUseCount = 0;
1237 unsigned MaxPhysReg = 0;
1241 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
1247 Ty = STy->getElementType(ResNo);
1262 for (StringRef Code : CI.Codes) {
1263 unsigned RegCount = 0;
1264 if (
Code.starts_with(
"a")) {
1275 MaxPhysReg = std::max(MaxPhysReg, std::min(RegIdx + NumRegs, 256u));
1285 AGPRDefCount =
alignTo(AGPRDefCount, RegCount);
1287 AGPRDefCount += RegCount;
1288 if (CI.isEarlyClobber) {
1289 AGPRUseCount =
alignTo(AGPRUseCount, RegCount);
1290 AGPRUseCount += RegCount;
1293 AGPRUseCount =
alignTo(AGPRUseCount, RegCount);
1294 AGPRUseCount += RegCount;
1299 unsigned MaxVirtReg = std::max(AGPRUseCount, AGPRDefCount);
1304 return std::min(MaxVirtReg + MaxPhysReg, 256u);
1307struct AAAMDGPUMinAGPRAlloc
1308 :
public StateWrapper<DecIntegerState<>, AbstractAttribute> {
1309 using Base = StateWrapper<DecIntegerState<>, AbstractAttribute>;
1310 AAAMDGPUMinAGPRAlloc(
const IRPosition &IRP, Attributor &
A) :
Base(IRP) {}
1312 static AAAMDGPUMinAGPRAlloc &createForPosition(
const IRPosition &IRP,
1315 return *
new (
A.Allocator) AAAMDGPUMinAGPRAlloc(IRP,
A);
1317 "AAAMDGPUMinAGPRAlloc is only valid for function position");
1322 auto [MinNumAGPR, MaxNumAGPR] =
1325 if (MinNumAGPR == 0)
1326 indicateOptimisticFixpoint();
1329 const std::string getAsStr(Attributor *
A)
const override {
1330 std::string Str =
"amdgpu-agpr-alloc=";
1331 raw_string_ostream OS(Str);
1336 void trackStatistics()
const override {}
1339 DecIntegerState<> Maximum;
1346 const Value *CalleeOp = CB.getCalledOperand();
1351 unsigned NumRegs = inlineAsmGetNumRequiredAGPRs(IA, CB);
1356 switch (CB.getIntrinsicID()) {
1359 case Intrinsic::write_register:
1360 case Intrinsic::read_register:
1361 case Intrinsic::read_volatile_register: {
1366 auto [
Kind, RegIdx, NumRegs] =
1379 return CB.hasFnAttr(Attribute::NoCallback);
1383 auto *CBEdges =
A.getAAFor<AACallEdges>(
1385 if (!CBEdges || CBEdges->hasUnknownCallee()) {
1390 for (
const Function *PossibleCallee : CBEdges->getOptimisticEdges()) {
1391 const auto *CalleeInfo =
A.getAAFor<AAAMDGPUMinAGPRAlloc>(
1393 if (!CalleeInfo || !CalleeInfo->isValidState()) {
1404 bool UsedAssumedInformation =
false;
1405 if (!
A.checkForAllCallLikeInstructions(CheckForMinAGPRAllocs, *
this,
1406 UsedAssumedInformation))
1407 return indicatePessimisticFixpoint();
1413 LLVMContext &Ctx = getAssociatedFunction()->getContext();
1414 SmallString<4> Buffer;
1415 raw_svector_ostream OS(Buffer);
1418 return A.manifestAttrs(
1419 getIRPosition(), {Attribute::get(Ctx,
"amdgpu-agpr-alloc", OS.str())});
1422 StringRef
getName()
const override {
return "AAAMDGPUMinAGPRAlloc"; }
1423 const char *getIdAddr()
const override {
return &
ID; }
1427 static bool classof(
const AbstractAttribute *AA) {
1431 static const char ID;
1434const char AAAMDGPUMinAGPRAlloc::ID = 0;
1438struct AAAMDGPUClusterDims
1439 :
public StateWrapper<BooleanState, AbstractAttribute> {
1440 using Base = StateWrapper<BooleanState, AbstractAttribute>;
1441 AAAMDGPUClusterDims(
const IRPosition &IRP, Attributor &
A) :
Base(IRP) {}
1444 static AAAMDGPUClusterDims &createForPosition(
const IRPosition &IRP,
1448 StringRef
getName()
const override {
return "AAAMDGPUClusterDims"; }
1451 const char *getIdAddr()
const override {
return &
ID; }
1455 static bool classof(
const AbstractAttribute *AA) {
1459 virtual const AMDGPU::ClusterDimsAttr &getClusterDims()
const = 0;
1462 static const char ID;
1465const char AAAMDGPUClusterDims::ID = 0;
1467struct AAAMDGPUClusterDimsFunction :
public AAAMDGPUClusterDims {
1468 AAAMDGPUClusterDimsFunction(
const IRPosition &IRP, Attributor &
A)
1469 : AAAMDGPUClusterDims(IRP,
A) {}
1473 assert(
F &&
"empty associated function");
1480 indicatePessimisticFixpoint();
1482 indicateOptimisticFixpoint();
1486 const std::string getAsStr(Attributor *
A)
const override {
1496 void trackStatistics()
const override {}
1499 auto OldState = Attr;
1501 auto CheckCallSite = [&](AbstractCallSite CS) {
1502 const auto *CallerAA =
A.getAAFor<AAAMDGPUClusterDims>(
1504 DepClassTy::REQUIRED);
1505 if (!CallerAA || !CallerAA->isValidState())
1508 return merge(CallerAA->getClusterDims());
1511 bool UsedAssumedInformation =
false;
1512 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
1514 UsedAssumedInformation))
1515 return indicatePessimisticFixpoint();
1517 return OldState == Attr ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED;
1522 return ChangeStatus::UNCHANGED;
1523 return A.manifestAttrs(
1525 {Attribute::get(getAssociatedFunction()->
getContext(), AttrName,
1530 const AMDGPU::ClusterDimsAttr &getClusterDims()
const override {
1535 bool merge(
const AMDGPU::ClusterDimsAttr &
Other) {
1550 if (
Other.isUnknown())
1575 AMDGPU::ClusterDimsAttr Attr;
1577 static constexpr char AttrName[] =
"amdgpu-cluster-dims";
1580AAAMDGPUClusterDims &
1581AAAMDGPUClusterDims::createForPosition(
const IRPosition &IRP, Attributor &
A) {
1583 return *
new (
A.Allocator) AAAMDGPUClusterDimsFunction(IRP,
A);
1584 llvm_unreachable(
"AAAMDGPUClusterDims is only valid for function position");
1587static bool runImpl(
Module &M, AnalysisGetter &AG, TargetMachine &TM,
1588 AMDGPUAttributorOptions
Options,
1590 SetVector<Function *> Functions;
1591 for (Function &
F : M) {
1592 if (!
F.isIntrinsic())
1596 CallGraphUpdater CGUpdater;
1598 AMDGPUInformationCache InfoCache(M, AG,
Allocator,
nullptr, TM);
1599 DenseSet<const char *>
Allowed(
1600 {&AAAMDAttributes::ID, &AAUniformWorkGroupSize::ID,
1602 &AAAMDMaxNumWorkgroups::ID, &AAAMDWavesPerEU::ID,
1606 &AAAMDGPUClusterDims::ID});
1608 AttributorConfig AC(CGUpdater);
1609 AC.IsClosedWorldModule =
Options.IsClosedWorld;
1611 AC.IsModulePass =
true;
1612 AC.DefaultInitializeLiveInternals =
false;
1613 AC.IndirectCalleeSpecializationCallback =
1614 [](Attributor &
A,
const AbstractAttribute &AA, CallBase &CB,
1619 AC.IPOAmendableCB = [](
const Function &
F) {
1620 return F.getCallingConv() == CallingConv::AMDGPU_KERNEL;
1623 Attributor
A(Functions, InfoCache, AC);
1626 StringRef LTOPhaseStr =
to_string(LTOPhase);
1627 dbgs() <<
"[AMDGPUAttributor] Running at phase " << LTOPhaseStr <<
'\n'
1628 <<
"[AMDGPUAttributor] Module " <<
M.getName() <<
" is "
1629 << (AC.IsClosedWorldModule ?
"" :
"not ")
1630 <<
"assumed to be a closed world.\n";
1633 for (
auto *
F : Functions) {
1637 CallingConv::ID CC =
F->getCallingConv();
1643 const GCNSubtarget &
ST =
TM.getSubtarget<GCNSubtarget>(*F);
1644 if (!
F->isDeclaration() &&
ST.hasClusters())
1647 if (
ST.hasGFX90AInsts())
1653 Ptr = LI->getPointerOperand();
1655 Ptr =
SI->getPointerOperand();
1657 Ptr = RMW->getPointerOperand();
1659 Ptr = CmpX->getPointerOperand();
1668 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, 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))
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, ArrayRef< StringLiteral > StandardNames)
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.
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)
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.