LLVM 24.0.0git
DXILSignatureAnalysis.cpp
Go to the documentation of this file.
1//===- DXILSignatureAnalysis.cpp - Semantic signatures --------------------===//
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 "DirectX.h"
11#include "llvm/ADT/STLExtras.h"
15#include "llvm/IR/Constants.h"
18#include "llvm/IR/IntrinsicsDirectX.h"
19#include "llvm/IR/Module.h"
22#include "llvm/Support/Error.h"
24#include <array>
25#include <set>
26
27using namespace llvm;
28using namespace llvm::dxil;
29using namespace llvm::hlsl;
30
31static Error signatureError(const Twine &Message) {
33}
34
35static bool isSignatureAccess(const IntrinsicInst &I) {
36 return I.getIntrinsicID() == Intrinsic::dx_load_input ||
37 I.getIntrinsicID() == Intrinsic::dx_store_output;
38}
39
40// Validate widths before fromMetadata extracts integer values or narrows them.
42 if (!Node || Node->getNumOperands() != 13)
43 return signatureError("expected a 13-operand signature element");
44 for (unsigned I = 0; I != 13; ++I) {
45 if (I == 1 || I == 4)
46 continue;
47 auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(Node->getOperand(I));
48 unsigned Width = (I == 7 || (I >= 9 && I <= 11)) ? 8 : 32;
49 if (!CI || CI->getBitWidth() != Width)
50 return signatureError("expected i" + Twine(Width) + " at operand " +
51 Twine(I));
52 }
53 if (!isa_and_nonnull<MDString>(Node->getOperand(1)))
54 return signatureError("expected semantic name string");
55 auto *Indices = dyn_cast_or_null<MDNode>(Node->getOperand(4));
56 if (!Indices)
57 return signatureError("expected semantic indices node");
58 for (const MDOperand &Index : Indices->operands()) {
60 if (!CI || CI->getBitWidth() != 32)
61 return signatureError("expected i32 semantic index");
62 }
63 return Error::success();
64}
65
71
73 switch (E.SemanticKind) {
74 case dxbc::PSV::SemanticKind::Target:
75 if (E.CompType != ElementType::F16 && E.CompType != ElementType::F32)
76 return signatureError(
77 "SV_Target requires 16- or 32-bit floating-point components");
78 break;
79 case dxbc::PSV::SemanticKind::Position:
80 if (E.Rows != 1 || E.Cols != 4 ||
81 (E.CompType != ElementType::F16 && E.CompType != ElementType::F32))
82 return signatureError(
83 "SV_Position requires one row of four floating-point components");
84 break;
85 case dxbc::PSV::SemanticKind::VertexID:
86 if (E.Rows != 1 || E.Cols != 1 ||
87 (E.CompType != ElementType::I16 && E.CompType != ElementType::U16 &&
88 E.CompType != ElementType::I32 && E.CompType != ElementType::U32))
89 return signatureError(
90 "SV_VertexID requires a scalar 16- or 32-bit integer");
91 break;
92 case dxbc::PSV::SemanticKind::InstanceID:
93 if (E.Rows != 1 || E.Cols != 1 ||
94 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
95 return signatureError(
96 "SV_InstanceID requires a scalar 16- or 32-bit unsigned integer");
97 break;
98 case dxbc::PSV::SemanticKind::ShadingRate:
99 if (E.Rows != 1 || E.Cols != 1 ||
100 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
101 return signatureError(
102 "SV_ShadingRate requires a scalar 16- or 32-bit unsigned integer");
103 break;
104 case dxbc::PSV::SemanticKind::SampleIndex:
105 if (E.Rows != 1 || E.Cols != 1 ||
106 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
107 return signatureError(
108 "SV_SampleIndex requires a scalar 16- or 32-bit unsigned integer");
109 break;
110 case dxbc::PSV::SemanticKind::PrimitiveID:
111 if (E.Rows != 1 || E.Cols != 1 ||
112 (E.CompType != ElementType::U16 && E.CompType != ElementType::U32))
113 return signatureError(
114 "SV_PrimitiveID requires a scalar 16- or 32-bit unsigned integer");
115 break;
116 case dxbc::PSV::SemanticKind::IsFrontFace:
117 if (E.Rows != 1 || E.Cols != 1 ||
118 (E.CompType != ElementType::I32 && E.CompType != ElementType::U32))
119 return signatureError("SV_IsFrontFace requires a scalar 32-bit integer");
120 break;
121 case dxbc::PSV::SemanticKind::Barycentrics:
122 if (E.Rows != 1 || E.Cols != 3 ||
123 (E.CompType != ElementType::F16 && E.CompType != ElementType::F32))
124 return signatureError("SV_Barycentrics requires one row of three 16- or "
125 "32-bit floating-point components");
126 break;
127 default:
128 break;
129 }
130 return Error::success();
131}
132
134 switch (E.SemanticKind) {
135 case dxbc::PSV::SemanticKind::Target:
136 if (E.Rows != 1 || E.SemanticIndices.front() >= 8)
137 return signatureError(
138 "pixel targets require one row and an index within 0-7");
139 break;
140 case dxbc::PSV::SemanticKind::VertexID:
141 if (E.SemanticIndices.front() != 0)
142 return signatureError("SV_VertexID requires semantic index 0");
143 break;
144 case dxbc::PSV::SemanticKind::Barycentrics:
145 if (E.SemanticIndices.front() != 0)
146 return signatureError("SV_Barycentrics requires semantic index 0");
147 break;
148 case dxbc::PSV::SemanticKind::SampleIndex:
149 if (E.SemanticIndices.front() != 0)
150 return signatureError("SV_SampleIndex requires semantic index 0");
151 break;
152 case dxbc::PSV::SemanticKind::PrimitiveID:
153 if (E.SemanticIndices.front() != 0)
154 return signatureError("SV_PrimitiveID requires semantic index 0");
155 break;
156 case dxbc::PSV::SemanticKind::IsFrontFace:
157 if (E.SemanticIndices.front() != 0)
158 return signatureError("SV_IsFrontFace requires semantic index 0");
159 break;
160 default:
161 break;
162 }
163 return Error::success();
164}
165
166static Error
168 const VersionTuple &ShaderModelVersion) {
169 switch (E.SemanticKind) {
170 case dxbc::PSV::SemanticKind::Barycentrics:
171 if (ShaderModelVersion < VersionTuple(6, 1))
172 return signatureError("SV_Barycentrics requires shader model 6.1");
173 break;
174 default:
175 break;
176 }
177 return Error::success();
178}
179
184 const VersionTuple &ShaderModelVersion,
185 bool Native16, unsigned &Extent) {
186 if (!MD)
187 return Error::success();
188 auto *List = dyn_cast<MDNode>(MD);
189 if (!List)
190 return signatureError("expected a signature element list or null");
191
192 std::set<std::pair<std::string, uint32_t>> Semantics;
193 constexpr unsigned MaxAllocatedElements = MaxSignatureRows * 4;
194 unsigned NumAllocated = 0;
195 std::array<uint8_t, MaxSignatureRows> AllocatedColumns = {};
196 std::array<dxbc::PSV::InterpolationMode, MaxSignatureRows> RowModes = {};
197 std::array<bool, MaxSignatureRows> RowNative16 = {};
198 for (const MDOperand &Op : List->operands()) {
200 if (Error Err = checkElementNode(Node))
201 return Err;
203 if (!Parsed)
204 return Parsed.takeError();
205 SemanticSignatureElement E = std::move(*Parsed);
206 if (E.SigId != Out.size())
207 return signatureError("signature IDs must be dense and in list order");
208 if (Stage != Triple::Vertex && Stage != Triple::Pixel)
209 return signatureError("nonempty signatures are currently supported only "
210 "for vertex and pixel entries");
211 if (!E.Rows || E.Rows > MaxSignatureRows)
212 return signatureError("signature row count must be within 1-32");
213 if (E.SemanticName.empty() || E.SemanticName.contains('\0'))
214 return signatureError("invalid semantic name");
215 if (E.CompType != ElementType::F16 && E.CompType != ElementType::F32 &&
216 !isIntegerComponent(E.CompType))
217 return signatureError("unsupported signature component type");
218 if (E.GSStream != 0)
219 return signatureError("nonzero stream requires a geometry output");
220 auto NamedKind = getSemanticKind(E.SemanticName);
221 auto Interpretation = getInterpretationKind(NamedKind, Stage, IO);
222 if (Interpretation == SemanticInterpretation::Invalid)
223 return signatureError("invalid or unsupported semantic for this stage "
224 "and signature category");
225 if (Interpretation == SemanticInterpretation::NotAllocated)
226 return signatureError("semantic accessed by a dedicated intrinsic must "
227 "not appear in an input/output signature");
228 auto ExpectedKind = Interpretation == SemanticInterpretation::Arbitrary
229 ? dxbc::PSV::SemanticKind::Arbitrary
230 : NamedKind;
231 if (E.SemanticKind != ExpectedKind)
232 return signatureError("semantic name and kind disagree at this signature "
233 "point");
234 if (Interpretation == SemanticInterpretation::NotPacked) {
235 if (E.isAllocated())
236 return signatureError(E.SemanticName +
237 " must not have an allocated location");
238 } else {
239 if (!E.isAllocated())
240 return signatureError("signature element " + Twine(E.SigId) + " ('" +
241 E.SemanticName + "') has no allocated location");
242 if (E.StartRow >= MaxSignatureRows ||
243 E.Rows > MaxSignatureRows - E.StartRow || E.StartCol + E.Cols > 4)
244 return signatureError(
245 "allocated signature element exceeds register bounds");
246 }
247 if (E.InterpMode == dxbc::PSV::InterpolationMode::Invalid)
248 return signatureError("invalid interpolation mode");
249
250 for (uint32_t Index : E.SemanticIndices)
251 if (!Semantics.emplace(E.SemanticName.upper(), Index).second)
252 return signatureError("duplicate semantic name and index");
253 if (Error Err = diagnoseSemanticType(E))
254 return Err;
255 if (Error Err = diagnoseSemanticIndex(E))
256 return Err;
257 if (Error Err = diagnoseSemanticShaderModel(E, ShaderModelVersion))
258 return Err;
259 if (E.SemanticKind == dxbc::PSV::SemanticKind::Barycentrics) {
261 if (E.InterpMode == Mode::Undefined || E.InterpMode == Mode::Constant)
262 return signatureError("SV_Barycentrics requires perspective or "
263 "noperspective interpolation");
264 }
265
266 if (Stage == Triple::Vertex && IO == IOType::In &&
267 (E.StartRow != Extent || E.StartCol != 0))
268 return signatureError("vertex inputs require stacked locations in "
269 "signature order (element " +
270 Twine(E.SigId) + ")");
271 if (Interpretation == SemanticInterpretation::Target &&
272 (E.StartRow != E.SemanticIndices.front() || E.StartCol != 0))
273 return signatureError("pixel target location must match its semantic "
274 "index at column 0");
275 if (Stage == Triple::Pixel && IO == IOType::In &&
276 isIntegerComponent(E.CompType) &&
277 E.InterpMode != dxbc::PSV::InterpolationMode::Constant)
278 return signatureError(
279 "integer pixel inputs require constant interpolation");
280
281 if (E.isAllocated()) {
282 if (++NumAllocated > MaxAllocatedElements)
283 return signatureError("too many signature elements");
284 // Co-packed elements must obey row constraints, even when their component
285 // masks do not overlap. Min-precision types occupy 32-bit components.
286 bool IsNative16 = Native16 && (E.CompType == ElementType::F16 ||
287 E.CompType == ElementType::I16 ||
288 E.CompType == ElementType::U16);
289 uint8_t Mask = E.getDeclaredMask();
290 for (unsigned Row = E.StartRow; Row != E.StartRow + E.Rows; ++Row) {
291 if (AllocatedColumns[Row] & Mask)
292 return signatureError("signature elements overlap at row " +
293 Twine(Row) + " (element " + Twine(E.SigId) +
294 ")");
295 if (AllocatedColumns[Row] && RowModes[Row] != E.InterpMode)
296 return signatureError(
297 "signature elements have different interpolation "
298 "modes at row " +
299 Twine(Row) + " (element " + Twine(E.SigId) + ")");
300 if (AllocatedColumns[Row] && RowNative16[Row] != IsNative16)
301 return signatureError("signature elements have different component "
302 "widths at row " +
303 Twine(Row) + " (element " + Twine(E.SigId) +
304 ")");
305 AllocatedColumns[Row] |= Mask;
306 RowModes[Row] = E.InterpMode;
307 RowNative16[Row] = IsNative16;
308 }
309 Extent = std::max(Extent, E.StartRow + E.Rows);
310 }
311 E.SemanticName = Info.Names.insert(E.SemanticName).first->getKey();
312
313 // Access masks will be recomputed so reset to 0 here.
314 E.UsageMask = 0;
315 E.DynIndexMask = 0;
316 Out.push_back(std::move(E));
317 }
318 return Error::success();
319}
320
322 bool Input = I.getIntrinsicID() == Intrinsic::dx_load_input;
323 auto &Elements = Input ? Sig.Inputs : Sig.Outputs;
324 auto *ID = dyn_cast<ConstantInt>(I.getArgOperand(0));
325 auto *Col = dyn_cast<ConstantInt>(I.getArgOperand(2));
326 StringRef Category = Input ? "input" : "output";
327 assert(ID && "signature ID is marked as ImmArg and must be constant");
328 if (ID->getZExtValue() >= Elements.size())
329 return signatureError(Category +
330 " signature: signature access has an invalid element "
331 "ID " +
332 Twine(ID->getZExtValue()));
333 auto &E = Elements[ID->getZExtValue()];
334 auto AccessError = [&](const Twine &Message) {
335 return signatureError(Category + " signature element " + Twine(E.SigId) +
336 " ('" + E.SemanticName + "'): " + Message);
337 };
338 if (E.SemanticKind == dxbc::PSV::SemanticKind::SampleIndex)
339 return AccessError("must not be read with dx.op.load/store");
340 Type *Ty = Input ? I.getType() : I.getArgOperand(3)->getType();
341 unsigned Width = 1;
342 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
343 Width = VT->getNumElements();
344 Ty = VT->getElementType();
345 }
346 if (!Col || Col->getZExtValue() >= E.Cols ||
347 Width > E.Cols - Col->getZExtValue())
348 return AccessError("signature access has an invalid component index");
349 auto *Row = dyn_cast<ConstantInt>(I.getArgOperand(1));
350 if (Row && Row->getZExtValue() >= E.Rows)
351 return AccessError("signature access has an invalid row index");
352 if (!Row && E.Rows == 1)
353 return AccessError(
354 "dynamic indexing requires a multi-row signature element");
355 bool CorrectType = false;
356 switch (E.CompType) {
357 case ElementType::F16:
358 CorrectType = Ty->isHalfTy();
359 break;
360 case ElementType::F32:
361 CorrectType = Ty->isFloatTy();
362 break;
363 case ElementType::I16:
364 case ElementType::U16:
365 CorrectType = Ty->isIntegerTy(16);
366 break;
367 case ElementType::I1:
368 // Boolean signature elements use the i32 load/store overload.
369 CorrectType = Ty->isIntegerTy(32);
370 break;
371 case ElementType::I32:
372 case ElementType::U32:
373 CorrectType = Ty->isIntegerTy(32);
374 break;
375 default:
376 llvm_unreachable("invalid signature component type");
377 }
378 if (!CorrectType)
379 return AccessError("signature access type disagrees with its element");
380 uint8_t Mask = ((1U << Width) - 1) << Col->getZExtValue();
381 E.UsageMask |= Mask << E.getStartColOrZero();
382 if (!Row)
383 E.DynIndexMask |= Mask;
384 return Error::success();
385}
386
388 // Each output vector needs four component bits, so one 32-bit word holds
389 // eight vectors. Adding seven rounds up to include a partially filled word.
390 unsigned Words = (Sig.OutputVectors + 7) / 8;
391 Sig.InputOutputMap.assign(Sig.InputVectors * 4 * Words, 0);
392 // Conservatively connect every accessed input component to every written
393 // output component. This includes control, memory, call, and dynamic-index
394 // dependencies without incorrectly claiming that unknown dependencies are
395 // absent. Unused components and padding remain zero. Both DXIL and PSV use
396 // this same map; a more precise dependency analysis can refine it later.
397 for (const auto &Input : Sig.Inputs) {
398 if (!Input.isAllocated())
399 continue;
400 for (unsigned IR = 0; IR != Input.Rows; ++IR)
401 for (unsigned IC = 0; IC != 4; ++IC) {
402 if (!(Input.UsageMask & (1U << IC)))
403 continue;
404 unsigned Base = ((Input.StartRow + IR) * 4 + IC) * Words;
405 for (const auto &Output : Sig.Outputs)
406 for (unsigned OR = 0; OR != Output.Rows; ++OR)
407 for (unsigned OC = 0; OC != 4; ++OC) {
408 if (!(Output.UsageMask & (1U << OC)))
409 continue;
410 unsigned Bit = (Output.StartRow + OR) * 4 + OC;
411 Sig.InputOutputMap[Base + Bit / 32] |= 1U << (Bit % 32);
412 }
413 }
414 }
415}
416
420 if (NamedMDNode *Table = M.getNamedMetadata("dx.semantic.signatures")) {
421 for (const MDNode *Record : Table->operands()) {
422 if (Record->getNumOperands() != 3)
423 return signatureError(
424 "expected an entry/input/output signature triple");
425 auto *VAM = dyn_cast_or_null<ValueAsMetadata>(Record->getOperand(0));
426 auto *F = VAM ? dyn_cast<Function>(VAM->getValue()) : nullptr;
427 if (!F || F->getParent() != &M || F->isDeclaration())
428 return signatureError(
429 "signature entry must be a defined function in the module");
430 auto EP =
432 [F](const EntryProperties &E) { return E.Entry == F; });
433 if (EP == MMI.EntryPropertyVec.end())
434 return signatureError("signature function is not a shader entry");
435 if (Info.Entries.contains(F))
436 return signatureError("duplicate signature record for entry '" +
437 F->getName() + "'");
438 EntrySignature Sig;
439 Sig.Stage = EP->ShaderStage;
441 M.getModuleFlag("dx.nativelowprec")))
442 Sig.UseNative16Bit = !Native->isZero();
443 if (Sig.UseNative16Bit && MMI.ShaderModelVersion < VersionTuple(6, 2))
444 return signatureError(
445 "native 16-bit signatures require shader model 6.2");
446 auto AddContext = [&](Error Err, StringRef Category) -> Error {
447 return signatureError("entry '" + F->getName() + "' " + Category +
448 " signature: " + toString(std::move(Err)));
449 };
450 if (Error Err = parseSignature(
451 Record->getOperand(1), Sig.Inputs, Info, Sig.Stage, IOType::In,
453 return AddContext(std::move(Err), "input");
454 if (Error Err = parseSignature(
455 Record->getOperand(2), Sig.Outputs, Info, Sig.Stage, IOType::Out,
457 return AddContext(std::move(Err), "output");
458 for (const Instruction &I : instructions(F))
459 if (auto *II = dyn_cast<IntrinsicInst>(&I);
461 if (Error Err = analyzeAccess(*II, Sig))
462 return signatureError("entry '" + F->getName() +
463 "': " + toString(std::move(Err)));
465 Info.Entries.try_emplace(F, std::move(Sig));
466 }
467 }
468 // Signature IDs are local to an entry. Do not guess which entry a helper's
469 // accesses belong to, even if that helper happens to have a single caller.
470 for (const Function &F : M)
471 if (!Info.Entries.contains(&F))
472 for (const Instruction &I : instructions(F))
473 if (auto *II = dyn_cast<IntrinsicInst>(&I);
475 return signatureError("signature access in function '" + F.getName() +
476 "' has no entry signature metadata");
477 return std::move(Info);
478}
479
481 const ModuleMetadataInfo &MMI) {
482 auto Result = analyzeModule(M, MMI);
483 if (!Result) {
484 M.getContext().emitError("Invalid semantic signature: " +
485 toString(Result.takeError()));
486 return ModuleSignatureInfo();
487 }
488 return std::move(*Result);
489}
490
493 VersionTuple ValidatorVersion) {
494 if (Elements.empty())
495 return nullptr;
496 auto I32 = [&](uint32_t V) {
497 return ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), V));
498 };
499 auto I8 = [&](uint8_t V) {
500 return ConstantAsMetadata::get(ConstantInt::get(Type::getInt8Ty(Ctx), V));
501 };
503 for (const auto &E : Elements) {
504 SmallVector<Metadata *> Indices, Props;
505 for (uint32_t Index : E.SemanticIndices)
506 Indices.push_back(I32(Index));
507 if (E.GSStream)
508 Props.append({I32(0), I32(E.GSStream)});
509 if (E.DynIndexMask)
510 Props.append({I32(2), I32(E.DynIndexMask)});
511 if (E.UsageMask &&
512 (ValidatorVersion.empty() || ValidatorVersion == VersionTuple(0, 0) ||
513 ValidatorVersion >= VersionTuple(1, 5)))
514 Props.append({I32(3), I32(E.UsageMask >> E.getStartColOrZero())});
516 Ctx, {I32(E.SigId), MDString::get(Ctx, E.SemanticName),
517 I8(static_cast<uint8_t>(E.CompType)),
518 I8(static_cast<uint8_t>(E.SemanticKind)),
519 MDNode::get(Ctx, Indices), I8(static_cast<uint8_t>(E.InterpMode)),
520 I32(E.Rows), I8(E.Cols), I32(E.StartRow), I8(E.StartCol),
521 Props.empty() ? nullptr : MDNode::get(Ctx, Props)}));
522 }
523 return MDNode::get(Ctx, Nodes);
524}
525
527 switch (Type) {
528 case ElementType::I1:
529 return Legacy ? dxbc::SigComponentType::Unknown
530 : dxbc::SigComponentType::UInt32;
531 case ElementType::I16:
532 return dxbc::SigComponentType::SInt16;
533 case ElementType::U16:
534 return dxbc::SigComponentType::UInt16;
535 case ElementType::I32:
536 return dxbc::SigComponentType::SInt32;
537 case ElementType::U32:
538 return dxbc::SigComponentType::UInt32;
539 case ElementType::F16:
540 return dxbc::SigComponentType::Float16;
541 case ElementType::F32:
542 return dxbc::SigComponentType::Float32;
543 default:
544 llvm_unreachable("invalid signature component type");
545 }
546}
547
549 using KindTy = dxbc::PSV::SemanticKind;
550 switch (Kind) {
551 case KindTy::Arbitrary:
552 return dxbc::D3DSystemValue::Undefined;
553 case KindTy::VertexID:
554 return dxbc::D3DSystemValue::VertexID;
555 case KindTy::InstanceID:
556 return dxbc::D3DSystemValue::InstanceID;
557 case KindTy::Position:
558 return dxbc::D3DSystemValue::Position;
559 case KindTy::IsFrontFace:
560 return dxbc::D3DSystemValue::IsFrontFace;
561 case KindTy::ClipDistance:
562 return dxbc::D3DSystemValue::ClipDistance;
563 case KindTy::CullDistance:
564 return dxbc::D3DSystemValue::CullDistance;
565 case KindTy::Target:
566 return dxbc::D3DSystemValue::Target;
567 case KindTy::ShadingRate:
568 return dxbc::D3DSystemValue::ShadingRate;
569 case KindTy::Barycentrics:
570 return dxbc::D3DSystemValue::Barycentrics;
571 case KindTy::SampleIndex:
572 return dxbc::D3DSystemValue::SampleIndex;
573 case KindTy::PrimitiveID:
574 return dxbc::D3DSystemValue::PrimitiveID;
575 default:
576 llvm_unreachable("validated vertex/pixel signature semantic");
577 }
578}
579
580// The DXIL reader normalizes system-value semantic names when loading module
581// metadata. The validator then recreates ISG1/OSG1 from those normalized names
582// and compares the parts byte-for-byte, so the container must use the same
583// spelling even if HLSL (or the source metadata) used a different casing.
585 using Kind = dxbc::PSV::SemanticKind;
586 switch (E.SemanticKind) {
587 case Kind::Arbitrary:
588 return E.SemanticName;
589 case Kind::VertexID:
590 return "SV_VertexID";
591 case Kind::InstanceID:
592 return "SV_InstanceID";
593 case Kind::Position:
594 return "SV_Position";
595 case Kind::IsFrontFace:
596 return "SV_IsFrontFace";
597 case Kind::ClipDistance:
598 return "SV_ClipDistance";
599 case Kind::CullDistance:
600 return "SV_CullDistance";
601 case Kind::Target:
602 return "SV_Target";
603 case Kind::ShadingRate:
604 return "SV_ShadingRate";
605 case Kind::Barycentrics:
606 return "SV_Barycentrics";
607 case Kind::SampleIndex:
608 return "SV_SampleIndex";
609 case Kind::PrimitiveID:
610 return "SV_PrimitiveID";
611 default:
612 llvm_unreachable("validated vertex/pixel signature semantic");
613 }
614}
615
618 bool Input, bool Native16, bool Legacy) {
619 for (const auto &E : Elements) {
620 uint8_t Mask = E.getDeclaredMask();
621 uint8_t ExclusiveMask =
622 Input ? E.getAlwaysReadsMask() : E.getNeverWritesMask();
623 if (Legacy)
624 ExclusiveMask = Input ? 0 : static_cast<uint8_t>(~Mask);
625 for (auto [Row, Index] : enumerate(E.SemanticIndices))
626 Sig.addParam(E.GSStream, getContainerSemanticName(E), Index,
627 getSystemValue(E.SemanticKind),
628 getComponentType(E.CompType, Legacy),
629 E.isAllocated() ? E.StartRow + Row : UnallocatedRow, Mask,
630 ExclusiveMask, E.getMinPrecision(!Native16));
631 }
632}
633
636 bool Legacy) {
637 for (const auto &E : Elements) {
638 auto Type = getComponentType(E.CompType, Legacy);
639 // SigComponentType and PSV ComponentType share COMPONENT_TYPE definitions.
640 Dest.push_back(
641 {E.SemanticKind == dxbc::PSV::SemanticKind::Arbitrary ? E.SemanticName
642 : StringRef(),
643 E.SemanticIndices,
644 E.isAllocated() ? static_cast<uint8_t>(E.StartRow) : uint8_t(0),
645 E.Cols, E.getStartColOrZero(), E.isAllocated(), E.SemanticKind,
646 static_cast<dxbc::PSV::ComponentType>(Type), E.InterpMode,
647 E.DynIndexMask, static_cast<uint8_t>(E.GSStream)});
648 }
649}
650
652 VersionTuple ValidatorVersion) const {
653 if (Inputs.empty() && Outputs.empty())
654 return nullptr;
655 return MDNode::get(Ctx,
656 {emitSignature(Ctx, Inputs, ValidatorVersion),
657 emitSignature(Ctx, Outputs, ValidatorVersion), nullptr});
658}
659
661 mcdxbc::Signature &Output,
662 VersionTuple ValidatorVersion) const {
663 bool Legacy = !ValidatorVersion.empty() &&
664 ValidatorVersion != VersionTuple(0, 0) &&
665 ValidatorVersion < VersionTuple(1, 5);
668}
669
671 // Each output vector needs four component bits, so one 32-bit word holds
672 // eight vectors. Conservatively mark every written output component as
673 // dependent on the view ID, matching the conservative input/output map.
674 SmallVector<uint32_t> Mask((OutputVectors + 7) / 8, 0);
675 for (const auto &Output : Outputs) {
676 if (!Output.isAllocated())
677 continue;
678 for (unsigned R = 0; R != Output.Rows; ++R)
679 for (unsigned C = 0; C != 4; ++C) {
680 if (!(Output.UsageMask & (1U << C)))
681 continue;
682 unsigned Bit = (Output.StartRow + R) * 4 + C;
683 Mask[Bit / 32] |= 1U << (Bit % 32);
684 }
685 }
686 return Mask;
687}
688
690 VersionTuple ValidatorVersion,
691 bool UsesViewID) const {
692 bool Legacy = !ValidatorVersion.empty() &&
693 ValidatorVersion != VersionTuple(0, 0) &&
694 ValidatorVersion < VersionTuple(1, 5);
700 if (UsesViewID)
702 if (Stage == Triple::Vertex)
704 llvm::any_of(Outputs, [](const auto &E) {
705 return E.SemanticKind == dxbc::PSV::SemanticKind::Position;
706 });
707 if (Stage == Triple::Pixel)
709 llvm::any_of(Inputs, [](const auto &E) {
710 return E.InterpMode == dxbc::PSV::InterpolationMode::LinearSample ||
711 E.InterpMode ==
712 dxbc::PSV::InterpolationMode::LinearNoperspectiveSample ||
713 E.SemanticKind == dxbc::PSV::SemanticKind::SampleIndex;
714 });
715}
716
720 if (UsesViewID)
723 return State;
724}
725
727 auto Print = [&](StringRef Name, ArrayRef<SemanticSignatureElement> Elements,
728 unsigned Vectors) {
729 OS << " " << Name << ": " << Elements.size() << " elements, " << Vectors
730 << " vectors\n";
731 for (const auto &E : Elements)
732 OS << " " << E.SigId << ": " << E.SemanticName << " rows=" << E.Rows
733 << " cols=" << unsigned(E.Cols) << " at " << E.StartRow << ":"
734 << unsigned(E.StartCol) << " usage=" << unsigned(E.UsageMask)
735 << " dynamic=" << unsigned(E.DynIndexMask) << '\n';
736 };
737 Print("Inputs", Inputs, InputVectors);
738 Print("Outputs", Outputs, OutputVectors);
739}
740
742 for (const Function &F : M)
743 if (const auto *Sig = get(&F)) {
744 OS << "Semantic signatures for '" << F.getName() << "':\n";
745 Sig->print(OS);
746 }
747}
748
749AnalysisKey SignatureAnalysis::Key;
754
760
762 Info = std::make_unique<ModuleSignatureInfo>(collectSignatures(
763 M, getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata()));
764 return false;
765}
766
771
773 if (Info)
774 Info->print(OS, *M);
775}
776
779 "DXIL Semantic Signature Analysis", false, true)
782 "DXIL Semantic Signature Analysis", false, true)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GlobalVariable * buildSignature(Module &M, Signature &Sig, StringRef Name, StringRef SectionName, const dxil::ModuleMetadataInfo &MMI)
static Error diagnoseSemanticType(const SemanticSignatureElement &E)
static Error diagnoseSemanticIndex(const SemanticSignatureElement &E)
static bool isSignatureAccess(const IntrinsicInst &I)
static bool isIntegerComponent(ElementType Type)
static MDNode * emitSignature(LLVMContext &Ctx, ArrayRef< SemanticSignatureElement > Elements, VersionTuple ValidatorVersion)
static void buildSignature(mcdxbc::Signature &Sig, ArrayRef< SemanticSignatureElement > Elements, bool Input, bool Native16, bool Legacy)
static dxbc::D3DSystemValue getSystemValue(dxbc::PSV::SemanticKind Kind)
static Expected< ModuleSignatureInfo > analyzeModule(Module &M, const ModuleMetadataInfo &MMI)
static ModuleSignatureInfo collectSignatures(Module &M, const ModuleMetadataInfo &MMI)
static dxbc::SigComponentType getComponentType(ElementType Type, bool Legacy)
static void buildDependencyMap(EntrySignature &Sig)
static Error diagnoseSemanticShaderModel(const SemanticSignatureElement &E, const VersionTuple &ShaderModelVersion)
static Error checkElementNode(const MDNode *Node)
static void buildPSVElements(SmallVectorImpl< mcdxbc::PSVSignatureElement > &Dest, ArrayRef< SemanticSignatureElement > Elements, bool Legacy)
static StringRef getContainerSemanticName(const SemanticSignatureElement &E)
static Error signatureError(const Twine &Message)
static Error analyzeAccess(const IntrinsicInst &I, EntrySignature &Sig)
static Error parseSignature(Metadata *MD, SmallVectorImpl< SemanticSignatureElement > &Out, ModuleSignatureInfo &Info, Triple::EnvironmentType Stage, IOType IO, const VersionTuple &ShaderModelVersion, bool Native16, unsigned &Extent)
Module.h This file contains the declarations for the Module class.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
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
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
The Input class is used to parse a yaml document into in-memory structs and vectors.
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.
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:549
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1087
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Tuple of metadata.
Definition Metadata.h:1505
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1806
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
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
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
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:294
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Represents a version number in the form major[.minor[.subminor[.build]]].
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero).
const EntrySignature * get(const Function *F) const
void print(raw_ostream &OS, const Module &M) const
PreservedAnalyses 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...
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
Result run(Module &M, ModuleAnalysisManager &AM)
void addParam(uint32_t Stream, StringRef Name, uint32_t Index, dxbc::D3DSystemValue SystemValue, dxbc::SigComponentType CompType, uint32_t Register, uint8_t Mask, uint8_t ExclusiveMask, dxbc::SigMinPrecision MinPrecision)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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 dxbc::PSV::SemanticKind getSemanticKind(StringRef SemanticName)
static constexpr unsigned MaxSignatureRows
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:721
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
DWARFExpression::Operation Op
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
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
SmallVector< hlsl::SemanticSignatureElement > Inputs
SmallVector< uint32_t > getDependencyState(bool UsesViewID) const
Return the serialized dx.viewIdState words for this entry: input scalar count, output scalar count,...
Triple::EnvironmentType Stage
void buildSignatures(mcdxbc::Signature &Input, mcdxbc::Signature &Output, VersionTuple ValidatorVersion) const
Append ISG1/OSG1 parameters to the supplied builders.
SmallVector< hlsl::SemanticSignatureElement > Outputs
void updatePSV(mcdxbc::PSVRuntimeInfo &PSV, VersionTuple ValidatorVersion, bool UsesViewID) const
Append PSV signature elements and set vector extents, the dependency map, the view ID output mask if ...
SmallVector< uint32_t > getViewIDOutputMask() const
Return the mask of output scalars that depend on the view ID.
MDTuple * getAsMetadata(LLVMContext &Ctx, VersionTuple ValidatorVersion) const
Return the DXIL input/output/patch-constant signature triple.
SmallVector< uint32_t > InputOutputMap
void print(raw_ostream &OS) const
SmallVector< EntryProperties > EntryPropertyVec
static LLVM_ABI Expected< SemanticSignatureElement > fromMetadata(const MDNode *Node)
dxbc::PSV::v3::RuntimeInfo BaseData
SmallVector< PSVSignatureElement > InputElements
SmallVector< PSVSignatureElement > OutputElements
std::array< SmallVector< uint32_t >, 4 > OutputVectorMasks
std::array< SmallVector< uint32_t >, 4 > InputOutputMap