LLVM 23.0.0git
DXILMetadataAnalysis.cpp
Go to the documentation of this file.
1//=- DXILMetadataAnalysis.cpp - Representation of Module metadata -*- C++ -*=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/APInt.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/IR/Constants.h"
15#include "llvm/IR/Metadata.h"
16#include "llvm/IR/Module.h"
21
22#define DEBUG_TYPE "dxil-metadata-analysis"
23
24using namespace llvm;
25using namespace dxil;
26
29 "compress-srci", cl::ValueOptional,
30 cl::desc("Choose SCRI part compression:"),
31 cl::values(clEnumValN(dxbc::SourceInfo::Contents::CompressionType::None,
32 "none", "No compression"),
33 clEnumValN(dxbc::SourceInfo::Contents::CompressionType::Zlib,
34 "zlib", "Use zlib")),
36
39 const Triple &TT = M.getTargetTriple();
40 MMDAI.DXILVersion = TT.getDXILVersion();
41 MMDAI.ShaderModelVersion = TT.getOSVersion();
42 MMDAI.ShaderProfile = TT.getEnvironment();
43 NamedMDNode *ValidatorVerNode = M.getNamedMetadata("dx.valver");
44 if (ValidatorVerNode) {
45 auto *ValVerMD = cast<MDNode>(ValidatorVerNode->getOperand(0));
46 auto *MajorMD = mdconst::extract<ConstantInt>(ValVerMD->getOperand(0));
47 auto *MinorMD = mdconst::extract<ConstantInt>(ValVerMD->getOperand(1));
48 MMDAI.ValidatorVersion =
49 VersionTuple(MajorMD->getZExtValue(), MinorMD->getZExtValue());
50 }
51
52 NamedMDNode *ContentsNode = M.getNamedMetadata("dx.source.contents");
53 NamedMDNode *ArgsNode = M.getNamedMetadata("dx.source.args");
54 if (ContentsNode && ArgsNode) {
55 MMDAI.SourceInfo.emplace();
56 if (CompressSRCI.getNumOccurrences() > 0) {
57 MMDAI.SourceInfo->setCompressionType(CompressSRCI);
58 } else {
59 // If the option is not specified, pick zlib if available.
60 MMDAI.SourceInfo->setCompressionType(
62 ? dxbc::SourceInfo::Contents::CompressionType::Zlib
63 : dxbc::SourceInfo::Contents::CompressionType::None);
64 }
65 for (Metadata *FileInfoNode : ContentsNode->operands()) {
66 auto *FileInfo = cast<MDTuple>(FileInfoNode);
67 MMDAI.SourceInfo->addFile(
68 cast<MDString>(FileInfo->getOperand(0))->getString(),
69 cast<MDString>(FileInfo->getOperand(1))->getString());
70 }
71 for (Metadata *ArgNode : ArgsNode->getOperand(0)->operands())
72 MMDAI.SourceInfo->addArg(cast<MDString>(ArgNode)->getString(), "");
73 }
74
75 // For all HLSL Shader functions
76 for (auto &F : M.functions()) {
77 if (!F.hasFnAttribute("hlsl.shader"))
78 continue;
79
80 EntryProperties EFP(&F);
81 // Get "hlsl.shader" attribute
82 Attribute EntryAttr = F.getFnAttribute("hlsl.shader");
83 assert(EntryAttr.isValid() &&
84 "Invalid value specified for HLSL function attribute hlsl.shader");
85 StringRef EntryProfile = EntryAttr.getValueAsString();
86 Triple T("", "", "", EntryProfile);
87 EFP.ShaderStage = T.getEnvironment();
88 // Get numthreads attribute value, if one exists
89 StringRef NumThreadsStr =
90 F.getFnAttribute("hlsl.numthreads").getValueAsString();
91 if (!NumThreadsStr.empty()) {
92 SmallVector<StringRef> NumThreadsVec;
93 NumThreadsStr.split(NumThreadsVec, ',');
94 assert(NumThreadsVec.size() == 3 && "Invalid numthreads specified");
95 // Read in the three component values of numthreads
96 [[maybe_unused]] bool Success =
97 llvm::to_integer(NumThreadsVec[0], EFP.NumThreadsX, 10);
98 assert(Success && "Failed to parse X component of numthreads");
99 Success = llvm::to_integer(NumThreadsVec[1], EFP.NumThreadsY, 10);
100 assert(Success && "Failed to parse Y component of numthreads");
101 Success = llvm::to_integer(NumThreadsVec[2], EFP.NumThreadsZ, 10);
102 assert(Success && "Failed to parse Z component of numthreads");
103 }
104 // Get wavesize attribute value, if one exists
105 StringRef WaveSizeStr =
106 F.getFnAttribute("hlsl.wavesize").getValueAsString();
107 if (!WaveSizeStr.empty()) {
108 SmallVector<StringRef> WaveSizeVec;
109 WaveSizeStr.split(WaveSizeVec, ',');
110 assert(WaveSizeVec.size() == 3 && "Invalid wavesize specified");
111 // Read in the three component values of numthreads
112 [[maybe_unused]] bool Success =
113 llvm::to_integer(WaveSizeVec[0], EFP.WaveSizeMin, 10);
114 assert(Success && "Failed to parse Min component of wavesize");
115 Success = llvm::to_integer(WaveSizeVec[1], EFP.WaveSizeMax, 10);
116 assert(Success && "Failed to parse Max component of wavesize");
117 Success = llvm::to_integer(WaveSizeVec[2], EFP.WaveSizePref, 10);
118 assert(Success && "Failed to parse Preferred component of wavesize");
119 }
120 MMDAI.EntryPropertyVec.push_back(EFP);
121 }
122 return MMDAI;
123}
124
126 OS << "Shader Model Version : " << ShaderModelVersion.getAsString() << "\n";
127 OS << "DXIL Version : " << DXILVersion.getAsString() << "\n";
128 OS << "Target Shader Stage : "
130 OS << "Validator Version : " << ValidatorVersion.getAsString() << "\n";
131 for (const auto &EP : EntryPropertyVec) {
132 OS << " " << EP.Entry->getName() << "\n";
133 OS << " Function Shader Stage : "
134 << Triple::getEnvironmentTypeName(EP.ShaderStage) << "\n";
135 OS << " NumThreads: " << EP.NumThreadsX << "," << EP.NumThreadsY << ","
136 << EP.NumThreadsZ << "\n";
137 }
138}
139
140//===----------------------------------------------------------------------===//
141// DXILMetadataAnalysis and DXILMetadataAnalysisPrinterPass
142
143// Provide an explicit template instantiation for the static ID.
144AnalysisKey DXILMetadataAnalysis::Key;
145
150
158
159//===----------------------------------------------------------------------===//
160// DXILMetadataAnalysisWrapperPass
161
164
166
171
173 MetadataInfo.reset(new ModuleMetadataInfo(collectMetadataInfo(M)));
174 return false;
175}
176
178
180 const Module *) const {
181 if (!MetadataInfo) {
182 OS << "No module metadata info has been built!\n";
183 return;
184 }
185 MetadataInfo->print(dbgs());
186}
187
188#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
191#endif
192
193INITIALIZE_PASS(DXILMetadataAnalysisWrapperPass, "dxil-metadata-analysis",
194 "DXIL Module Metadata analysis", false, true)
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
This file contains the declarations for the subclasses of Constant, which represent the different fla...
cl::OptionCategory DXContainerCategory("DXContainer Options")
static cl::opt< dxbc::SourceInfo::Contents::CompressionType > CompressSRCI("compress-srci", cl::ValueOptional, cl::desc("Choose SCRI part compression:"), cl::values(clEnumValN(dxbc::SourceInfo::Contents::CompressionType::None, "none", "No compression"), clEnumValN(dxbc::SourceInfo::Contents::CompressionType::Zlib, "zlib", "Use zlib")), cl::cat(DXContainerCategory))
static ModuleMetadataInfo collectMetadataInfo(Module &M)
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
This file contains the declarations for metadata subclasses.
#define T
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some functions that are useful when dealing with strings.
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.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
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.
LLVM_ABI dxil::ModuleMetadataInfo run(Module &M, ModuleAnalysisManager &AM)
Gather module metadata info for the module M.
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1431
Root of the metadata hierarchy.
Definition Metadata.h:64
ModulePass(char &pid)
Definition Pass.h:257
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1749
LLVM_ABI MDNode * getOperand(unsigned i) const
iterator_range< op_iterator > operands()
Definition Metadata.h:1845
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
static LLVM_ABI StringRef getEnvironmentTypeName(EnvironmentType Kind)
Get the canonical name for the Kind environment.
Definition Triple.cpp:505
Represents a version number in the form major[.minor[.subminor[.build]]].
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
LLVM_ABI bool isAvailable()
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Triple::EnvironmentType ShaderStage
std::optional< mcdxbc::SourceInfoBuilder > SourceInfo
Triple::EnvironmentType ShaderProfile
LLVM_ABI void print(raw_ostream &OS) const
SmallVector< EntryProperties > EntryPropertyVec