LLVM 22.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_ballot:
69 // case Intrinsic::dx_wave_readfirst:
70 // case Intrinsic::dx_wave_reduce.and:
71 // case Intrinsic::dx_wave_reduce.or:
72 // case Intrinsic::dx_wave_reduce.xor:
73 // case Intrinsic::dx_wave_prefixop:
74 // case Intrinsic::dx_quad.readat:
75 // case Intrinsic::dx_quad.readacrossx:
76 // case Intrinsic::dx_quad.readacrossy:
77 // case Intrinsic::dx_quad.readacrossdiagonal:
78 // case Intrinsic::dx_wave_prefixballot:
79 // case Intrinsic::dx_wave_match:
80 // case Intrinsic::dx_wavemulti.*:
81 // case Intrinsic::dx_wavemulti.ballot:
82 // case Intrinsic::dx_quad.vote:
83 switch (IID) {
84 default:
85 return false;
86 case Intrinsic::dx_wave_is_first_lane:
87 case Intrinsic::dx_wave_getlaneindex:
88 case Intrinsic::dx_wave_any:
89 case Intrinsic::dx_wave_all:
90 case Intrinsic::dx_wave_readlane:
91 case Intrinsic::dx_wave_active_countbits:
92 // Wave Active Op Variants
93 case Intrinsic::dx_wave_reduce_sum:
94 case Intrinsic::dx_wave_reduce_usum:
95 case Intrinsic::dx_wave_reduce_max:
96 case Intrinsic::dx_wave_reduce_umax:
97 case Intrinsic::dx_wave_reduce_min:
98 case Intrinsic::dx_wave_reduce_umin:
99 return true;
100 }
101}
102
103/// Update the shader flags mask based on the given instruction.
104/// \param CSF Shader flags mask to update.
105/// \param I Instruction to check.
106void ModuleShaderFlags::updateFunctionFlags(ComputedShaderFlags &CSF,
107 const Instruction &I,
109 const ModuleMetadataInfo &MMDI) {
110 if (!CSF.Doubles)
111 CSF.Doubles = I.getType()->getScalarType()->isDoubleTy();
112
113 if (!CSF.Doubles) {
114 for (const Value *Op : I.operands()) {
115 if (Op->getType()->getScalarType()->isDoubleTy()) {
116 CSF.Doubles = true;
117 break;
118 }
119 }
120 }
121
122 if (CSF.Doubles) {
123 switch (I.getOpcode()) {
124 case Instruction::FDiv:
125 case Instruction::UIToFP:
126 case Instruction::SIToFP:
127 case Instruction::FPToUI:
128 case Instruction::FPToSI:
129 CSF.DX11_1_DoubleExtensions = true;
130 break;
131 }
132 }
133
134 if (!CSF.LowPrecisionPresent)
135 CSF.LowPrecisionPresent = I.getType()->getScalarType()->isIntegerTy(16) ||
136 I.getType()->getScalarType()->isHalfTy();
137
138 if (!CSF.LowPrecisionPresent) {
139 for (const Value *Op : I.operands()) {
140 if (Op->getType()->getScalarType()->isIntegerTy(16) ||
141 Op->getType()->getScalarType()->isHalfTy()) {
142 CSF.LowPrecisionPresent = true;
143 break;
144 }
145 }
146 }
147
148 if (CSF.LowPrecisionPresent) {
149 if (CSF.NativeLowPrecisionMode)
150 CSF.NativeLowPrecision = true;
151 else
152 CSF.MinimumPrecision = true;
153 }
154
155 if (!CSF.Int64Ops)
156 CSF.Int64Ops = I.getType()->getScalarType()->isIntegerTy(64);
157
158 if (!CSF.Int64Ops && !isa<LifetimeIntrinsic>(&I)) {
159 for (const Value *Op : I.operands()) {
160 if (Op->getType()->getScalarType()->isIntegerTy(64)) {
161 CSF.Int64Ops = true;
162 break;
163 }
164 }
165 }
166
167 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
168 switch (II->getIntrinsicID()) {
169 default:
170 break;
171 case Intrinsic::dx_resource_handlefrombinding: {
172 dxil::ResourceTypeInfo &RTI = DRTM[cast<TargetExtType>(II->getType())];
173
174 // Set ResMayNotAlias if DXIL validator version >= 1.8 and the function
175 // uses UAVs
176 if (!CSF.ResMayNotAlias && CanSetResMayNotAlias &&
177 MMDI.ValidatorVersion >= VersionTuple(1, 8) && RTI.isUAV())
178 CSF.ResMayNotAlias = true;
179
180 switch (RTI.getResourceKind()) {
183 CSF.EnableRawAndStructuredBuffers = true;
184 break;
185 default:
186 break;
187 }
188 break;
189 }
190 case Intrinsic::dx_resource_load_typedbuffer: {
191 dxil::ResourceTypeInfo &RTI =
192 DRTM[cast<TargetExtType>(II->getArgOperand(0)->getType())];
193 if (RTI.isTyped())
194 CSF.TypedUAVLoadAdditionalFormats |= RTI.getTyped().ElementCount > 1;
195 break;
196 }
197 }
198 }
199 // Handle call instructions
200 if (auto *CI = dyn_cast<CallInst>(&I)) {
201 const Function *CF = CI->getCalledFunction();
202 // Merge-in shader flags mask of the called function in the current module
203 if (FunctionFlags.contains(CF))
204 CSF.merge(FunctionFlags[CF]);
205
206 // TODO: Set DX11_1_DoubleExtensions if I is a call to DXIL intrinsic
207 // DXIL::Opcode::Fma https://github.com/llvm/llvm-project/issues/114554
208
209 CSF.WaveOps |= checkWaveOps(CI->getIntrinsicID());
210 }
211}
212
213/// Set shader flags that apply to all functions within the module
215ModuleShaderFlags::gatherGlobalModuleFlags(const Module &M,
216 const DXILResourceMap &DRM,
217 const ModuleMetadataInfo &MMDI) {
218
219 ComputedShaderFlags CSF;
220
221 // Set DisableOptimizations flag based on the presence of OptimizeNone
222 // attribute of entry functions.
223 if (MMDI.EntryPropertyVec.size() > 0) {
224 CSF.DisableOptimizations = MMDI.EntryPropertyVec[0].Entry->hasFnAttribute(
225 llvm::Attribute::OptimizeNone);
226 // Ensure all entry functions have the same optimization attribute
227 for (const auto &EntryFunProps : MMDI.EntryPropertyVec)
228 if (CSF.DisableOptimizations !=
229 EntryFunProps.Entry->hasFnAttribute(llvm::Attribute::OptimizeNone))
230 EntryFunProps.Entry->getContext().diagnose(DiagnosticInfoUnsupported(
231 *(EntryFunProps.Entry), "Inconsistent optnone attribute "));
232 }
233
234 CSF.UAVsAtEveryStage = hasUAVsAtEveryStage(DRM, MMDI);
235
236 // Set the Max64UAVs flag if the number of UAVs is > 8
237 uint32_t NumUAVs = 0;
238 for (auto &UAV : DRM.uavs())
239 if (MMDI.ValidatorVersion < VersionTuple(1, 6))
240 NumUAVs++;
241 else // MMDI.ValidatorVersion >= VersionTuple(1, 6)
242 NumUAVs += UAV.getBinding().Size;
243 if (NumUAVs > 8)
244 CSF.Max64UAVs = true;
245
246 // Set the module flag that enables native low-precision execution mode.
247 // NativeLowPrecisionMode can only be set when the command line option
248 // -enable-16bit-types is provided. This is indicated by the dx.nativelowprec
249 // module flag being set
250 // This flag is needed even if the module does not use 16-bit types because a
251 // corresponding debug module may include 16-bit types, and tools that use the
252 // debug module may expect it to have the same flags as the original
253 if (auto *NativeLowPrec = mdconst::extract_or_null<ConstantInt>(
254 M.getModuleFlag("dx.nativelowprec")))
255 if (MMDI.ShaderModelVersion >= VersionTuple(6, 2))
256 CSF.NativeLowPrecisionMode = NativeLowPrec->getValue().getBoolValue();
257
258 // Set ResMayNotAlias to true if DXIL validator version < 1.8 and there
259 // are UAVs present globally.
260 if (CanSetResMayNotAlias && MMDI.ValidatorVersion < VersionTuple(1, 8))
261 CSF.ResMayNotAlias = !DRM.uavs().empty();
262
263 return CSF;
264}
265
266/// Construct ModuleShaderFlags for module Module M
268 const DXILResourceMap &DRM,
269 const ModuleMetadataInfo &MMDI) {
270
271 CanSetResMayNotAlias = MMDI.DXILVersion >= VersionTuple(1, 7);
272 // The command line option -res-may-alias will set the dx.resmayalias module
273 // flag to 1, thereby disabling the ability to set the ResMayNotAlias flag
274 if (auto *ResMayAlias = mdconst::extract_or_null<ConstantInt>(
275 M.getModuleFlag("dx.resmayalias")))
276 if (ResMayAlias->getValue().getBoolValue())
277 CanSetResMayNotAlias = false;
278
279 ComputedShaderFlags GlobalSFMask = gatherGlobalModuleFlags(M, DRM, MMDI);
280
281 CallGraph CG(M);
282
283 // Compute Shader Flags Mask for all functions using post-order visit of SCC
284 // of the call graph.
285 for (scc_iterator<CallGraph *> SCCI = scc_begin(&CG); !SCCI.isAtEnd();
286 ++SCCI) {
287 const std::vector<CallGraphNode *> &CurSCC = *SCCI;
288
289 // Union of shader masks of all functions in CurSCC
291 // List of functions in CurSCC that are neither external nor declarations
292 // and hence whose flags are collected
293 SmallVector<Function *> CurSCCFuncs;
294 for (CallGraphNode *CGN : CurSCC) {
295 Function *F = CGN->getFunction();
296 if (!F)
297 continue;
298
299 if (F->isDeclaration()) {
300 assert(!F->getName().starts_with("dx.op.") &&
301 "DXIL Shader Flag analysis should not be run post-lowering.");
302 continue;
303 }
304
305 ComputedShaderFlags CSF = GlobalSFMask;
306 for (const auto &BB : *F)
307 for (const auto &I : BB)
308 updateFunctionFlags(CSF, I, DRTM, MMDI);
309 // Update combined shader flags mask for all functions in this SCC
310 SCCSF.merge(CSF);
311
312 CurSCCFuncs.push_back(F);
313 }
314
315 // Update combined shader flags mask for all functions of the module
316 CombinedSFMask.merge(SCCSF);
317
318 // Shader flags mask of each of the functions in an SCC of the call graph is
319 // the union of all functions in the SCC. Update shader flags masks of
320 // functions in CurSCC accordingly. This is trivially true if SCC contains
321 // one function.
322 for (Function *F : CurSCCFuncs)
323 // Merge SCCSF with that of F
324 FunctionFlags[F].merge(SCCSF);
325 }
326}
327
329 uint64_t FlagVal = (uint64_t) * this;
330 OS << formatv("; Shader Flags Value: {0:x8}\n;\n", FlagVal);
331 if (FlagVal == 0)
332 return;
333 OS << "; Note: shader requires additional functionality:\n";
334#define SHADER_FEATURE_FLAG(FeatureBit, DxilModuleNum, FlagName, Str) \
335 if (FlagName) \
336 (OS << ";").indent(7) << Str << "\n";
337#include "llvm/BinaryFormat/DXContainerConstants.def"
338 OS << "; Note: extra DXIL module flags:\n";
339#define DXIL_MODULE_FLAG(DxilModuleBit, FlagName, Str) \
340 if (FlagName) \
341 (OS << ";").indent(7) << Str << "\n";
342#include "llvm/BinaryFormat/DXContainerConstants.def"
343 OS << ";\n";
344}
345
346/// Return the shader flags mask of the specified function Func.
349 auto Iter = FunctionFlags.find(Func);
350 assert((Iter != FunctionFlags.end() && Iter->first == Func) &&
351 "Get Shader Flags : No Shader Flags Mask exists for function");
352 return Iter->second;
353}
354
355//===----------------------------------------------------------------------===//
356// ShaderFlagsAnalysis and ShaderFlagsAnalysisPrinterPass
357
358// Provide an explicit template instantiation for the static ID.
359AnalysisKey ShaderFlagsAnalysis::Key;
360
366
368 MSFI.initialize(M, DRTM, DRM, MMDI);
369
370 return MSFI;
371}
372
375 const ModuleShaderFlags &FlagsInfo = AM.getResult<ShaderFlagsAnalysis>(M);
376 // Print description of combined shader flags for all module functions
377 OS << "; Combined Shader Flags for Module\n";
378 FlagsInfo.getCombinedFlags().print(OS);
379 // Print shader flags mask for each of the module functions
380 OS << "; Shader Flags for Module Functions\n";
381 for (const auto &F : M.getFunctionList()) {
382 if (F.isDeclaration())
383 continue;
384 const ComputedShaderFlags &SFMask = FlagsInfo.getFunctionFlags(&F);
385 OS << formatv("; Function {0} : {1:x8}\n;\n", F.getName(),
386 (uint64_t)(SFMask));
387 }
388
389 return PreservedAnalyses::all();
390}
391
392//===----------------------------------------------------------------------===//
393// ShaderFlagsAnalysis and ShaderFlagsAnalysisPrinterPass
394
396 DXILResourceTypeMap &DRTM =
397 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
398 DXILResourceMap &DRM =
399 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
400 const ModuleMetadataInfo MMDI =
402
403 MSFI.initialize(M, DRTM, DRM, MMDI);
404 return false;
405}
406
413
415
417 "DXIL Shader Flag Analysis", true, true)
421 "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 ...
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:55
#define I(x, y, z)
Definition MD5.cpp:58
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()
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:302
@ Amplification
Definition Triple.h:309
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:682
This is an optimization pass for GlobalISel generic memory operations.
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