1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! What a lift needs before it writes any code: the interface (signatures, interpolation from the declarations,
//! resources from the declarations named and laid out by the container's reflection where it has any), how the entry
//! point carries it, and the facts the declarations state. Pure data; the module is built from it.
use std::collections::{BTreeMap, BTreeSet};
use iridia::build::Kind;
use iridia::{
Access, BufferKind, BufferLayout, D3dBinding, D3dClass, DomainFacts, EntryIo, GeometryFacts, GsInput,
GsOutput, HullFacts, Interface, Label, Partitioning, Resource, ResourceId, ResourceKind,
ResourceProvenance, SampleType, ScalarType, Stage, StageFacts, StorageTarget, SystemValue, TessDomain,
TessTopology, TextureDim, Value, Varying, VaryingProvenance, entry_io,
};
use naga::ImageDimension;
use crate::{Result, error, read, resource_reflection, varying};
use dxbc_reader::decode::{Declared, Decoded, Register, Selection};
/// A phase of a hull program: the control-point phase, or a fork or join phase of its patch-constant function, with
/// the words of the token stream it covers and how many instances it runs.
#[derive(Clone, Debug)]
pub(crate) struct Phase {
pub kind: PhaseKind,
pub words: std::ops::Range<usize>,
pub instances: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PhaseKind {
ControlPoint,
Fork,
Join,
}
/// The phases of a hull program, in order, from the phase markers among its declarations.
fn phases_of(decoded: &Decoded) -> Result<Vec<Phase>> {
let mut starts: Vec<(usize, PhaseKind)> = decoded
.declarations
.iter()
.filter_map(|d| match d.opcode {
114 => Some((d.word, PhaseKind::ControlPoint)),
115 => Some((d.word, PhaseKind::Fork)),
116 => Some((d.word, PhaseKind::Join)),
_ => None,
})
.collect();
starts.sort_by_key(|(word, _)| *word);
let mut phases = Vec::new();
for (i, (start, kind)) in starts.iter().enumerate() {
let end = starts.get(i.saturating_add(1)).map_or(usize::MAX, |(w, _)| *w);
// the instance count a fork or join phase declares
let mut instances = 1;
for d in &decoded.declarations {
if let Declared::Other { opcode, words, .. } = &d.kind
&& (*start..end).contains(&d.word)
&& matches!((opcode, kind), (153, PhaseKind::Fork) | (154, PhaseKind::Join))
{
let [count] = words[..] else {
return Err(error(
d.word,
format!(
"a phase's instance count of {} words, where it has 1",
words.len()
),
));
};
instances = count;
break;
}
}
phases.push(Phase {
kind: *kind,
words: *start..end,
instances,
});
}
Ok(phases)
}
/// What a program may declare, D3D11's limits: a declaration past them is not a program of the format, and the lifter
/// would allocate locals, array elements or registers for it. `dcl_temps` (r0 to r4095), one `dcl_indexable_temp` array
/// (x#[4096]), a constant buffer (4096 rows of four lanes), thread-group memory (32 KiB), a structured buffer's element
/// (2048 bytes), the registers a `dcl_index_range` covers, a geometry program's output (1024 vertices) and its instances
/// (32).
const MAX_TEMPS: u32 = 4096;
const MAX_INDEXABLE_TEMP: u32 = 4096;
const MAX_CONSTANT_BUFFER_ROWS: u32 = 4096;
const MAX_SHARED_BYTES: u32 = 32 * 1024;
const MAX_STRUCTURE_STRIDE: u32 = 2048;
const MAX_INDEX_RANGE: u32 = 4096;
const MAX_GS_VERTICES: u32 = 1024;
const MAX_GS_INSTANCES: u32 = 32;
/// One declared resource, with what the module's global for it needs.
#[derive(Clone, Debug)]
pub(crate) enum Declaration {
ConstantBuffer {
slot: u32,
rows: u32,
},
Texture(Texture),
/// A typed buffer view: its loads return four lanes.
TypedBuffer {
slot: u32,
},
RawBuffer {
slot: u32,
},
StructuredBuffer {
slot: u32,
stride: u32,
},
Sampler {
slot: u32,
comparison: bool,
},
/// A typed unordered-access texture view.
View(View),
/// An unordered-access view of a buffer: raw, structured or typed.
UavBuffer(UavBuffer),
}
/// An unordered-access buffer view `u<slot>`, with the access the program makes of it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct UavBuffer {
pub slot: u32,
pub kind: UavKind,
pub load: bool,
pub store: bool,
/// The integer type its atomic operations have, when it has any.
pub atomic: Option<naga::Scalar>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UavKind {
Raw,
Structured {
stride: u32,
},
/// A typed buffer: four lanes of this kind per element.
Typed(Kind),
}
/// Thread-group shared memory `g<register>`: its size in words, the element stride of a structured one in bytes.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Shared {
pub register: u32,
pub words: u32,
pub stride: Option<u32>,
pub atomic: Option<naga::Scalar>,
}
/// A typed unordered-access view `u<slot>` of a texture, with the access the program makes of it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct View {
pub slot: u32,
pub dim: ImageDimension,
pub arrayed: bool,
/// What its loads return and its stores take in each lane.
pub kind: Kind,
pub load: bool,
pub store: bool,
/// Atomic operations reach it: the view is a single 32-bit lane (`r32uint` or `r32sint`) and `kind` says which.
pub atomic: bool,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Texture {
pub slot: u32,
pub dim: ImageDimension,
pub arrayed: bool,
pub multi: bool,
/// What a load returns in each lane.
pub kind: Kind,
/// Compared against a reference (`sample_c`, `gather4_c`): a depth image in the module.
pub depth: bool,
}
pub(crate) struct Setup {
pub interface: Interface,
pub io: EntryIo,
pub early_depth_test: bool,
/// Parallel to `interface.resources`.
pub declarations: Vec<Declaration>,
pub immediates: Vec<[u32; 4]>,
pub shared: Vec<Shared>,
/// A compute program's thread group size.
pub workgroup: Option<[u32; 3]>,
/// The compute ids the program declares it reads.
pub ids: BTreeSet<SystemValue>,
pub indexable: Vec<(u32, u32)>,
pub temps: u32,
/// The lanes of each input register the program declares it reads.
pub declared_inputs: BTreeMap<u32, u8>,
/// The registers addressed by a computed index (`dcl_index_range`): whether an output, the first register, how many.
pub index_ranges: Vec<(bool, u32, u32)>,
/// The functions of a program of a stage with no entry point (see [`iridia::stage_functions`]).
pub sigs: Option<Vec<iridia::FunctionSig>>,
/// A hull program's phases (empty for the other stages).
pub phases: Vec<Phase>,
/// The registers of the patch constants (a hull program's outputs of its fork and join phases, a domain
/// program's inputs) as the interface's patch-constant varyings place them, with the lanes declared.
pub declared_patch: BTreeMap<u32, u8>,
pub notes: BTreeSet<String>,
}
impl Setup {
/// Bind the constant buffers `bound` names at the sizes it states: the interface's layouts, and the rows of the
/// buffers' declarations with them.
pub(crate) fn bind_sizes(&mut self, bound: &iridia::BoundSizes) -> Result<()> {
bound
.apply(&mut self.interface)
.map_err(|why| error(0, format!("bound sizes: {why}")))?;
for (resource, d) in self.interface.resources.iter().zip(self.declarations.iter_mut()) {
if let (ResourceKind::ConstantBuffer { layout }, Declaration::ConstantBuffer { rows, .. }) =
(&resource.kind, d)
{
*rows = (*rows).max(layout.size.div_ceil(16));
}
}
Ok(())
}
pub(crate) fn empty() -> Self {
Self {
interface: Interface {
stage: Stage::Pixel,
inputs: Vec::new(),
outputs: Vec::new(),
resources: Vec::new(),
facts: Default::default(),
},
io: EntryIo {
arguments: Vec::new(),
results: Vec::new(),
},
early_depth_test: false,
declarations: Vec::new(),
immediates: Vec::new(),
shared: Vec::new(),
workgroup: None,
ids: BTreeSet::new(),
indexable: Vec::new(),
temps: 0,
declared_inputs: BTreeMap::new(),
index_ranges: Vec::new(),
sigs: None,
phases: Vec::new(),
declared_patch: BTreeMap::new(),
notes: BTreeSet::new(),
}
}
pub(crate) fn new(bytes: &[u8], decoded: &Decoded, stage: Stage) -> Result<Self> {
let (program_type, input_elements, output_elements) =
dxbc_reader::signature_elements(bytes).map_err(read)?;
debug_assert_eq!(crate::reflection::stage_of(program_type), stage);
let mut setup = Self::empty();
let refuse = |detail: String| error(0, detail);
let phases = phases_of(decoded)?;
// a declaration inside a fork or join phase is the patch-constant function's, else the control-point phase's
// or the whole program's
let in_patch_phase = |word: usize| {
phases
.iter()
.any(|p| p.kind != PhaseKind::ControlPoint && p.words.contains(&word))
};
// what the declarations of a hull or domain program state about its patch
let (mut input_points, mut output_points, mut tess_domain) = (0u32, 0u32, 0u32);
let (mut partitioning, mut topology, mut max_factor) = (0u32, 0u32, 64.0f32.to_bits());
// and of a geometry program
let (mut gs_input, mut gs_output, mut gs_vertices, mut gs_instances) = (0u32, 0u32, 0u32, 1u32);
let mut declared_inputs: BTreeMap<u32, u8> = BTreeMap::new();
let (mut primitive_id, mut input_coverage) = (false, false);
let (mut depth, mut coverage, mut stencil) = (None, false, false);
let mut interpolations: Vec<(u32, u8, iridia::Interpolation)> = Vec::new();
let mut declared_outputs: BTreeMap<u32, u8> = BTreeMap::new();
for d in &decoded.declarations {
let at = |detail: String| error(d.word, detail);
match &d.kind {
// a hull program declares them again in each of its phases: the most any of them uses
Declared::Temps(n) => {
if *n > MAX_TEMPS {
return Err(at(format!(
"dcl_temps {n}: D3D has at most {MAX_TEMPS} temporaries"
)));
}
setup.temps = setup.temps.max(*n);
}
Declared::IndexableTemp {
register,
size,
components,
} => {
if *components > 4 || *size == 0 || *size > MAX_INDEXABLE_TEMP {
return Err(at(format!(
"dcl_indexable_temp x{register}[{size}] of {components} components: D3D has 1 to \
{MAX_INDEXABLE_TEMP} elements of 1 to 4 components"
)));
}
setup.indexable.push((*register, *size));
}
Declared::GlobalFlags(flags) => {
if flags & 2 != 0 {
return Err(at(
"double precision is enabled (global flag): doubles are not lifted".into(),
));
}
if flags & 4 != 0 {
setup.early_depth_test = true;
}
if flags & 0x20 != 0 {
setup
.notes
.insert("min-precision operands are computed at 32 bits".into());
}
}
Declared::ImmediateBuffer(rows) => setup.immediates = rows.clone(),
Declared::CustomData { .. } => {}
Declared::Input {
operand,
interpolation,
name,
} => match operand.register {
Register::Input | Register::InputControlPoint => {
let Selection::Mask(mask) = operand.selection else {
return Err(at("an input declaration without a lane mask".into()));
};
// a control point is indexed first, the register last
let register = operand.indices.last().map_or(0, |i| i.base);
*declared_inputs.entry(register).or_default() |= mask;
if let Some(mode) = interpolation {
let interp = iridia::d3d::interpolation(*mode).map_err(|e| at(e.to_string()))?;
interpolations.push((register, mask, interp));
}
let _ = name;
}
Register::InputPatchConstant => {
let Selection::Mask(mask) = operand.selection else {
return Err(at("a patch constant declaration without a lane mask".into()));
};
let register = operand.indices.first().map_or(0, |i| i.base);
*setup.declared_patch.entry(register).or_default() |= mask;
}
// the phases' numbers and the domain location are arguments of the functions
Register::OutputControlPointId
| Register::ForkInstanceId
| Register::JoinInstanceId
| Register::InputDomainPoint => {}
Register::PrimitiveId => primitive_id = true,
Register::InputCoverage => input_coverage = true,
Register::ThreadId => {
setup.ids.insert(SystemValue::DispatchThreadId);
}
Register::ThreadGroupId => {
setup.ids.insert(SystemValue::GroupId);
}
Register::ThreadIdInGroup => {
setup.ids.insert(SystemValue::GroupThreadId);
}
Register::ThreadIdInGroupFlattened => {
setup.ids.insert(SystemValue::GroupIndex);
}
other => return Err(at(format!("a declared input of register type {other:?}"))),
},
Declared::Output { operand, .. } => match operand.register {
Register::Output => {
let Selection::Mask(mask) = operand.selection else {
return Err(at("an output declaration without a lane mask".into()));
};
let register = operand.indices.first().map_or(0, |i| i.base);
if in_patch_phase(d.word) {
*setup.declared_patch.entry(register).or_default() |= mask;
} else {
*declared_outputs.entry(register).or_default() |= mask;
}
}
Register::OutputDepth => depth = Some(SystemValue::Depth),
Register::OutputDepthGreaterEqual => depth = Some(SystemValue::DepthGreaterEqual),
Register::OutputDepthLessEqual => depth = Some(SystemValue::DepthLessEqual),
Register::OutputCoverage => coverage = true,
Register::OutputStencilRef => stencil = true,
other => return Err(at(format!("a declared output of register type {other:?}"))),
},
Declared::ConstantBuffer {
slot,
rows,
dimensions,
..
} => {
if *dimensions > 2 {
return Err(at("SM5.1 constant buffer declaration".into()));
}
if *rows > MAX_CONSTANT_BUFFER_ROWS {
return Err(at(format!(
"dcl_constantbuffer cb{slot}[{rows}]: D3D has at most {MAX_CONSTANT_BUFFER_ROWS} rows"
)));
}
setup.declarations.push(Declaration::ConstantBuffer {
slot: *slot,
rows: *rows,
});
}
Declared::Sampler { slot, mode } => {
if *mode == 2 {
return Err(at("mono sampler".into()));
}
setup.declarations.push(Declaration::Sampler {
slot: *slot,
comparison: *mode == 1,
});
}
Declared::Resource {
slot,
dimension,
samples,
returns,
..
} => {
let kind = match returns[0] {
1 | 2 | 5 => Kind::F,
3 => Kind::I,
4 | 6 => Kind::U,
other => return Err(at(format!("resource return type {other}"))),
};
let (dim, arrayed) = match dimension {
1 => {
setup.declarations.push(Declaration::TypedBuffer { slot: *slot });
continue;
}
2 => (ImageDimension::D1, false),
3 | 4 => (ImageDimension::D2, false),
5 => (ImageDimension::D3, false),
6 => (ImageDimension::Cube, false),
8 | 9 => (ImageDimension::D2, true),
10 => (ImageDimension::Cube, true),
other => return Err(at(format!("resource dimension {other}"))),
};
setup.declarations.push(Declaration::Texture(Texture {
slot: *slot,
dim,
arrayed,
multi: matches!(dimension, 4 | 9) || *samples != 0,
kind,
depth: false,
}));
}
Declared::ResourceRaw { slot } => {
setup.declarations.push(Declaration::RawBuffer { slot: *slot })
}
Declared::ResourceStructured { slot, stride } => {
if *stride > MAX_STRUCTURE_STRIDE {
return Err(at(format!(
"dcl_resource_structured t{slot}: a stride of {stride} bytes, D3D has at most \
{MAX_STRUCTURE_STRIDE}"
)));
}
setup.declarations.push(Declaration::StructuredBuffer {
slot: *slot,
stride: *stride,
})
}
Declared::UavTyped {
slot,
dimension,
returns,
..
} => {
let kind = match returns[0] {
1 | 2 | 5 => Kind::F,
3 => Kind::I,
4 | 6 => Kind::U,
other => return Err(at(format!("unordered-access view return type {other}"))),
};
let (dim, arrayed) = match dimension {
2 => (ImageDimension::D1, false),
3 => (ImageDimension::D2, false),
5 => (ImageDimension::D3, false),
7 => (ImageDimension::D1, true),
8 => (ImageDimension::D2, true),
1 => {
setup.declarations.push(Declaration::UavBuffer(UavBuffer {
slot: *slot,
kind: UavKind::Typed(kind),
load: false,
store: false,
atomic: None,
}));
continue;
}
_ => return Err(at(format!("unordered-access view dimension {dimension}"))),
};
setup.declarations.push(Declaration::View(View {
slot: *slot,
dim,
arrayed,
kind,
load: false,
store: false,
atomic: false,
}));
}
Declared::UavRaw { slot, .. } => setup.declarations.push(Declaration::UavBuffer(UavBuffer {
slot: *slot,
kind: UavKind::Raw,
load: false,
store: false,
atomic: None,
})),
Declared::UavStructured { slot, stride, .. } => {
if *stride > MAX_STRUCTURE_STRIDE {
return Err(at(format!(
"dcl_uav_structured u{slot}: a stride of {stride} bytes, D3D has at most \
{MAX_STRUCTURE_STRIDE}"
)));
}
setup.declarations.push(Declaration::UavBuffer(UavBuffer {
slot: *slot,
kind: UavKind::Structured {
stride: (*stride).max(4),
},
load: false,
store: false,
atomic: None,
}))
}
Declared::ThreadGroup(size) => setup.workgroup = Some(*size),
Declared::GroupSharedRaw { register, bytes } => {
if *bytes > MAX_SHARED_BYTES {
return Err(at(format!(
"dcl_tgsm_raw g{register}: {bytes} bytes, D3D has at most {MAX_SHARED_BYTES} per \
thread group"
)));
}
setup.shared.push(Shared {
register: *register,
words: bytes.div_ceil(4),
stride: None,
atomic: None,
})
}
Declared::GroupSharedStructured {
register,
stride,
count,
} => {
let words = stride
.div_ceil(4)
.checked_mul(*count)
.filter(|words| words.saturating_mul(4) <= MAX_SHARED_BYTES)
.ok_or_else(|| {
at(format!(
"dcl_tgsm_structured g{register}: {count} elements of {stride} bytes, D3D has at \
most {MAX_SHARED_BYTES} bytes per thread group"
))
})?;
setup.shared.push(Shared {
register: *register,
words,
stride: Some(*stride),
atomic: None,
});
}
// the phases (their markers and instance counts are read from the declarations as a whole), a
// register range the program only addresses statically, and what a hull program states of its patch
Declared::Other {
opcode: 113..=116 | 153 | 154,
..
} => {}
// dcl_index_range: registers the program addresses by a computed index, [operand, first, count]
Declared::Other {
opcode: 91, words, ..
} => {
let [token, first, count] = words[..] else {
return Err(at(format!(
"dcl_index_range of {} words, where it has 3",
words.len()
)));
};
let output = match (token >> 12) & 255 {
1 => false,
2 => true,
other => {
return Err(at(format!(
"dcl_index_range of operand register type {other}: only inputs and outputs are lifted"
)));
}
};
if count == 0 || first.checked_add(count).is_none_or(|end| end > MAX_INDEX_RANGE) {
return Err(at(format!(
"dcl_index_range of {count} registers from {first}: D3D has registers up to \
{MAX_INDEX_RANGE}"
)));
}
setup.index_ranges.push((output, first, count));
}
Declared::Other {
opcode: 93, control, ..
} => gs_input = *control,
Declared::Other {
opcode: 92, control, ..
} => gs_output = *control,
Declared::Other {
opcode: 94, words, ..
} => {
let [count] = words[..] else {
return Err(at(format!("dcl_maxout of {} words, where it has 1", words.len())));
};
if count > MAX_GS_VERTICES {
return Err(at(format!(
"dcl_maxout {count}: D3D has at most {MAX_GS_VERTICES} vertices"
)));
}
gs_vertices = count;
}
Declared::Other {
opcode: 206, words, ..
} => {
let [count] = words[..] else {
return Err(at(format!(
"dcl_gs_instances of {} words, where it has 1",
words.len()
)));
};
if !(1..=MAX_GS_INSTANCES).contains(&count) {
return Err(at(format!(
"dcl_gs_instances {count}: D3D has 1 to {MAX_GS_INSTANCES} instances"
)));
}
gs_instances = count;
}
// dcl_stream: only stream 0 is rasterized; the others are stream output
Declared::Other {
opcode: 143, words, ..
} => {
let [_, stream] = words[..] else {
return Err(at(format!("dcl_stream of {} words, where it has 2", words.len())));
};
if stream != 0 {
return Err(at(
"a geometry program's output to a stream other than 0 is not lifted".into(),
));
}
}
Declared::Other {
opcode: 147, control, ..
} => input_points = *control,
Declared::Other {
opcode: 148, control, ..
} => output_points = *control,
Declared::Other {
opcode: 149, control, ..
} => tess_domain = *control,
Declared::Other {
opcode: 150, control, ..
} => partitioning = *control,
Declared::Other {
opcode: 151, control, ..
} => topology = *control,
Declared::Other {
opcode: 152, words, ..
} => {
let [bits] = words[..] else {
return Err(at(format!(
"dcl_hs_max_tessfactor of {} words, where it has 1",
words.len()
)));
};
max_factor = bits;
}
Declared::Other { opcode, .. } => {
return Err(at(format!(
"{} ({opcode}) is not lifted",
dxbc_reader::decode::opcode_name(*opcode)
)));
}
}
}
setup.declared_inputs = declared_inputs;
setup.phases = phases;
// the access the program makes of each typed view
for ins in &decoded.instructions {
let (operand, store) = match ins.opcode {
163 => (2, false),
164 => (0, true),
_ => continue,
};
let slot = ins
.operands
.get(operand)
.and_then(|o| o.indices.first())
.map_or(0, |i| i.base);
for d in &mut setup.declarations {
if let Declaration::View(v) = d
&& v.slot == slot
{
v.store |= store;
v.load |= !store;
}
}
}
// the access the program makes of each unordered-access buffer and of thread-group memory, and the integer
// type of the atomic operations that reach them
for ins in &decoded.instructions {
let name = ins.name();
let (resource, load, store, atomic) = match name {
"ld_raw" => (3, true, false, None),
"ld_structured" => (4, true, false, None),
"ld_uav_typed" => (3, true, false, None),
"store_raw" | "store_structured" | "store_uav_typed" => (1, false, true, None),
n if n.starts_with("atomic_") => (
1,
true,
true,
Some(if matches!(n, "atomic_imax" | "atomic_imin") {
naga::Scalar::I32
} else {
naga::Scalar::U32
}),
),
n if n.starts_with("imm_atomic_")
&& !matches!(n, "imm_atomic_alloc" | "imm_atomic_consume") =>
{
(
2,
true,
true,
Some(if matches!(n, "imm_atomic_imax" | "imm_atomic_imin") {
naga::Scalar::I32
} else {
naga::Scalar::U32
}),
)
}
_ => continue,
};
// the resource operand is the one after the destination (and the addresses of a load, which come first)
let operand = match name {
"ld_raw" => 2,
"ld_structured" => 3,
"ld_uav_typed" => 2,
n if n.starts_with("imm_atomic_") => 1,
_ => 0,
};
let _ = resource;
let Some(op) = ins.operands.get(operand) else {
continue;
};
let index = op.indices.first().map_or(0, |i| i.base);
match op.register {
Register::Uav => {
for d in &mut setup.declarations {
if let Declaration::UavBuffer(b) = d
&& b.slot == index
{
b.load |= load;
b.store |= store;
if let Some(a) = atomic {
// a signed minimum or maximum makes the buffer's atomics signed
b.atomic = Some(match (b.atomic, a) {
(Some(naga::Scalar::I32), _) | (_, naga::Scalar::I32) => {
naga::Scalar::I32
}
_ => naga::Scalar::U32,
});
}
}
// atomic operations on a typed texture view make it a single 32-bit lane
if let Declaration::View(v) = d
&& v.slot == index
&& let Some(a) = atomic
{
v.atomic = true;
v.kind = if a == naga::Scalar::I32 || v.kind == Kind::I {
Kind::I
} else {
Kind::U
};
}
}
}
Register::GroupSharedMemory => {
for g in &mut setup.shared {
if g.register == index
&& let Some(a) = atomic
{
g.atomic = Some(match (g.atomic, a) {
(Some(naga::Scalar::I32), _) | (_, naga::Scalar::I32) => naga::Scalar::I32,
_ => naga::Scalar::U32,
});
}
}
}
_ => {}
}
}
// a texture compared against a reference is a depth image
for ins in &decoded.instructions {
if matches!(ins.opcode, 70 | 71 | 126) {
let slot = ins
.operands
.get(2)
.and_then(|o| o.indices.first())
.map_or(0, |i| i.base);
for d in &mut setup.declarations {
if let Declaration::Texture(t) = d
&& t.slot == slot
{
t.depth = true;
}
}
}
}
// the signature's elements, every one, as the container declares them (input layouts and stage linking are
// matched against the signature): `used` is false for an element the program does not declare
let mut interface = Interface {
stage,
inputs: Vec::new(),
outputs: Vec::new(),
resources: Vec::new(),
facts: Default::default(),
};
for e in &input_elements {
// a geometry program's primitive number is the function's own argument (`SV_PrimitiveID`, one for the
// primitive), not an input per vertex
if stage == Stage::Geometry && e.system_value == 7 {
continue;
}
let declared = setup
.declared_inputs
.get(&e.register)
.is_some_and(|m| m & e.mask != 0);
// D3D_NAME_PRIMITIVE_ID and _COVERAGE are read as special operands, not through a register
let special = (e.system_value == 7 && primitive_id) || (e.system_value == 66 && input_coverage);
let mut v = varying(e, stage, false)?;
v.used &= declared || special;
interface.inputs.push(v);
}
for e in &output_elements {
let declared = declared_outputs.get(&e.register).is_some_and(|m| m & e.mask != 0);
let mut v = varying(e, stage, true)?;
let keep = match v.system {
// a built-in output has a local only when the program declares it
Some(SystemValue::Depth | SystemValue::DepthGreaterEqual | SystemValue::DepthLessEqual) => {
depth.is_some()
}
Some(SystemValue::Coverage) => coverage,
Some(SystemValue::StencilRef) => stencil,
// the program's own declaration, not the signature's mask of the lanes it writes (that stays in
// provenance, and says which lanes an executor marks written)
_ => {
v.used = declared;
true
}
};
if keep {
interface.outputs.push(v);
}
}
// the interface: signature elements, the interpolation the declarations state, the system values the
// signatures leave out
for input in &mut interface.inputs {
let Some(d3d) = input.provenance.d3d else { continue };
let mut declared = interpolations
.iter()
.filter(|(r, m, _)| *r == d3d.register && m & d3d.mask != 0)
.map(|(_, _, i)| *i);
input.interp = declared.next();
if declared.any(|other| Some(other) != input.interp) {
return Err(refuse(format!(
"input {}{} is declared with different interpolations",
input.label.name, input.label.index
)));
}
}
let special = |name: &str, system: SystemValue, scalar: ScalarType| Varying {
label: Label {
name: name.into(),
index: 0,
},
system: Some(system),
value: Value { scalar, width: 1 },
interp: None,
used: true,
provenance: VaryingProvenance::default(),
};
if primitive_id
&& !matches!(stage, Stage::Hull | Stage::Domain | Stage::Geometry)
&& !interface
.inputs
.iter()
.any(|v| v.system == Some(SystemValue::PrimitiveIndex))
{
interface.inputs.push(special(
"SV_PrimitiveID",
SystemValue::PrimitiveIndex,
ScalarType::Uint,
));
}
if input_coverage
&& !interface
.inputs
.iter()
.any(|v| v.system == Some(SystemValue::Coverage))
{
interface
.inputs
.push(special("SV_Coverage", SystemValue::Coverage, ScalarType::Uint));
}
if let Some(system) = depth {
if !interface.outputs.iter().any(|v| v.system == Some(system)) {
let name = match system {
SystemValue::DepthGreaterEqual => "SV_DepthGreaterEqual",
SystemValue::DepthLessEqual => "SV_DepthLessEqual",
_ => "SV_Depth",
};
interface.outputs.push(special(name, system, ScalarType::Float));
}
if system != SystemValue::Depth {
setup
.notes
.insert("a conservative depth output is written as a plain depth output".into());
}
}
if coverage
&& !interface
.outputs
.iter()
.any(|v| v.system == Some(SystemValue::Coverage))
{
interface
.outputs
.push(special("SV_Coverage", SystemValue::Coverage, ScalarType::Uint));
}
if stencil
&& !interface
.outputs
.iter()
.any(|v| v.system == Some(SystemValue::StencilRef))
{
interface.outputs.push(special(
"SV_StencilRef",
SystemValue::StencilRef,
ScalarType::Uint,
));
}
// the patch of a hull program (its patch constants are written by the fork and join phases) or a domain program
// (it reads them): the patch-constant signature's elements, `used` where the program declares them
if matches!(stage, Stage::Hull | Stage::Domain) {
let output = stage == Stage::Hull;
let mut patch_constants = Vec::new();
for e in dxbc_reader::patch_signature_elements(bytes).map_err(read)? {
let declared = setup
.declared_patch
.get(&e.register)
.is_some_and(|m| m & e.mask != 0);
let mut v = varying(&e, stage, output)?;
v.used = declared;
patch_constants.push(v);
}
let code = |name: &str, value: u32, limit: u32| -> Result<u32> {
if (1..=limit).contains(&value) {
Ok(value)
} else {
Err(refuse(format!("{name}: {value} is not mapped")))
}
};
let domain = match code("dcl_tess_domain", tess_domain, 3)? {
1 => TessDomain::Isoline,
2 => TessDomain::Triangle,
_ => TessDomain::Quad,
};
interface.facts = if output {
StageFacts::Hull(HullFacts {
domain,
partitioning: match code("dcl_tess_partitioning", partitioning, 4)? {
1 => Partitioning::Integer,
2 => Partitioning::Pow2,
3 => Partitioning::FractionalOdd,
_ => Partitioning::FractionalEven,
},
topology: match code("dcl_tess_output_primitive", topology, 4)? {
1 => TessTopology::Point,
2 => TessTopology::Line,
3 => TessTopology::TriangleCw,
_ => TessTopology::TriangleCcw,
},
input_control_points: code("dcl_input_control_point_count", input_points, 32)?,
output_control_points: code("dcl_output_control_point_count", output_points, 32)?,
max_tess_factor_bits: max_factor,
patch_constants,
})
} else {
StageFacts::Domain(DomainFacts {
domain,
input_control_points: code("dcl_input_control_point_count", input_points, 32)?,
patch_constants,
})
};
}
if stage == Stage::Geometry {
let input = match gs_input {
1 => GsInput::Point,
2 => GsInput::Line,
3 => GsInput::Triangle,
6 => GsInput::LineAdjacency,
7 => GsInput::TriangleAdjacency,
other => return Err(refuse(format!("dcl_gs_input_primitive: {other} is not mapped"))),
};
let output = match gs_output {
1 => GsOutput::PointList,
3 => GsOutput::LineStrip,
5 => GsOutput::TriangleStrip,
other => {
return Err(refuse(format!(
"dcl_gs_output_primitive_topology: {other} is not mapped"
)));
}
};
interface.facts = StageFacts::Geometry(GeometryFacts {
input,
output,
max_vertices: gs_vertices,
instances: gs_instances,
});
}
// a compute program's ids are system inputs the signature does not list
for id in setup.ids.clone() {
let (name, width) = match id {
SystemValue::DispatchThreadId => ("SV_DispatchThreadID", 3),
SystemValue::GroupId => ("SV_GroupID", 3),
SystemValue::GroupThreadId => ("SV_GroupThreadID", 3),
_ => ("SV_GroupIndex", 1),
};
let mut v = special(name, id, ScalarType::Uint);
v.value.width = width;
interface.inputs.push(v);
}
// outputs: a stage's depth hint is a plain depth output in the module
setup.interface = interface;
// resources, in declaration order; reflection, where the container has one this reader reads, names them and
// lays out the constant buffers (one that doesn't parse is refused, not taken as absent)
let rdef = resource_reflection(bytes).map_err(|e| refuse(format!("reflection: {e}")))?;
for (i, d) in setup.declarations.iter_mut().enumerate() {
let (class, register, kind, default_name) = match d {
Declaration::ConstantBuffer { slot, rows } => (
D3dClass::ConstantBuffer,
*slot,
ResourceKind::ConstantBuffer {
layout: BufferLayout {
size: rows
.checked_mul(16)
.ok_or_else(|| refuse("constant buffer size".into()))?,
constants: Vec::new(),
},
},
format!("cb{slot}"),
),
Declaration::Texture(t) => (
D3dClass::ShaderResource,
t.slot,
ResourceKind::Texture {
dim: match t.dim {
ImageDimension::D1 => TextureDim::D1,
ImageDimension::D2 => TextureDim::D2,
ImageDimension::D3 => TextureDim::D3,
ImageDimension::Cube => TextureDim::Cube,
},
arrayed: t.arrayed,
multisampled: t.multi,
sample: if t.depth {
SampleType::Depth
} else {
match t.kind {
Kind::I => SampleType::Sint,
Kind::U => SampleType::Uint,
_ => SampleType::Float,
}
},
},
format!("t{}", t.slot),
),
Declaration::TypedBuffer { slot } => {
let scalar = typed_scalar(decoded, *slot);
(
D3dClass::ShaderResource,
*slot,
ResourceKind::Buffer(BufferKind::Typed(Value { scalar, width: 4 })),
format!("t{slot}"),
)
}
Declaration::RawBuffer { slot } => (
D3dClass::ShaderResource,
*slot,
ResourceKind::Buffer(BufferKind::Raw),
format!("t{slot}"),
),
Declaration::StructuredBuffer { slot, stride } => (
D3dClass::ShaderResource,
*slot,
ResourceKind::Buffer(BufferKind::Structured { stride: *stride }),
format!("t{slot}"),
),
Declaration::View(v) => (
D3dClass::UnorderedAccess,
v.slot,
ResourceKind::Storage {
target: StorageTarget::Image {
dim: match v.dim {
ImageDimension::D1 => TextureDim::D1,
ImageDimension::D2 => TextureDim::D2,
ImageDimension::D3 => TextureDim::D3,
ImageDimension::Cube => TextureDim::Cube,
},
arrayed: v.arrayed,
sample: match v.kind {
Kind::I => SampleType::Sint,
Kind::U => SampleType::Uint,
_ => SampleType::Float,
},
},
access: match (v.load, v.store) {
(true, true) => Access::ReadWrite,
(false, true) => Access::Write,
_ => Access::Read,
},
},
format!("u{}", v.slot),
),
Declaration::UavBuffer(b) => (
D3dClass::UnorderedAccess,
b.slot,
ResourceKind::Storage {
target: StorageTarget::Buffer(match b.kind {
UavKind::Raw => BufferKind::Raw,
UavKind::Structured { stride } => BufferKind::Structured { stride },
UavKind::Typed(kind) => BufferKind::Typed(Value {
scalar: match kind {
Kind::I => ScalarType::Sint,
Kind::U => ScalarType::Uint,
_ => ScalarType::Float,
},
width: 4,
}),
}),
access: match (b.load, b.store) {
(true, true) => Access::ReadWrite,
(false, true) => Access::Write,
_ => Access::Read,
},
},
format!("u{}", b.slot),
),
Declaration::Sampler { slot, comparison } => (
D3dClass::Sampler,
*slot,
ResourceKind::Sampler {
comparison: *comparison,
},
format!("s{slot}"),
),
};
let reflected = rdef.as_ref().and_then(|r| {
r.resources.iter().find(|r| {
r.provenance
.d3d
.is_some_and(|b| b.class == class && b.register == register)
})
});
let mut kind = kind;
let mut name = default_name;
if let Some(r) = reflected {
name = r.provenance.name.clone();
if let Some(layout) = &r.provenance.layout
&& let ResourceKind::Buffer(BufferKind::Structured { stride })
| ResourceKind::Storage {
target: StorageTarget::Buffer(BufferKind::Structured { stride }),
..
} = &kind
&& layout.size != *stride
{
return Err(refuse(format!(
"{name}: reflected element size {} disagrees with declared stride {stride}",
layout.size
)));
}
if let (
ResourceKind::ConstantBuffer { layout },
ResourceKind::ConstantBuffer { layout: stated },
) = (&mut kind, &r.kind)
{
let size = layout.size.max(stated.size);
*layout = stated.clone();
layout.size = size;
if let Declaration::ConstantBuffer { rows, .. } = d {
*rows = (*rows).max(size.div_ceil(16));
}
}
}
setup.interface.resources.push(Resource {
id: ResourceId(
u32::try_from(i).map_err(|_| refuse("more than 4294967295 resources".into()))?,
),
kind,
count: 1,
provenance: ResourceProvenance {
name,
d3d: Some(D3dBinding {
class,
register,
space: 0,
}),
counter_of: None,
layout: reflected.and_then(|r| r.provenance.layout.clone()),
},
});
}
// a vertex program that writes no position feeds a tessellator (or a stream-output stage): it is functions
if stage == Stage::Vertex
&& !setup
.interface
.outputs
.iter()
.any(|v| v.system == Some(SystemValue::ClipPosition))
{
setup.interface.facts = StageFacts::VertexWithoutPosition;
}
setup.sigs = iridia::stage_functions(&setup.interface).map_err(refuse)?;
if setup.sigs.is_none() {
setup.io = entry_io(&setup.interface).map_err(refuse)?;
}
Ok(setup)
}
}
/// A typed buffer view's lane type, from its declaration's first return nibble.
fn typed_scalar(decoded: &Decoded, slot: u32) -> ScalarType {
for d in &decoded.declarations {
if let Declared::Resource { slot: s, returns, .. } = &d.kind
&& *s == slot
{
return match returns[0] {
3 => ScalarType::Sint,
4 | 6 => ScalarType::Uint,
_ => ScalarType::Float,
};
}
}
ScalarType::Float
}