LLVM 24.0.0git
SemanticSignatures.cpp
Go to the documentation of this file.
1//===- SemanticSignatures.cpp - HLSL Semantic Signature helpers -----------===//
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 implements a library for working with HLSL shader input and
10/// output semantic signatures and their DirectX metadata representation.
11///
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Enum.h"
17#include "llvm/ADT/bit.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Metadata.h"
20#include "llvm/IR/Type.h"
22#include <algorithm>
23#include <cassert>
24
25using namespace llvm;
26using namespace llvm::hlsl;
28
29namespace {
30
31// Inclusive upper bounds of the operand enums
32constexpr uint32_t MaxCompType =
34constexpr uint32_t MaxSemanticKind =
35 static_cast<uint32_t>(dxbc::PSV::SemanticKind::Invalid);
36constexpr uint32_t MaxInterpMode =
37 static_cast<uint32_t>(dxbc::PSV::InterpolationMode::Invalid);
38
39Error makeError(const Twine &Msg) {
41}
42
43Expected<uint64_t> extractInt(const MDNode *Node, unsigned OpId) {
44 auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(Node->getOperand(OpId));
45 if (!CI)
46 return makeError("expected integer operand " + Twine(OpId));
47 return CI->getZExtValue();
48}
49} // namespace
50
57
60 if (Modifiers == InterpolationModifier::None)
61 return InterpolationMode::Undefined;
62 if (any(Modifiers & InterpolationModifier::NoInterpolation))
64 ? InterpolationMode::Constant
65 : InterpolationMode::Invalid;
66
68 switch (getInterpolationSamplingLocation(Modifiers)) {
70 return NoPerspective ? InterpolationMode::LinearNoperspectiveSample
71 : InterpolationMode::LinearSample;
73 return NoPerspective ? InterpolationMode::LinearNoperspectiveCentroid
74 : InterpolationMode::LinearCentroid;
77 return NoPerspective ? InterpolationMode::LinearNoperspective
78 : InterpolationMode::Linear;
79 default:
80 llvm_unreachable("invalid interpolation sampling location");
81 }
82}
83
87 if (!((Stage == Triple::Pixel && IO == IOType::In) ||
88 (Stage == Triple::Vertex && IO == IOType::Out)))
89 return InterpolationMode::Undefined;
90
91 if (Mode == InterpolationMode::Undefined) {
92 switch (CompType) {
99 Mode = InterpolationMode::Linear;
100 break;
101 default:
102 Mode = InterpolationMode::Constant;
103 break;
104 }
105 }
106
107 if (Kind == dxbc::PSV::SemanticKind::Position) {
108 switch (Mode) {
109 case InterpolationMode::Linear:
110 return InterpolationMode::LinearNoperspective;
111 case InterpolationMode::LinearCentroid:
112 return InterpolationMode::LinearNoperspectiveCentroid;
113 case InterpolationMode::LinearSample:
114 return InterpolationMode::LinearNoperspectiveSample;
115 default:
116 break;
117 }
118 }
119 return Mode;
120}
121
123 if (!SemanticName.consume_front_insensitive("SV_"))
124 return dxbc::PSV::SemanticKind::Arbitrary;
125
126 for (const auto &Kind : dxbc::PSV::getSemanticKinds())
127 if (SemanticName.equals_insensitive(Kind.name()))
128 return Kind.value();
129
130 return dxbc::PSV::SemanticKind::Invalid;
131}
132
135 switch (SemanticKind) {
136 case dxbc::PSV::SemanticKind::Arbitrary: {
137 static constexpr IOType OutOrPatchConstant =
139 static constexpr SemanticStageInfo Stages[] = {
145 {Triple::Mesh, OutOrPatchConstant, SemanticInterpretation::Arbitrary},
146 };
147 return Stages;
148 }
149 case dxbc::PSV::SemanticKind::DispatchThreadID:
150 case dxbc::PSV::SemanticKind::GroupID:
151 case dxbc::PSV::SemanticKind::GroupIndex:
152 case dxbc::PSV::SemanticKind::GroupThreadID: {
153 static constexpr SemanticStageInfo Stages[] = {
158 };
159 return Stages;
160 }
161 case dxbc::PSV::SemanticKind::ViewID: {
162 static constexpr IOType InOrPatchConstant =
164 static constexpr SemanticStageInfo Stages[] = {
167 {Triple::Domain, InOrPatchConstant,
174 };
175 return Stages;
176 }
177 case dxbc::PSV::SemanticKind::Target: {
178 static constexpr SemanticStageInfo Stages[] = {
180 return Stages;
181 }
182 case dxbc::PSV::SemanticKind::VertexID:
183 case dxbc::PSV::SemanticKind::InstanceID: {
184 static constexpr SemanticStageInfo Stages[] = {
186 return Stages;
187 }
188 case dxbc::PSV::SemanticKind::IsFrontFace: {
189 static constexpr SemanticStageInfo Stages[] = {
192 return Stages;
193 }
194 case dxbc::PSV::SemanticKind::ShadingRate: {
195 static constexpr SemanticStageInfo Stages[] = {
203 return Stages;
204 }
205 case dxbc::PSV::SemanticKind::Position: {
206 static constexpr SemanticStageInfo Stages[] = {
218 };
219 return Stages;
220 }
221 case dxbc::PSV::SemanticKind::ClipDistance:
222 case dxbc::PSV::SemanticKind::CullDistance: {
223 static constexpr SemanticStageInfo Stages[] = {
235 };
236 return Stages;
237 }
238 case dxbc::PSV::SemanticKind::TessFactor:
239 case dxbc::PSV::SemanticKind::InsideTessFactor: {
240 static constexpr SemanticStageInfo Stages[] = {
245 };
246 return Stages;
247 }
248 default:
249 return {};
250 }
251}
252
255 Triple::EnvironmentType ShaderStage, IOType IOTy) {
256 assert(llvm::has_single_bit(static_cast<unsigned>(IOTy)) &&
257 "a single IOType is expected, not a mask of IOTypes");
258 for (const SemanticStageInfo &Info : getAvailableStages(SemanticKind))
259 if (Info.Stage == ShaderStage && any(Info.AllowedIOTypesMask & IOTy))
260 return Info.Interpretation;
262}
263
266 // Operand positions within a signature element metadata node.
267 enum class OpIdx : unsigned {
268 SigId,
270 CompType,
274 Rows,
275 Cols,
276 StartRow,
277 StartCol,
278 UsageMask,
280 GSStream,
281 LastEntry = GSStream,
282 };
283 const unsigned NumElementOperands = to_underlying(OpIdx::LastEntry) + 1;
284
285 if (!Node)
286 return makeError("signature element node is null");
287 if (Node->getNumOperands() != NumElementOperands)
288 return makeError("signature element node has wrong number of operands");
289
291
292 Expected<uint64_t> SigId = extractInt(Node, to_underlying(OpIdx::SigId));
293 if (!SigId)
294 return SigId.takeError();
295 Elem.SigId = *SigId;
296
297 auto *Name =
298 dyn_cast<MDString>(Node->getOperand(to_underlying(OpIdx::SemanticName)));
299 if (!Name)
300 return makeError("expected semantic name string");
301 Elem.SemanticName = Name->getString();
302
304 extractInt(Node, to_underlying(OpIdx::CompType));
305 if (!CompType)
306 return CompType.takeError();
307 if (*CompType > MaxCompType)
308 return makeError("invalid component type");
309 Elem.CompType = static_cast<dxil::ElementType>(*CompType);
310
312 extractInt(Node, to_underlying(OpIdx::SemanticKind));
313 if (!SemanticKind)
314 return SemanticKind.takeError();
315 if (*SemanticKind > MaxSemanticKind)
316 return makeError("invalid semantic kind");
317 Elem.SemanticKind = static_cast<dxbc::PSV::SemanticKind>(*SemanticKind);
318
319 auto *Indices =
320 dyn_cast<MDNode>(Node->getOperand(to_underlying(OpIdx::SemanticIndices)));
321 if (!Indices)
322 return makeError("expected semantic indices node");
323 for (unsigned I = 0, E = Indices->getNumOperands(); I != E; ++I) {
324 Expected<uint64_t> Index = extractInt(Indices, I);
325 if (!Index)
326 return Index.takeError();
327 Elem.SemanticIndices.push_back(*Index);
328 }
329
331 extractInt(Node, to_underlying(OpIdx::InterpMode));
332 if (!InterpMode)
333 return InterpMode.takeError();
334 if (*InterpMode > MaxInterpMode)
335 return makeError("invalid interpolation mode");
336 Elem.InterpMode = static_cast<dxbc::PSV::InterpolationMode>(*InterpMode);
337
338 Expected<uint64_t> Rows = extractInt(Node, to_underlying(OpIdx::Rows));
339 if (!Rows)
340 return Rows.takeError();
341 Elem.Rows = *Rows;
342
343 Expected<uint64_t> Cols = extractInt(Node, to_underlying(OpIdx::Cols));
344 if (!Cols)
345 return Cols.takeError();
346 if (*Cols < 1 || *Cols > 4)
347 return makeError("number of components per row must be within 1-4");
348 Elem.Cols = *Cols;
349
351 extractInt(Node, to_underlying(OpIdx::StartRow));
352 if (!StartRow)
353 return StartRow.takeError();
354 Elem.StartRow = *StartRow;
355
357 extractInt(Node, to_underlying(OpIdx::StartCol));
358 if (!StartCol)
359 return StartCol.takeError();
360 if (*StartCol > 3 && *StartCol != UnallocatedCol)
361 return makeError("start column must be within 0-3 or unallocated");
362 Elem.StartCol = *StartCol;
363
364 // The row/col sentinels are always set together
365 if ((Elem.StartRow == UnallocatedRow) != (Elem.StartCol == UnallocatedCol))
366 return makeError("start row and column sentinels must be set together");
367
369 extractInt(Node, to_underlying(OpIdx::UsageMask));
370 if (!UsageMask)
371 return UsageMask.takeError();
372 if (*UsageMask > 0xF)
373 return makeError("usage mask must be a 4-bit value");
374 Elem.UsageMask = *UsageMask;
375
377 extractInt(Node, to_underlying(OpIdx::DynIndexMask));
378 if (!DynIndexMask)
379 return DynIndexMask.takeError();
380 if (*DynIndexMask > 0xF)
381 return makeError("dynamic index mask must be a 4-bit value");
383
385 extractInt(Node, to_underlying(OpIdx::GSStream));
386 if (!GSStream)
387 return GSStream.takeError();
388 if (*GSStream > 3)
389 return makeError("geometry shader stream index must be within 0-3");
390 Elem.GSStream = *GSStream;
391
392 if (Elem.SemanticIndices.size() != Elem.Rows)
393 return makeError(
394 "number of semantic indices must equal the number of rows");
395
396 return Elem;
397}
398
400 Type *I32Ty = Type::getInt32Ty(Ctx);
401 Type *I8Ty = Type::getInt8Ty(Ctx);
402 auto GetI32 = [&](uint32_t Val) -> Metadata * {
403 return ConstantAsMetadata::get(ConstantInt::get(I32Ty, Val));
404 };
405 auto GetI8 = [&](uint8_t Val) -> Metadata * {
406 return ConstantAsMetadata::get(ConstantInt::get(I8Ty, Val));
407 };
408
410 for (uint32_t Index : SemanticIndices)
411 IndexOps.push_back(GetI32(Index));
412
413 return MDNode::get(Ctx,
414 {GetI32(SigId), MDString::get(Ctx, SemanticName),
415 GetI32(static_cast<uint32_t>(CompType)),
416 GetI32(static_cast<uint32_t>(SemanticKind)),
417 MDNode::get(Ctx, IndexOps),
418 GetI32(static_cast<uint32_t>(InterpMode)), GetI32(Rows),
419 GetI8(Cols), GetI32(StartRow), GetI8(StartCol),
420 GetI8(UsageMask), GetI8(DynIndexMask), GetI32(GSStream)});
421}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
const char * Msg
This file contains library features backported from future STL versions.
This file implements the C++20 <bit> header.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
Root of the metadata hierarchy.
Definition Metadata.h:64
void push_back(const T &Elt)
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
bool equals_insensitive(StringRef RHS) const
Check for string equality, ignoring case.
Definition StringRef.h:170
bool consume_front_insensitive(StringRef Prefix)
Returns true if this StringRef has the given prefix, ignoring case, and removes that prefix.
Definition StringRef.h:681
@ Amplification
Definition Triple.h:412
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI EnumStrings< SemanticKind, 1 > getSemanticKinds()
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
static constexpr uint32_t UnallocatedRow
LLVM_ABI SemanticInterpretation getInterpretationKind(dxbc::PSV::SemanticKind SemanticKind, Triple::EnvironmentType ShaderStage, IOType IOTy)
LLVM_ABI ArrayRef< SemanticStageInfo > getAvailableStages(dxbc::PSV::SemanticKind SemanticKind)
LLVM_ABI dxbc::PSV::InterpolationMode getInterpolationMode(InterpolationModifier Modifiers)
LLVM_ABI dxbc::PSV::InterpolationMode normalizeInterpolationMode(dxbc::PSV::InterpolationMode Mode, dxil::ElementType CompType, dxbc::PSV::SemanticKind Kind, Triple::EnvironmentType Stage, IOType IO)
LLVM_ABI InterpolationModifier getInterpolationSamplingLocation(InterpolationModifier Modifiers)
LLVM_ABI dxbc::PSV::SemanticKind getSemanticKind(StringRef SemanticName)
static constexpr uint8_t UnallocatedCol
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:720
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
static LLVM_ABI Expected< SemanticSignatureElement > fromMetadata(const MDNode *Node)
dxbc::PSV::InterpolationMode InterpMode
LLVM_ABI MDNode * toMetadata(LLVMContext &Ctx) const