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
use crate::Version;
use std::{
collections::HashMap,
error::Error,
fmt::{self, Display, Formatter},
ops::Range,
string::FromUtf8Error,
};
include!(concat!(env!("OUT_DIR"), "/spirv_parse.rs"));
#[derive(Clone, Debug)]
pub struct Spirv {
version: Version,
bound: u32,
instructions: Vec<Instruction>,
ids: HashMap<Id, IdDataIndices>,
range_capability: Range<usize>,
range_extension: Range<usize>,
range_ext_inst_import: Range<usize>,
memory_model: usize,
range_entry_point: Range<usize>,
range_execution_mode: Range<usize>,
range_name: Range<usize>,
range_decoration: Range<usize>,
range_global: Range<usize>,
}
impl Spirv {
pub fn new(words: &[u32]) -> Result<Spirv, SpirvError> {
if words.len() < 5 {
return Err(SpirvError::InvalidHeader);
}
if words[0] != 0x07230203 {
return Err(SpirvError::InvalidHeader);
}
let version = Version {
major: (words[1] & 0x00ff0000) >> 16,
minor: (words[1] & 0x0000ff00) >> 8,
patch: words[1] & 0x000000ff,
};
let bound = words[3];
let instructions = {
let mut ret = Vec::new();
let mut rest = &words[5..];
while !rest.is_empty() {
let word_count = (rest[0] >> 16) as usize;
assert!(word_count >= 1);
if rest.len() < word_count {
return Err(ParseError {
instruction: ret.len(),
word: rest.len(),
error: ParseErrors::UnexpectedEOF,
words: rest.to_owned(),
}
.into());
}
let mut reader = InstructionReader::new(&rest[0..word_count], ret.len());
let instruction = Instruction::parse(&mut reader)?;
if !reader.is_empty() {
return Err(reader.map_err(ParseErrors::LeftoverOperands).into());
}
ret.push(instruction);
rest = &rest[word_count..];
}
ret
};
let mut ids = HashMap::with_capacity(instructions.len().min(bound as usize));
let mut range_capability: Option<Range<usize>> = None;
let mut range_extension: Option<Range<usize>> = None;
let mut range_ext_inst_import: Option<Range<usize>> = None;
let mut range_memory_model: Option<Range<usize>> = None;
let mut range_entry_point: Option<Range<usize>> = None;
let mut range_execution_mode: Option<Range<usize>> = None;
let mut range_name: Option<Range<usize>> = None;
let mut range_decoration: Option<Range<usize>> = None;
let mut range_global: Option<Range<usize>> = None;
let mut in_function = false;
fn set_range(range: &mut Option<Range<usize>>, index: usize) -> Result<(), SpirvError> {
if let Some(range) = range {
if range.end != index {
return Err(SpirvError::BadLayout { index });
}
range.end = index + 1;
} else {
*range = Some(Range {
start: index,
end: index + 1,
});
}
Ok(())
}
for (index, instruction) in instructions.iter().enumerate() {
if let Some(id) = instruction.result_id() {
if u32::from(id) >= bound {
return Err(SpirvError::IdOutOfBounds { id, index, bound });
}
let members = if let Instruction::TypeStruct { member_types, .. } = instruction {
member_types
.iter()
.map(|_| StructMemberDataIndices::default())
.collect()
} else {
Vec::new()
};
let data = IdDataIndices {
index,
names: Vec::new(),
decorations: Vec::new(),
members,
};
if let Some(first) = ids.insert(id, data) {
return Err(SpirvError::DuplicateId {
id,
first_index: first.index,
second_index: index,
});
}
}
match instruction {
Instruction::Capability { .. } => set_range(&mut range_capability, index)?,
Instruction::Extension { .. } => set_range(&mut range_extension, index)?,
Instruction::ExtInstImport { .. } => set_range(&mut range_ext_inst_import, index)?,
Instruction::MemoryModel { .. } => set_range(&mut range_memory_model, index)?,
Instruction::EntryPoint { .. } => set_range(&mut range_entry_point, index)?,
Instruction::ExecutionMode { .. } | Instruction::ExecutionModeId { .. } => {
set_range(&mut range_execution_mode, index)?
}
Instruction::Name { .. } | Instruction::MemberName { .. } => {
set_range(&mut range_name, index)?
}
Instruction::Decorate { .. }
| Instruction::MemberDecorate { .. }
| Instruction::DecorationGroup { .. }
| Instruction::GroupDecorate { .. }
| Instruction::GroupMemberDecorate { .. }
| Instruction::DecorateId { .. }
| Instruction::DecorateString { .. }
| Instruction::MemberDecorateString { .. } => {
set_range(&mut range_decoration, index)?
}
Instruction::TypeVoid { .. }
| Instruction::TypeBool { .. }
| Instruction::TypeInt { .. }
| Instruction::TypeFloat { .. }
| Instruction::TypeVector { .. }
| Instruction::TypeMatrix { .. }
| Instruction::TypeImage { .. }
| Instruction::TypeSampler { .. }
| Instruction::TypeSampledImage { .. }
| Instruction::TypeArray { .. }
| Instruction::TypeRuntimeArray { .. }
| Instruction::TypeStruct { .. }
| Instruction::TypeOpaque { .. }
| Instruction::TypePointer { .. }
| Instruction::TypeFunction { .. }
| Instruction::TypeEvent { .. }
| Instruction::TypeDeviceEvent { .. }
| Instruction::TypeReserveId { .. }
| Instruction::TypeQueue { .. }
| Instruction::TypePipe { .. }
| Instruction::TypeForwardPointer { .. }
| Instruction::TypePipeStorage { .. }
| Instruction::TypeNamedBarrier { .. }
| Instruction::TypeRayQueryKHR { .. }
| Instruction::TypeAccelerationStructureKHR { .. }
| Instruction::TypeCooperativeMatrixNV { .. }
| Instruction::TypeVmeImageINTEL { .. }
| Instruction::TypeAvcImePayloadINTEL { .. }
| Instruction::TypeAvcRefPayloadINTEL { .. }
| Instruction::TypeAvcSicPayloadINTEL { .. }
| Instruction::TypeAvcMcePayloadINTEL { .. }
| Instruction::TypeAvcMceResultINTEL { .. }
| Instruction::TypeAvcImeResultINTEL { .. }
| Instruction::TypeAvcImeResultSingleReferenceStreamoutINTEL { .. }
| Instruction::TypeAvcImeResultDualReferenceStreamoutINTEL { .. }
| Instruction::TypeAvcImeSingleReferenceStreaminINTEL { .. }
| Instruction::TypeAvcImeDualReferenceStreaminINTEL { .. }
| Instruction::TypeAvcRefResultINTEL { .. }
| Instruction::TypeAvcSicResultINTEL { .. }
| Instruction::ConstantTrue { .. }
| Instruction::ConstantFalse { .. }
| Instruction::Constant { .. }
| Instruction::ConstantComposite { .. }
| Instruction::ConstantSampler { .. }
| Instruction::ConstantNull { .. }
| Instruction::ConstantPipeStorage { .. }
| Instruction::SpecConstantTrue { .. }
| Instruction::SpecConstantFalse { .. }
| Instruction::SpecConstant { .. }
| Instruction::SpecConstantComposite { .. }
| Instruction::SpecConstantOp { .. } => set_range(&mut range_global, index)?,
Instruction::Variable { storage_class, .. }
if *storage_class != StorageClass::Function =>
{
set_range(&mut range_global, index)?
}
Instruction::Function { .. } => {
in_function = true;
}
Instruction::Line { .. } | Instruction::NoLine { .. } => {
if !in_function {
set_range(&mut range_global, index)?
}
}
_ => (),
}
}
let mut spirv = Spirv {
version,
bound,
instructions,
ids,
range_capability: range_capability.unwrap_or_default(),
range_extension: range_extension.unwrap_or_default(),
range_ext_inst_import: range_ext_inst_import.unwrap_or_default(),
memory_model: if let Some(range) = range_memory_model {
if range.end - range.start != 1 {
return Err(SpirvError::MemoryModelInvalid);
}
range.start
} else {
return Err(SpirvError::MemoryModelInvalid);
},
range_entry_point: range_entry_point.unwrap_or_default(),
range_execution_mode: range_execution_mode.unwrap_or_default(),
range_name: range_name.unwrap_or_default(),
range_decoration: range_decoration.unwrap_or_default(),
range_global: range_global.unwrap_or_default(),
};
for index in spirv.range_name.clone() {
match &spirv.instructions[index] {
Instruction::Name { target, .. } => {
spirv.ids.get_mut(target).unwrap().names.push(index);
}
Instruction::MemberName { ty, member, .. } => {
spirv.ids.get_mut(ty).unwrap().members[*member as usize]
.names
.push(index);
}
_ => unreachable!(),
}
}
for index in spirv.range_decoration.clone() {
match &spirv.instructions[index] {
Instruction::Decorate { target, .. }
| Instruction::DecorateId { target, .. }
| Instruction::DecorateString { target, .. } => {
spirv.ids.get_mut(target).unwrap().decorations.push(index);
}
Instruction::MemberDecorate {
structure_type: target,
member,
..
}
| Instruction::MemberDecorateString {
struct_type: target,
member,
..
} => {
spirv.ids.get_mut(target).unwrap().members[*member as usize]
.decorations
.push(index);
}
_ => (),
}
}
for index in spirv.range_decoration.clone() {
match &spirv.instructions[index] {
Instruction::GroupDecorate {
decoration_group,
targets,
..
} => {
let indices = {
let data = &spirv.ids[decoration_group];
if !matches!(
spirv.instructions[data.index],
Instruction::DecorationGroup { .. }
) {
return Err(SpirvError::GroupDecorateNotGroup { index });
};
data.decorations.clone()
};
for target in targets {
spirv
.ids
.get_mut(target)
.unwrap()
.decorations
.extend(&indices);
}
}
Instruction::GroupMemberDecorate {
decoration_group,
targets,
..
} => {
let indices = {
let data = &spirv.ids[decoration_group];
if !matches!(
spirv.instructions[data.index],
Instruction::DecorationGroup { .. }
) {
return Err(SpirvError::GroupDecorateNotGroup { index });
};
data.decorations.clone()
};
for (target, member) in targets {
spirv.ids.get_mut(target).unwrap().members[*member as usize]
.decorations
.extend(&indices);
}
}
_ => (),
}
}
Ok(spirv)
}
#[inline]
pub fn instructions(&self) -> &[Instruction] {
&self.instructions
}
#[inline]
pub fn version(&self) -> Version {
self.version
}
#[inline]
pub fn bound(&self) -> u32 {
self.bound
}
#[inline]
pub fn id<'a>(&'a self, id: Id) -> IdInfo<'a> {
IdInfo {
data_indices: &self.ids[&id],
instructions: &self.instructions,
}
}
#[inline]
pub fn iter_capability(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_capability.clone()].iter()
}
#[inline]
pub fn iter_extension(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_extension.clone()].iter()
}
#[inline]
pub fn iter_ext_inst_import(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_ext_inst_import.clone()].iter()
}
#[inline]
pub fn memory_model(&self) -> &Instruction {
&self.instructions[self.memory_model]
}
#[inline]
pub fn iter_entry_point(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_entry_point.clone()].iter()
}
#[inline]
pub fn iter_execution_mode(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_execution_mode.clone()].iter()
}
#[inline]
pub fn iter_name(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_name.clone()].iter()
}
#[inline]
pub fn iter_decoration(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_decoration.clone()].iter()
}
#[inline]
pub fn iter_global(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions[self.range_global.clone()].iter()
}
}
#[derive(Clone, Debug)]
struct IdDataIndices {
index: usize,
names: Vec<usize>,
decorations: Vec<usize>,
members: Vec<StructMemberDataIndices>,
}
#[derive(Clone, Debug, Default)]
struct StructMemberDataIndices {
names: Vec<usize>,
decorations: Vec<usize>,
}
#[derive(Clone, Debug)]
pub struct IdInfo<'a> {
data_indices: &'a IdDataIndices,
instructions: &'a [Instruction],
}
impl<'a> IdInfo<'a> {
#[inline]
pub fn instruction(&self) -> &'a Instruction {
&self.instructions[self.data_indices.index]
}
#[inline]
pub fn iter_name(&self) -> impl ExactSizeIterator<Item = &'a Instruction> {
let instructions = self.instructions;
self.data_indices
.names
.iter()
.map(move |&index| &instructions[index])
}
#[inline]
pub fn iter_decoration(&self) -> impl ExactSizeIterator<Item = &'a Instruction> {
let instructions = self.instructions;
self.data_indices
.decorations
.iter()
.map(move |&index| &instructions[index])
}
#[inline]
pub fn iter_members(&self) -> impl ExactSizeIterator<Item = StructMemberInfo<'a>> {
let instructions = self.instructions;
self.data_indices
.members
.iter()
.map(move |data_indices| StructMemberInfo {
data_indices,
instructions,
})
}
}
#[derive(Clone, Debug)]
pub struct StructMemberInfo<'a> {
data_indices: &'a StructMemberDataIndices,
instructions: &'a [Instruction],
}
impl<'a> StructMemberInfo<'a> {
#[inline]
pub fn iter_name(&self) -> impl ExactSizeIterator<Item = &'a Instruction> {
let instructions = self.instructions;
self.data_indices
.names
.iter()
.map(move |&index| &instructions[index])
}
#[inline]
pub fn iter_decoration(&self) -> impl ExactSizeIterator<Item = &'a Instruction> {
let instructions = self.instructions;
self.data_indices
.decorations
.iter()
.map(move |&index| &instructions[index])
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Id(u32);
impl From<Id> for u32 {
#[inline]
fn from(id: Id) -> u32 {
id.0
}
}
impl Display for Id {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "%{}", self.0)
}
}
#[derive(Debug)]
struct InstructionReader<'a> {
words: &'a [u32],
next_word: usize,
instruction: usize,
}
impl<'a> InstructionReader<'a> {
#[inline]
fn new(words: &'a [u32], instruction: usize) -> Self {
debug_assert!(!words.is_empty());
Self {
words,
next_word: 0,
instruction,
}
}
#[inline]
fn is_empty(&self) -> bool {
self.next_word >= self.words.len()
}
#[inline]
fn map_err(&self, error: ParseErrors) -> ParseError {
ParseError {
instruction: self.instruction,
word: self.next_word - 1,
error,
words: self.words.to_owned(),
}
}
#[inline]
fn next_u32(&mut self) -> Result<u32, ParseError> {
let word = *self.words.get(self.next_word).ok_or(ParseError {
instruction: self.instruction,
word: self.next_word,
error: ParseErrors::MissingOperands,
words: self.words.to_owned(),
})?;
self.next_word += 1;
Ok(word)
}
#[inline]
fn next_u64(&mut self) -> Result<u64, ParseError> {
Ok(self.next_u32()? as u64 | (self.next_u32()? as u64) << 32)
}
fn next_string(&mut self) -> Result<String, ParseError> {
let mut bytes = Vec::new();
loop {
let word = self.next_u32()?.to_le_bytes();
if let Some(nul) = word.iter().position(|&b| b == 0) {
bytes.extend(&word[0..nul]);
break;
} else {
bytes.extend(word);
}
}
String::from_utf8(bytes).map_err(|err| self.map_err(ParseErrors::FromUtf8Error(err)))
}
#[inline]
fn remainder(&mut self) -> Vec<u32> {
let vec = self.words[self.next_word..].to_owned();
self.next_word = self.words.len();
vec
}
}
#[derive(Clone, Debug)]
pub enum SpirvError {
BadLayout {
index: usize,
},
DuplicateId {
id: Id,
first_index: usize,
second_index: usize,
},
GroupDecorateNotGroup {
index: usize,
},
IdOutOfBounds {
id: Id,
index: usize,
bound: u32,
},
InvalidHeader,
MemoryModelInvalid,
ParseError(ParseError),
}
impl Display for SpirvError {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::BadLayout { index } => write!(
f,
"the instruction at index {} does not follow the logical layout of a module",
index
),
Self::DuplicateId {
id,
first_index,
second_index,
} => write!(
f,
"id {} is assigned more than once, by instructions {} and {}",
id, first_index, second_index
),
Self::GroupDecorateNotGroup { index } => write!(f, "a GroupDecorate or GroupMemberDecorate instruction at index {} referred to an Id that was not a DecorationGroup", index),
Self::IdOutOfBounds { id, bound, index, } => write!(f, "id {}, assigned at instruction {}, is not below the maximum bound {}", id, index, bound),
Self::InvalidHeader => write!(f, "the SPIR-V module header is invalid"),
Self::MemoryModelInvalid => {
write!(f, "the MemoryModel instruction is not present exactly once")
}
Self::ParseError(_) => write!(f, "parse error"),
}
}
}
impl Error for SpirvError {
#[inline]
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::ParseError(err) => Some(err),
_ => None,
}
}
}
impl From<ParseError> for SpirvError {
#[inline]
fn from(err: ParseError) -> Self {
Self::ParseError(err)
}
}
#[derive(Clone, Debug)]
pub struct ParseError {
pub instruction: usize,
pub word: usize,
pub error: ParseErrors,
pub words: Vec<u32>,
}
impl Display for ParseError {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"at instruction {}, word {}: {}",
self.instruction, self.word, self.error
)
}
}
impl Error for ParseError {}
#[derive(Clone, Debug)]
pub enum ParseErrors {
FromUtf8Error(FromUtf8Error),
LeftoverOperands,
MissingOperands,
UnexpectedEOF,
UnknownEnumerant(&'static str, u32),
UnknownOpcode(u16),
UnknownSpecConstantOpcode(u16),
}
impl Display for ParseErrors {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::FromUtf8Error(err) => write!(f, "invalid UTF-8 in string literal"),
Self::LeftoverOperands => write!(f, "unparsed operands remaining"),
Self::MissingOperands => write!(f, "the instruction and its operands require more words than are present in the instruction"),
Self::UnexpectedEOF => write!(f, "encountered unexpected end of file"),
Self::UnknownEnumerant(ty, enumerant) => write!(f, "invalid enumerant {} for enum {}", enumerant, ty),
Self::UnknownOpcode(opcode) => write!(f, "invalid instruction opcode {}", opcode),
Self::UnknownSpecConstantOpcode(opcode) => write!(f, "invalid spec constant instruction opcode {}", opcode),
}
}
}