LLVM 23.0.0git
DXILShaderFlags.cpp
Go to the documentation of this file.
1//===- DXILShaderFlags.cpp - DXIL Shader Flags helper objects -------------===//
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///
9/// \file This file contains helper objects and APIs for working with DXIL
10/// Shader Flags.
11///
12//===----------------------------------------------------------------------===//
13
14#include "DXILShaderFlags.h"
15#include "DirectX.h"
20#include "llvm/IR/Attributes.h"
22#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/IntrinsicsDirectX.h"
27#include "llvm/IR/Module.h"
31
32using namespace llvm;
33using namespace llvm::dxil;
34
63
64static bool checkWaveOps(Intrinsic::ID IID) {
65 // Currently unsupported intrinsics
66 // case Intrinsic::dx_wave_getlanecount:
67 // case Intrinsic::dx_wave_allequal:
68 // case Intrinsic::dx_wave_readfirst:
69 // case Intrinsic::dx_wave_reduce.and:
70 // case Intrinsic::dx_wave_reduce.or:
71 // case Intrinsic::dx_wave_reduce.xor:
72 // case Intrinsic::dx_wave_prefixop:
73 // case Intrinsic::dx_quad.readat:
74 // case Intrinsic::dx_quad.readacrossx:
75 // case Intrinsic::dx_quad.readacrossy:
76 // case Intrinsic::dx_quad.readacrossdiagonal:
77 // case Intrinsic::dx_wave_prefixballot:
78 // case Intrinsic::dx_wave_match:
79 // case Intrinsic::dx_wavemulti.*:
80 // case Intrinsic::dx_wavemulti.ballot:
81 // case Intrinsic::dx_quad.vote:
82 switch (IID) {
83 default:
84 return false;
85 case Intrinsic::dx_wave_is_first_lane:
86 case Intrinsic::dx_wave_getlaneindex:
87 case Intrinsic::dx_wave_any:
88 case Intrinsic::dx_wave_all:
89 case Intrinsic::dx_wave_readlane:
90 case Intrinsic::dx_wave_active_countbits:
91 case Intrinsic::dx_wave_ballot:
92 case Intrinsic::dx_wave_prefix_bit_count:
93 // Wave Active Op Variants
94 case Intrinsic::dx_wave_reduce_sum:
95 case Intrinsic::dx_wave_reduce_usum:
96 case Intrinsic::dx_wave_reduce_max:
97 case Intrinsic::dx_wave_reduce_umax:
98 case Intrinsic::dx_wave_reduce_min:
99 case Intrinsic::dx_wave_reduce_umin:
100 return true;
101 }
102}
103
104// Checks to see if the status bit from a load with status
105// instruction is ever extracted. If it is, the module needs
106// to have the TiledResources shader flag set.
108 [[maybe_unused]] Intrinsic::ID IID = II.getIntrinsicID();
109 assert(IID == Intrinsic::dx_resource_load_typedbuffer ||
110 IID == Intrinsic::dx_resource_load_rawbuffer &&
111 "unexpected intrinsic ID");
112 for (const User *U : II.users()) {
113 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U)) {
114 // Resource load operations return a {result, status} pair.
115 // Check if we extract the status
116 if (EVI->getNumIndices() == 1 && EVI->getIndices()[0] == 1)
117 return true;
118 }
119 }
120
121 return false;
122}
123
124/// Update the shader flags mask based on the given instruction.
125/// \param CSF Shader flags mask to update.
126/// \param I Instruction to check.
127void ModuleShaderFlags::updateFunctionFlags(ComputedShaderFlags &CSF,
128 const Instruction &I,
130 const ModuleMetadataInfo &MMDI) {
131 if (!CSF.Doubles)
132 CSF.Doubles = I.getType()->getScalarType()->isDoubleTy();
133
134 if (!CSF.Doubles) {
135 for (const Value *Op : I.operands()) {
136 if (Op->getType()->getScalarType()->isDoubleTy()) {
137 CSF.Doubles = true;
138 break;
139 }
140 }
141 }
142
143 if (CSF.Doubles) {
144 switch (I.getOpcode()) {
145 case Instruction::FDiv:
146 case Instruction::UIToFP:
147 case Instruction::SIToFP:
148 case Instruction::FPToUI:
149 case Instruction::FPToSI:
150 CSF.DX11_1_DoubleExtensions = true;
151 break;
152 }
153 }
154
155 if (!CSF.LowPrecisionPresent)
156 CSF.LowPrecisionPresent = I.getType()->getScalarType()->isIntegerTy(16) ||
157 I.getType()->getScalarType()->isHalfTy();
158
159 if (!CSF.LowPrecisionPresent) {
160 for (const Value *Op : I.operands()) {
161 if (Op->getType()->getScalarType()->isIntegerTy(16) ||
162 Op->getType()->getScalarType()->isHalfTy()) {
163 CSF.LowPrecisionPresent = true;
164 break;
165 }
166 }
167 }
168
169 if (CSF.LowPrecisionPresent) {
170 if (CSF.NativeLowPrecisionMode)
171 CSF.NativeLowPrecision = true;
172 else
173 CSF.MinimumPrecision = true;
174 }
175
176 if (!CSF.Int64Ops)
177 CSF.Int64Ops = I.getType()->getScalarType()->isIntegerTy(64);
178
179 if (!CSF.Int64Ops && !isa<LifetimeIntrinsic>(&I)) {
180 for (const Value *Op : I.operands()) {
181 if (Op->getType()->getScalarType()->isIntegerTy(64)) {
182 CSF.Int64Ops = true;
183 break;
184 }
185 }
186 }
187
188 if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
189 switch (II->getIntrinsicID()) {
190 default:
191 break;
192 case Intrinsic::dx_resource_handlefrombinding: {
193 dxil::ResourceTypeInfo &RTI = DRTM[cast<TargetExtType>(II->getType())];
194
195 // Set ResMayNotAlias if DXIL validator version >= 1.8 and the function
196 // uses UAVs
197 if (!CSF.ResMayNotAlias && CanSetResMayNotAlias &&
198 MMDI.ValidatorVersion >= VersionTuple(1, 8) && RTI.isUAV())
199 CSF.ResMayNotAlias = true;
200
201 switch (RTI.getResourceKind()) {
204 CSF.EnableRawAndStructuredBuffers = true;
205 break;
206 default:
207 break;
208 }
209 break;
210 }
211 case Intrinsic::dx_resource_load_typedbuffer: {
212 dxil::ResourceTypeInfo &RTI =
213 DRTM[cast<TargetExtType>(II->getArgOperand(0)->getType())];
214 if (RTI.isTyped())
215 CSF.TypedUAVLoadAdditionalFormats |= RTI.getTyped().ElementCount > 1;
216 if (!CSF.TiledResources && checkIfStatusIsExtracted(*II))
217 CSF.TiledResources = true;
218 break;
219 }
220 case Intrinsic::dx_resource_load_rawbuffer: {
221 if (!CSF.TiledResources && checkIfStatusIsExtracted(*II))
222 CSF.TiledResources = true;
223 break;
224 }
225 }
226 }
227 // Handle call instructions
228 if (auto *CI = dyn_cast<CallInst>(&I)) {
229 const Function *CF = CI->getCalledFunction();
230 // Merge-in shader flags mask of the called function in the current module
231 if (FunctionFlags.contains(CF))
232 CSF.merge(FunctionFlags[CF]);
233
234 // TODO: Set DX11_1_DoubleExtensions if I is a call to DXIL intrinsic
235 // DXIL::Opcode::Fma https://github.com/llvm/llvm-project/issues/114554
236
237 CSF.WaveOps |= checkWaveOps(CI->getIntrinsicID());
238 }
239}
240
241/// Set shader flags that apply to all functions within the module
243ModuleShaderFlags::gatherGlobalModuleFlags(const Module &M,
244 const DXILResourceMap &DRM,
245 const ModuleMetadataInfo &MMDI) {
246
247 ComputedShaderFlags CSF;
248
249 // Set DisableOptimizations flag based on the presence of OptimizeNone
250 // attribute of entry functions.
251 if (MMDI.EntryPropertyVec.size() > 0) {
252 CSF.DisableOptimizations = MMDI.EntryPropertyVec[0].Entry->hasFnAttribute(
253 llvm::Attribute::OptimizeNone);
254 // Ensure all entry functions have the same optimization attribute
255 for (const auto &EntryFunProps : MMDI.EntryPropertyVec)
256 if (CSF.DisableOptimizations !=
257 EntryFunProps.Entry->hasFnAttribute(llvm::Attribute::OptimizeNone))
258 EntryFunProps.Entry->getContext().diagnose(DiagnosticInfoUnsupported(
259 *(EntryFunProps.Entry), "Inconsistent optnone attribute "));
260 }
261
262 CSF.UAVsAtEveryStage = hasUAVsAtEveryStage(DRM, MMDI);
263
264 // Set the Max64UAVs flag if the number of UAVs is > 8
265 uint32_t NumUAVs = 0;
266 for (auto &UAV : DRM.uavs())
267 if (MMDI.ValidatorVersion < VersionTuple(1, 6))
268 NumUAVs++;
269 else // MMDI.ValidatorVersion >= VersionTuple(1, 6)
270 NumUAVs += UAV.getBinding().Size;
271 if (NumUAVs > 8)
272 CSF.Max64UAVs = true;
273
274 // Set the module flag that enables native low-precision execution mode.
275 // NativeLowPrecisionMode can only be set when the command line option
276 // -enable-16bit-types is provided. This is indicated by the dx.nativelowprec
277 // module flag being set
278 // This flag is needed even if the module does not use 16-bit types because a
279 // corresponding debug module may include 16-bit types, and tools that use the
280 // debug module may expect it to have the same flags as the original
281 if (auto *NativeLowPrec = mdconst::extract_or_null<ConstantInt>(
282 M.getModuleFlag("dx.nativelowprec")))
283 if (MMDI.ShaderModelVersion >= VersionTuple(6, 2))
284 CSF.NativeLowPrecisionMode = NativeLowPrec->getValue().getBoolValue();
285
286 // Set ResMayNotAlias to true if DXIL validator version < 1.8 and there
287 // are UAVs present globally.
288 if (CanSetResMayNotAlias && MMDI.ValidatorVersion < VersionTuple(1, 8))
289 CSF.ResMayNotAlias = !DRM.uavs().empty();
290
291 // The command line option -all-resources-bound will set the
292 // dx.allresourcesbound module flag to 1
293 if (auto *AllResourcesBound = mdconst::extract_or_null<ConstantInt>(
294 M.getModuleFlag("dx.allresourcesbound")))
295 if (AllResourcesBound->getValue().getBoolValue())
296 CSF.AllResourcesBound = true;
297
298 return CSF;
299}
300
301/// Construct ModuleShaderFlags for module Module M
303 const DXILResourceMap &DRM,
304 const ModuleMetadataInfo &MMDI) {
305
306 CanSetResMayNotAlias = MMDI.DXILVersion >= VersionTuple(1, 7);
307 // The command line option -res-may-alias will set the dx.resmayalias module
308 // flag to 1, thereby disabling the ability to set the ResMayNotAlias flag
309 if (auto *ResMayAlias = mdconst::extract_or_null<ConstantInt>(
310 M.getModuleFlag("dx.resmayalias")))
311 if (ResMayAlias->getValue().getBoolValue())
312 CanSetResMayNotAlias = false;
313
314 ComputedShaderFlags GlobalSFMask = gatherGlobalModuleFlags(M, DRM, MMDI);
315
316 CallGraph CG(M);
317
318 // Compute Shader Flags Mask for all functions using post-order visit of SCC
319 // of the call graph.
320 for (scc_iterator<CallGraph *> SCCI = scc_begin(&CG); !SCCI.isAtEnd();
321 ++SCCI) {
322 const std::vector<CallGraphNode *> &CurSCC = *SCCI;
323
324 // Union of shader masks of all functions in CurSCC
326 // List of functions in CurSCC that are neither external nor declarations
327 // and hence whose flags are collected
328 SmallVector<Function *> CurSCCFuncs;
329 for (CallGraphNode *CGN : CurSCC) {
330 Function *F = CGN->getFunction();
331 if (!F)
332 continue;
333
334 if (F->isDeclaration()) {
335 assert(!F->getName().starts_with("dx.op.") &&
336 "DXIL Shader Flag analysis should not be run post-lowering.");
337 continue;
338 }
339
340 ComputedShaderFlags CSF = GlobalSFMask;
341 for (const auto &BB : *F)
342 for (const auto &I : BB)
343 updateFunctionFlags(CSF, I, DRTM, MMDI);
344 // Update combined shader flags mask for all functions in this SCC
345 SCCSF.merge(CSF);
346
347 CurSCCFuncs.push_back(F);
348 }
349
350 // Update combined shader flags mask for all functions of the module
351 CombinedSFMask.merge(SCCSF);
352
353 // Shader flags mask of each of the functions in an SCC of the call graph is
354 // the union of all functions in the SCC. Update shader flags masks of
355 // functions in CurSCC accordingly. This is trivially true if SCC contains
356 // one function.
357 for (Function *F : CurSCCFuncs)
358 // Merge SCCSF with that of F
359 FunctionFlags[F].merge(SCCSF);
360 }
361}
362
364 uint64_t FlagVal = (uint64_t) * this;
365 OS << formatv("; Shader Flags Value: {0:x8}\n;\n", FlagVal);
366 if (FlagVal == 0)
367 return;
368 OS << "; Note: shader requires additional functionality:\n";
369#define SHADER_FEATURE_FLAG(FeatureBit, DxilModuleNum, FlagName, Str) \
370 if (FlagName) \
371 (OS << ";").indent(7) << Str << "\n";
372#include "llvm/BinaryFormat/DXContainerConstants.def"
373 OS << "; Note: extra DXIL module flags:\n";
374#define DXIL_MODULE_FLAG(DxilModuleBit, FlagName, Str) \
375 if (FlagName) \
376 (OS << ";").indent(7) << Str << "\n";
377#include "llvm/BinaryFormat/DXContainerConstants.def"
378 OS << ";\n";
379}
380
381/// Return the shader flags mask of the specified function Func.
384 auto Iter = FunctionFlags.find(Func);
385 assert((Iter != FunctionFlags.end() && Iter->first == Func) &&
386 "Get Shader Flags : No Shader Flags Mask exists for function");
387 return Iter->second;
388}
389
390//===----------------------------------------------------------------------===//
391// ShaderFlagsAnalysis and ShaderFlagsAnalysisPrinterPass
392
393// Provide an explicit template instantiation for the static ID.
394AnalysisKey ShaderFlagsAnalysis::Key;
395
401
403 MSFI.initialize(M, DRTM, DRM, MMDI);
404
405 return MSFI;
406}
407
410 const ModuleShaderFlags &FlagsInfo = AM.getResult<ShaderFlagsAnalysis>(M);
411 // Print description of combined shader flags for all module functions
412 OS << "; Combined Shader Flags for Module\n";
413 FlagsInfo.getCombinedFlags().print(OS);
414 // Print shader flags mask for each of the module functions
415 OS << "; Shader Flags for Module Functions\n";
416 for (const auto &F : M.getFunctionList()) {
417 if (F.isDeclaration())
418 continue;
419 const ComputedShaderFlags &SFMask = FlagsInfo.getFunctionFlags(&F);
420 OS << formatv("; Function {0} : {1:x8}\n;\n", F.getName(),
421 (uint64_t)(SFMask));
422 }
423
424 return PreservedAnalyses::all();
425}
426
427//===----------------------------------------------------------------------===//
428// ShaderFlagsAnalysis and ShaderFlagsAnalysisPrinterPass
429
431 DXILResourceTypeMap &DRTM =
432 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
433 DXILResourceMap &DRM =
434 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
435 const ModuleMetadataInfo MMDI =
437
438 MSFI.initialize(M, DRTM, DRM, MMDI);
439 return false;
440}
441
448
450
452 "DXIL Shader Flag Analysis", true, true)
456 "DXIL Shader Flag Analysis", true, true)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the simple types necessary to represent the attributes associated with functions a...
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
bool checkIfStatusIsExtracted(const IntrinsicInst &II)
static bool hasUAVsAtEveryStage(const DXILResourceMap &DRM, const ModuleMetadataInfo &MMDI)
static bool checkWaveOps(Intrinsic::ID IID)
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file defines the SmallVector class.
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.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
A node in the call graph for a module.
Definition CallGraph.h:162
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
iterator_range< iterator > uavs()
This instruction extracts a struct member or array element value from an aggregate value.
A wrapper class for inspecting calls to intrinsic functions.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
@ RayGeneration
Definition Triple.h:307
@ Amplification
Definition Triple.h:314
Represents a version number in the form major[.minor[.subminor[.build]]].
LLVM_ABI bool isUAV() const
LLVM_ABI bool isTyped() const
LLVM_ABI TypedInfo getTyped() const
dxil::ResourceKind getResourceKind() const
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Wrapper pass for the legacy pass manager.
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.
ModuleShaderFlags run(Module &M, ModuleAnalysisManager &AM)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:49
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
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...
Definition Casting.h:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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
void merge(const ComputedShaderFlags CSF)
void print(raw_ostream &OS=dbgs()) const
Triple::EnvironmentType ShaderProfile
SmallVector< EntryProperties > EntryPropertyVec
const ComputedShaderFlags & getFunctionFlags(const Function *) const
Return the shader flags mask of the specified function Func.
void initialize(Module &, DXILResourceTypeMap &DRTM, const DXILResourceMap &DRM, const ModuleMetadataInfo &MMDI)
Construct ModuleShaderFlags for module Module M.
const ComputedShaderFlags & getCombinedFlags() const