19#include "llvm/IR/IntrinsicsDirectX.h"
28#define DEBUG_TYPE "dxil-resource"
35 case ResourceKind::Texture1D:
37 case ResourceKind::Texture2D:
39 case ResourceKind::Texture2DMS:
41 case ResourceKind::Texture3D:
43 case ResourceKind::TextureCube:
45 case ResourceKind::Texture1DArray:
46 return "Texture1DArray";
47 case ResourceKind::Texture2DArray:
48 return "Texture2DArray";
49 case ResourceKind::Texture2DMSArray:
50 return "Texture2DMSArray";
51 case ResourceKind::TextureCubeArray:
52 return "TextureCubeArray";
53 case ResourceKind::TypedBuffer:
55 case ResourceKind::RawBuffer:
57 case ResourceKind::StructuredBuffer:
58 return "StructuredBuffer";
59 case ResourceKind::CBuffer:
61 case ResourceKind::Sampler:
63 case ResourceKind::TBuffer:
65 case ResourceKind::RTAccelerationStructure:
66 return "RTAccelerationStructure";
67 case ResourceKind::FeedbackTexture2D:
68 return "FeedbackTexture2D";
69 case ResourceKind::FeedbackTexture2DArray:
70 return "FeedbackTexture2DArray";
71 case ResourceKind::NumEntries:
72 case ResourceKind::Invalid:
82 case ElementType::I16:
84 case ElementType::U16:
86 case ElementType::I32:
88 case ElementType::U32:
90 case ElementType::I64:
92 case ElementType::U64:
94 case ElementType::F16:
96 case ElementType::F32:
98 case ElementType::F64:
100 case ElementType::SNormF16:
102 case ElementType::UNormF16:
104 case ElementType::SNormF32:
106 case ElementType::UNormF32:
108 case ElementType::SNormF64:
110 case ElementType::UNormF64:
112 case ElementType::PackedS8x32:
114 case ElementType::PackedU8x32:
116 case ElementType::Invalid:
124 case ElementType::I1:
126 case ElementType::I16:
128 case ElementType::U16:
130 case ElementType::I32:
132 case ElementType::U32:
134 case ElementType::I64:
136 case ElementType::U64:
138 case ElementType::F16:
139 case ElementType::SNormF16:
140 case ElementType::UNormF16:
142 case ElementType::F32:
143 case ElementType::SNormF32:
144 case ElementType::UNormF32:
146 case ElementType::F64:
147 case ElementType::SNormF64:
148 case ElementType::UNormF64:
150 case ElementType::PackedS8x32:
151 return "int8_t4_packed";
152 case ElementType::PackedU8x32:
153 return "uint8_t4_packed";
154 case ElementType::Invalid:
162 case SamplerType::Default:
164 case SamplerType::Comparison:
166 case SamplerType::Mono:
174 case SamplerFeedbackType::MinMip:
176 case SamplerFeedbackType::MipRegionUsed:
177 return "MipRegionUsed";
184 Ty = Ty->getScalarType();
186 if (Ty->isIntegerTy()) {
187 switch (Ty->getIntegerBitWidth()) {
189 return IsSigned ? ElementType::I16 : ElementType::U16;
191 return IsSigned ? ElementType::I32 : ElementType::U32;
193 return IsSigned ? ElementType::I64 : ElementType::U64;
196 return ElementType::Invalid;
198 }
else if (Ty->isFloatTy()) {
199 return ElementType::F32;
200 }
else if (Ty->isDoubleTy()) {
201 return ElementType::F64;
202 }
else if (Ty->isHalfTy()) {
203 return ElementType::F16;
206 return ElementType::Invalid;
220 : HandleTy(HandleTy) {
237 Kind = Ty->getDimension();
240 Kind = Ty->getDimension();
243 Kind = Ty->getDimension();
255 bool IsWriteable,
bool IsROV,
256 Type *ContainedType =
nullptr,
257 bool IsSigned =
true) {
260 DestStream << (IsROV ?
"RasterizerOrdered" :
"RW");
268 ArrayDimensions.
push_back(AT->getNumElements());
269 ContainedType = AT->getElementType();
278 "invalid element type for raw buffer");
282 ElementName = ST->getStructName();
285 DestStream <<
"<" << ElementName;
287 DestStream << VTy->getNumElements();
288 for (
uint64_t Dim : ArrayDimensions)
289 DestStream <<
"[" << Dim <<
"]";
295 if (Ty && Ty->getNumElements() == 1 && Ty->getElementType(0) == ElemType)
305 ElementTypes.
reserve(ST->getNumElements());
306 for (
Type *ElTy : ST->elements()) {
313 if (ElementTypes.
size() == 2)
315 if (ElementTypes[1] == AT->getElementType())
319 if (ElementTypes.
size() == 1)
320 return ElementTypes[0];
327 AT->getNumElements());
345 RTy->isROV(), RTy->getResourceType(), RTy->isSigned());
352 false, RTy->getResourceType(), RTy->isSigned());
358 RTy->isROV(), RTy->getResourceType(), RTy->isSigned());
370 Type *Ty = RTy->getResourceType();
372 RTy->isROV(), RTy->getResourceType(),
true);
386 if (!CBufferName.
empty()) {
388 Name.append(CBufferName);
403 TypeName =
formatv(
"SamplerState<{0}>",
504 return {
isROV(Kind, HandleTy)};
514 return LayoutTy->getSize();
516 return DL.getTypeAllocSize(ElTy);
533 Alignment =
DL.getStructLayout(STy)->getAlignment();
535 return {Stride, AlignLog2};
549 return {RTy->getResourceType(), RTy->isSigned()};
554 return {RTy->getResourceType(), RTy->isSigned()};
558 return {RTy->getResourceType(), RTy->isSigned()};
583 Count = VTy->getNumElements();
584 return {ET, DXILStorageTy,
Count};
597 return HandleTy == RHS.HandleTy;
603 if (std::tie(RC, Kind) < std::tie(RHS.RC, RHS.Kind))
610 if (
isUAV() && RHS.isUAV() &&
getUAV() < RHS.getUAV())
613 getStruct(DummyDL) < RHS.getStruct(DummyDL))
637 OS <<
" IsROV: " << UAVFlags.
IsROV <<
"\n";
644 OS <<
" Buffer Stride: " <<
Struct.Stride <<
"\n";
645 OS <<
" Alignment: " <<
Struct.AlignLog2 <<
"\n";
660 assert(!Symbol &&
"Symbol has already been created");
662 int64_t
Size = Binding.Size;
681 auto getIntMD = [&I32Ty](
uint32_t V) {
685 auto getBoolMD = [&I1Ty](
uint32_t V) {
690 MDVals.
push_back(getIntMD(Binding.RecordID));
691 assert(Symbol &&
"Cannot yet create useful resource metadata without symbol");
694 MDVals.
push_back(getIntMD(Binding.Space));
695 MDVals.
push_back(getIntMD(Binding.LowerBound));
696 MDVals.
push_back(getIntMD(Binding.Size));
742std::pair<uint32_t, uint32_t>
748 bool IsUAV = RTI.
isUAV();
751 bool IsROV = IsUAV && UAVFlags.
IsROV;
753 uint8_t SamplerCmpOrHasCounter = 0;
763 Word0 |= (AlignLog2 & 0xF) << 8;
764 Word0 |= (IsUAV & 1) << 12;
765 Word0 |= (IsROV & 1) << 13;
766 Word0 |= (IsGloballyCoherent & 1) << 14;
767 Word0 |= (SamplerCmpOrHasCounter & 1) << 15;
782 Word1 |= (CompType & 0xFF) << 0;
783 Word1 |= (CompCount & 0xFF) << 8;
784 Word1 |= (SampleCount & 0xFF) << 16;
787 return {Word0, Word1};
793 OS <<
" Name: " << Name <<
"\n";
797 Symbol->printAsOperand(OS);
802 <<
" Record ID: " << Binding.RecordID <<
"\n"
803 <<
" Space: " << Binding.Space <<
"\n"
804 <<
" Lower Bound: " << Binding.LowerBound <<
"\n"
805 <<
" Size: " << Binding.Size <<
"\n";
808 OS <<
" Counter Direction: ";
831 ModuleAnalysisManager::Invalidator &Inv) {
834 return !PAC.preservedWhenStateless();
839 return F.getIntrinsicID() == Intrinsic::dx_resource_updatecounter;
847 case Intrinsic::dx_resource_handlefrombinding:
848 case Intrinsic::dx_resource_handlefromimplicitbinding:
858 assert(CA && CA->isString() &&
"expected constant string");
861 if (Name.ends_with(
'\0'))
862 Name = Name.drop_back(1);
866void DXILResourceMap::populateResourceInfos(
Module &M,
871 if (!
F.isDeclaration())
878 case Intrinsic::dx_resource_handlefrombinding: {
882 for (
User *U :
F.users())
895 Size, HandleTy, Name};
906 const auto &[LCI, LRI, LRTI] =
LHS;
907 const auto &[RCI, RRI, RRTI] =
RHS;
913 return std::tie(LRC, LRI, LRTI) < std::tie(RRC, RRI, RRTI);
915 for (
auto [CI, RI, RTI] : CIToInfos) {
916 if (Infos.empty() || RI != Infos.back())
918 CallMap[CI] = Infos.size() - 1;
923 FirstUAV = FirstCBuffer = FirstSampler =
Size;
925 for (
unsigned I = 0,
E =
Size;
I !=
E; ++
I) {
941 FirstCBuffer = std::min({FirstCBuffer, FirstSampler});
942 FirstUAV = std::min({FirstUAV, FirstCBuffer});
949void DXILResourceMap::populateCounterDirections(
Module &M) {
950 for (Function &
F :
M.functions()) {
954 LLVM_DEBUG(
dbgs() <<
"Update Counter Function: " <<
F.getName() <<
"\n");
956 for (
const User *U :
F.users()) {
958 assert(CI &&
"Users of dx_resource_updateCounter must be call instrs");
966 if (CountLiteral == 0)
970 if (CountLiteral > 0)
979 else if (RBInfo->CounterDirection !=
Direction) {
981 HasInvalidDirection =
true;
988void DXILResourceMap::populate(
Module &M, DXILResourceTypeMap &DRTM) {
989 populateResourceInfos(M, DRTM);
990 populateCounterDirections(M);
995 for (
unsigned I = 0, E = Infos.size();
I != E; ++
I) {
996 OS <<
"Resource " <<
I <<
":\n";
1002 for (
const auto &[CI, Index] : CallMap) {
1003 OS <<
"Call bound to " << Index <<
":";
1012 for (
const Value *V : Phi->operands()) {
1013 Children.append(findByUse(V));
1024 case Intrinsic::dx_resource_handlefrombinding: {
1025 auto Pos = CallMap.find(CI);
1026 assert(Pos != CallMap.end() &&
"HandleFromBinding must be in resource map");
1027 return {&Infos[Pos->second]};
1038 if (
V->getType() != UseType)
1049void DXILResourceBindingInfo::populate(
Module &M, DXILResourceTypeMap &DRTM) {
1050 hlsl::BindingInfoBuilder Builder;
1054 for (Function &
F :
M.functions()) {
1055 if (!
F.isDeclaration())
1058 switch (
F.getIntrinsicID()) {
1061 case Intrinsic::dx_resource_handlefrombinding: {
1065 for (User *U :
F.users())
1069 uint32_t LowerBound =
1077 assert((
Size < 0 || (
unsigned)LowerBound +
Size - 1 <= UINT32_MAX) &&
1078 "upper bound register overflow");
1079 uint32_t UpperBound =
Size < 0 ? UINT32_MAX : LowerBound +
Size - 1;
1085 case Intrinsic::dx_resource_handlefromimplicitbinding: {
1086 HasImplicitBinding =
true;
1093 [
this](
auto,
auto) { this->HasOverlappingBinding =
true; });
1098AnalysisKey DXILResourceTypeAnalysis::Key;
1099AnalysisKey DXILResourceAnalysis::Key;
1100AnalysisKey DXILResourceBindingAnalysis::Key;
1106 Data.populate(M, DRTM);
1114 Data.populate(M, DRTM);
1123 DRM.
print(OS, DRTM, M.getDataLayout());
1127void DXILResourceTypeWrapperPass::anchor() {}
1133 "DXIL Resource Type Analysis",
false,
true)
1153 Map->populate(M, *DRTM);
1162 OS <<
"No resource map has been built!\n";
1165 Map->print(OS, *DRTM, M->getDataLayout());
1168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1174 "DXIL Resources Analysis",
false,
true)
1196 BindingInfo->populate(M, DRTM);
1204 "DXIL Resource Binding Analysis",
false,
true)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static dxil::ElementType toDXILElementType(Type *Ty, bool IsSigned)
static bool isUpdateCounterIntrinsic(Function &F)
static StructType * getOrCreateElementStruct(Type *ElemType, StringRef Name)
static void formatTypeName(SmallString< 64 > &Dest, StringRef Name, bool IsWriteable, bool IsROV, Type *ContainedType=nullptr, bool IsSigned=true)
static StringRef getElementTypeName(ElementType ET)
static std::pair< Type *, bool > getTypedElementType(dxil::ResourceKind Kind, TargetExtType *Ty)
static dxil::ElementType toDXILStorageType(dxil::ElementType ET)
static bool isROV(dxil::ResourceKind Kind, TargetExtType *Ty)
static Type * getTypeWithoutPadding(Type *Ty)
static StringRef getResourceKindName(ResourceKind RK)
static StringRef getSamplerTypeName(SamplerType ST)
static StringRef getSamplerFeedbackTypeName(SamplerFeedbackType SFT)
static StringRef getElementTypeNameForTemplate(ElementType ET)
Module.h This file contains the declarations for the Module class.
Loop::LoopBounds::Direction Direction
Machine Check Debug Module
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file defines the SmallString class.
This file defines the SmallVector class.
Class for arbitrary precision integers.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
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...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
LLVM_ABI DXILResourceMap run(Module &M, ModuleAnalysisManager &AM)
Gather resource info for the module M.
LLVM_ABI DXILResourceBindingInfo run(Module &M, ModuleAnalysisManager &AM)
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
~DXILResourceBindingWrapperPass() override
DXILResourceBindingWrapperPass()
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
LLVM_ABI void print(raw_ostream &OS, DXILResourceTypeMap &DRTM, const DataLayout &DL) const
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &Inv)
DXILResourceTypeWrapperPass()
DXILResourceWrapperPass()
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
~DXILResourceWrapperPass() override
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
A parsed version of the target data layout string in and methods for querying it.
Class to represent fixed width SIMD vectors.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
@ ExternalLinkage
Externally visible function.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
The dx.Layout target extension type.
TargetExtType * getHandleTy() const
LLVM_ABI std::pair< uint32_t, uint32_t > getAnnotateProps(Module &M, dxil::ResourceTypeInfo &RTI) const
LLVM_ABI void print(raw_ostream &OS, dxil::ResourceTypeInfo &RTI, const DataLayout &DL) const
void setBindingID(unsigned ID)
LLVM_ABI GlobalVariable * createSymbol(Module &M, StructType *Ty)
LLVM_ABI MDTuple * getAsMetadata(Module &M, dxil::ResourceTypeInfo &RTI) const
ResourceCounterDirection CounterDirection
dxil::ResourceClass getResourceClass() const
LLVM_ABI uint32_t getMultiSampleCount() const
LLVM_ABI uint32_t getCBufferSize(const DataLayout &DL) const
LLVM_ABI bool operator<(const ResourceTypeInfo &RHS) const
LLVM_ABI bool isUAV() const
LLVM_ABI bool isMultiSample() const
LLVM_ABI bool isSampler() const
LLVM_ABI bool isTyped() const
LLVM_ABI dxil::SamplerType getSamplerType() const
LLVM_ABI ResourceTypeInfo(TargetExtType *HandleTy, const dxil::ResourceClass RC, const dxil::ResourceKind Kind)
LLVM_ABI bool isCBuffer() const
LLVM_ABI TypedInfo getTyped() const
LLVM_ABI StructType * createElementStruct(StringRef CBufferName="")
LLVM_ABI bool isFeedback() const
LLVM_ABI UAVInfo getUAV() const
LLVM_ABI StructInfo getStruct(const DataLayout &DL) const
LLVM_ABI bool isStruct() const
LLVM_ABI dxil::SamplerFeedbackType getFeedbackType() const
LLVM_ABI bool operator==(const ResourceTypeInfo &RHS) const
dxil::ResourceKind getResourceKind() const
LLVM_ABI void print(raw_ostream &OS, const DataLayout &DL) const
void trackBinding(dxil::ResourceClass RC, uint32_t Space, uint32_t LowerBound, uint32_t UpperBound, const void *Cookie)
LLVM_ABI BindingInfo calculateBindingInfo(llvm::function_ref< void(const BindingInfoBuilder &Builder, const Binding &Overlapping)> ReportOverlap)
Calculate the binding info - ReportOverlap will be called once for each overlapping binding.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an SmallVector or SmallString.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
LLVM_ABI StringRef getResourceClassName(ResourceClass RC)
ResourceKind
The kind of resource for an SRV or UAV resource.
@ RTAccelerationStructure
ElementType
The element type of an SRV or UAV resource.
LLVM_ABI StringRef getResourceNameFromBindingCall(CallInst *CI)
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
LLVM_ABI ModulePass * createDXILResourceBindingWrapperPassPass()
void stable_sort(R &&Range)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI ModulePass * createDXILResourceTypeWrapperPassPass()
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
FunctionAddr VTableAddr Count
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
FunctionAddr VTableAddr uintptr_t uintptr_t Data
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
unsigned Log2(Align A)
Returns the log2 of the alignment.
LLVM_ABI ModulePass * createDXILResourceWrapperPassPass()
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
dxil::ElementType DXILStorageTy
dxil::ElementType ElementTy