forked from KhronosGroup/Vulkan-ValidationLayers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shader_validation.cpp
4144 lines (3723 loc) · 199 KB
/
shader_validation.cpp
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
/* Copyright (c) 2015-2021 The Khronos Group Inc.
* Copyright (c) 2015-2021 Valve Corporation
* Copyright (c) 2015-2021 LunarG, Inc.
* Copyright (C) 2015-2021 Google Inc.
* Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Chris Forbes <[email protected]>
* Author: Dave Houlton <[email protected]>
* Author: Tobias Hector <[email protected]>
*/
#include "shader_validation.h"
#include <cassert>
#include <chrono>
#include <cinttypes>
#include <cmath>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include <spirv/unified1/spirv.hpp>
#include "vk_loader_platform.h"
#include "vk_enum_string_helper.h"
#include "vk_layer_data.h"
#include "vk_layer_extension_utils.h"
#include "vk_layer_utils.h"
#include "chassis.h"
#include "core_validation.h"
#include "spirv-tools/libspirv.h"
#include "xxhash.h"
void decoration_set::add(uint32_t decoration, uint32_t value) {
switch (decoration) {
case spv::DecorationLocation:
flags |= location_bit;
location = value;
break;
case spv::DecorationPatch:
flags |= patch_bit;
break;
case spv::DecorationRelaxedPrecision:
flags |= relaxed_precision_bit;
break;
case spv::DecorationBlock:
flags |= block_bit;
break;
case spv::DecorationBufferBlock:
flags |= buffer_block_bit;
break;
case spv::DecorationComponent:
flags |= component_bit;
component = value;
break;
case spv::DecorationInputAttachmentIndex:
flags |= input_attachment_index_bit;
input_attachment_index = value;
break;
case spv::DecorationDescriptorSet:
flags |= descriptor_set_bit;
descriptor_set = value;
break;
case spv::DecorationBinding:
flags |= binding_bit;
binding = value;
break;
case spv::DecorationNonWritable:
flags |= nonwritable_bit;
break;
case spv::DecorationBuiltIn:
flags |= builtin_bit;
builtin = value;
break;
}
}
enum FORMAT_TYPE {
FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
FORMAT_TYPE_SINT = 2,
FORMAT_TYPE_UINT = 4,
};
typedef std::pair<unsigned, unsigned> location_t;
static shader_stage_attributes shader_stage_attribs[] = {
{"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
{"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
{"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
{"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
{"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
};
unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
// SPIRV utility functions
void SHADER_MODULE_STATE::BuildDefIndex() {
function_set func_set = {};
EntryPoint *entry_point = nullptr;
for (auto insn : *this) {
// offset is not 0, it means it's updated and the offset is in a Function.
if (func_set.offset) {
func_set.op_lists.insert({insn.opcode(), insn.offset()});
} else if (entry_point) {
entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
}
switch (insn.opcode()) {
// Types
case spv::OpTypeVoid:
case spv::OpTypeBool:
case spv::OpTypeInt:
case spv::OpTypeFloat:
case spv::OpTypeVector:
case spv::OpTypeMatrix:
case spv::OpTypeImage:
case spv::OpTypeSampler:
case spv::OpTypeSampledImage:
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeStruct:
case spv::OpTypeOpaque:
case spv::OpTypePointer:
case spv::OpTypeFunction:
case spv::OpTypeEvent:
case spv::OpTypeDeviceEvent:
case spv::OpTypeReserveId:
case spv::OpTypeQueue:
case spv::OpTypePipe:
case spv::OpTypeAccelerationStructureNV:
case spv::OpTypeCooperativeMatrixNV:
def_index[insn.word(1)] = insn.offset();
break;
// Fixed constants
case spv::OpConstantTrue:
case spv::OpConstantFalse:
case spv::OpConstant:
case spv::OpConstantComposite:
case spv::OpConstantSampler:
case spv::OpConstantNull:
def_index[insn.word(2)] = insn.offset();
break;
// Specialization constants
case spv::OpSpecConstantTrue:
case spv::OpSpecConstantFalse:
case spv::OpSpecConstant:
case spv::OpSpecConstantComposite:
case spv::OpSpecConstantOp:
def_index[insn.word(2)] = insn.offset();
break;
// Variables
case spv::OpVariable:
def_index[insn.word(2)] = insn.offset();
break;
// Functions
case spv::OpFunction:
def_index[insn.word(2)] = insn.offset();
func_set.id = insn.word(2);
func_set.offset = insn.offset();
func_set.op_lists.clear();
break;
// Decorations
case spv::OpDecorate: {
auto target_id = insn.word(1);
decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
} break;
case spv::OpGroupDecorate: {
auto const &src = decorations[insn.word(1)];
for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
} break;
// Entry points ... add to the entrypoint table
case spv::OpEntryPoint: {
// Entry points do not have an id (the id is the function id) and thus need their own table
auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
auto execution_model = insn.word(1);
auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
entry_points.emplace(entrypoint_name,
EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
auto range = entry_points.equal_range(entrypoint_name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.offset == insn.offset()) {
entry_point = &(it->second);
break;
}
}
assert(entry_point != nullptr);
break;
}
case spv::OpFunctionEnd: {
assert(entry_point != nullptr);
func_set.length = insn.offset() - func_set.offset;
entry_point->function_set_list.emplace_back(func_set);
break;
}
// Copy operations
case spv::OpCopyLogical:
case spv::OpCopyObject: {
def_index[insn.word(2)] = insn.offset();
break;
}
default:
// We don't care about any other defs for now.
break;
}
}
}
unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
switch (mode) {
case spv::ExecutionModelVertex:
return VK_SHADER_STAGE_VERTEX_BIT;
case spv::ExecutionModelTessellationControl:
return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
case spv::ExecutionModelTessellationEvaluation:
return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
case spv::ExecutionModelGeometry:
return VK_SHADER_STAGE_GEOMETRY_BIT;
case spv::ExecutionModelFragment:
return VK_SHADER_STAGE_FRAGMENT_BIT;
case spv::ExecutionModelGLCompute:
return VK_SHADER_STAGE_COMPUTE_BIT;
case spv::ExecutionModelRayGenerationNV:
return VK_SHADER_STAGE_RAYGEN_BIT_NV;
case spv::ExecutionModelAnyHitNV:
return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
case spv::ExecutionModelClosestHitNV:
return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
case spv::ExecutionModelMissNV:
return VK_SHADER_STAGE_MISS_BIT_NV;
case spv::ExecutionModelIntersectionNV:
return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
case spv::ExecutionModelCallableNV:
return VK_SHADER_STAGE_CALLABLE_BIT_NV;
case spv::ExecutionModelTaskNV:
return VK_SHADER_STAGE_TASK_BIT_NV;
case spv::ExecutionModelMeshNV:
return VK_SHADER_STAGE_MESH_BIT_NV;
default:
return 0;
}
}
const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
VkShaderStageFlagBits stageBits) {
auto range = src->entry_points.equal_range(name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.stage == stageBits) {
return &(it->second);
}
}
return nullptr;
}
spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
auto range = src->entry_points.equal_range(name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.stage == stageBits) {
return src->at(it->second.offset);
}
}
return src->end();
}
static char const *StorageClassName(unsigned sc) {
switch (sc) {
case spv::StorageClassInput:
return "input";
case spv::StorageClassOutput:
return "output";
case spv::StorageClassUniformConstant:
return "const uniform";
case spv::StorageClassUniform:
return "uniform";
case spv::StorageClassWorkgroup:
return "workgroup local";
case spv::StorageClassCrossWorkgroup:
return "workgroup global";
case spv::StorageClassPrivate:
return "private global";
case spv::StorageClassFunction:
return "function";
case spv::StorageClassGeneric:
return "generic";
case spv::StorageClassAtomicCounter:
return "atomic counter";
case spv::StorageClassImage:
return "image";
case spv::StorageClassPushConstant:
return "push constant";
case spv::StorageClassStorageBuffer:
return "storage buffer";
default:
return "unknown";
}
}
// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
// Otherwise, returns src->end().
spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
auto value = src->get_def(id);
// If id is a copy, see where it was copied from
if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
id = value.word(3);
value = src->get_def(id);
}
if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
return value;
}
return src->end();
}
// Assumes itr points to an OpConstant instruction
uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
// Either returns the constant value described by the instruction at id, or 1
uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
auto value = GetConstantDef(src, id);
if (src->end() == value) {
// TODO: Either ensure that the specialization transform is already performed on a module we're
// considering here, OR -- specialize on the fly now.
return 1;
}
return GetConstantValue(value);
}
static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypeBool:
ss << "bool";
break;
case spv::OpTypeInt:
ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
break;
case spv::OpTypeFloat:
ss << "float" << insn.word(2);
break;
case spv::OpTypeVector:
ss << "vec" << insn.word(3) << " of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeMatrix:
ss << "mat" << insn.word(3) << " of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeArray:
ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeRuntimeArray:
ss << "runtime arr[] of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypePointer:
ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
DescribeTypeInner(ss, src, insn.word(3));
break;
case spv::OpTypeStruct: {
ss << "struct of (";
for (unsigned i = 2; i < insn.len(); i++) {
DescribeTypeInner(ss, src, insn.word(i));
if (i == insn.len() - 1) {
ss << ")";
} else {
ss << ", ";
}
}
break;
}
case spv::OpTypeSampler:
ss << "sampler";
break;
case spv::OpTypeSampledImage:
ss << "sampler+";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeImage:
ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
break;
case spv::OpTypeAccelerationStructureNV:
ss << "accelerationStruture";
break;
default:
ss << "oddtype";
break;
}
}
static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
std::ostringstream ss;
DescribeTypeInner(ss, src, type);
return ss.str();
}
static bool IsNarrowNumericType(spirv_inst_iter type) {
if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
return type.word(2) < 64;
}
static bool TypesMatch(SHADER_MODULE_STATE const *a, SHADER_MODULE_STATE const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
bool b_arrayed, bool relaxed) {
// Walk two type trees together, and complain about differences
auto a_insn = a->get_def(a_type);
auto b_insn = b->get_def(b_type);
assert(a_insn != a->end());
assert(b_insn != b->end());
// Ignore runtime-sized arrays-- they cannot appear in these interfaces.
if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
}
if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
// We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
}
if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
}
if (a_insn.opcode() != b_insn.opcode()) {
return false;
}
if (a_insn.opcode() == spv::OpTypePointer) {
// Match on pointee type. storage class is expected to differ
return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
}
if (a_arrayed || b_arrayed) {
// If we havent resolved array-of-verts by here, we're not going to.
return false;
}
switch (a_insn.opcode()) {
case spv::OpTypeBool:
return true;
case spv::OpTypeInt:
// Match on width, signedness
return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
case spv::OpTypeFloat:
// Match on width
return a_insn.word(2) == b_insn.word(2);
case spv::OpTypeVector:
// Match on element type, count.
if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
return a_insn.word(3) >= b_insn.word(3);
} else {
return a_insn.word(3) == b_insn.word(3);
}
case spv::OpTypeMatrix:
// Match on element type, count.
return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
a_insn.word(3) == b_insn.word(3);
case spv::OpTypeArray:
// Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
// vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
case spv::OpTypeStruct:
// Match on all element types
{
if (a_insn.len() != b_insn.len()) {
return false; // Structs cannot match if member counts differ
}
for (unsigned i = 2; i < a_insn.len(); i++) {
if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
return false;
}
}
return true;
}
default:
// Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
return false;
}
}
static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypePointer:
// See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
// pointers around.
return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
case spv::OpTypeArray:
if (strip_array_level) {
return GetLocationsConsumedByType(src, insn.word(2), false);
} else {
return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
}
case spv::OpTypeMatrix:
// Num locations is the dimension * element size
return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
case spv::OpTypeVector: {
auto scalar_type = src->get_def(insn.word(2));
auto bit_width =
(scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
// Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
return (bit_width * insn.word(3) + 127) / 128;
}
default:
// Everything else is just 1.
return 1;
// TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
}
}
static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypePointer:
// See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
// pointers around.
return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
case spv::OpTypeStruct: {
uint32_t sum = 0;
for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
sum += GetComponentsConsumedByType(src, insn.word(i), false);
}
return sum;
}
case spv::OpTypeArray:
if (strip_array_level) {
return GetComponentsConsumedByType(src, insn.word(2), false);
} else {
return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
}
case spv::OpTypeMatrix:
// Num locations is the dimension * element size
return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
case spv::OpTypeVector: {
auto scalar_type = src->get_def(insn.word(2));
auto bit_width =
(scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
// One component is 32-bit
return (bit_width * insn.word(3) + 31) / 32;
}
case spv::OpTypeFloat: {
auto bit_width = insn.word(2);
return (bit_width + 31) / 32;
}
case spv::OpTypeInt: {
auto bit_width = insn.word(2);
return (bit_width + 31) / 32;
}
case spv::OpConstant:
return GetComponentsConsumedByType(src, insn.word(1), false);
default:
return 0;
}
}
static unsigned GetLocationsConsumedByFormat(VkFormat format) {
switch (format) {
case VK_FORMAT_R64G64B64A64_SFLOAT:
case VK_FORMAT_R64G64B64A64_SINT:
case VK_FORMAT_R64G64B64A64_UINT:
case VK_FORMAT_R64G64B64_SFLOAT:
case VK_FORMAT_R64G64B64_SINT:
case VK_FORMAT_R64G64B64_UINT:
return 2;
default:
return 1;
}
}
static unsigned GetFormatType(VkFormat fmt) {
if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
if (fmt == VK_FORMAT_UNDEFINED) return 0;
// everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
return FORMAT_TYPE_FLOAT;
}
// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
// also used for input attachments, as we statically know their format.
static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypeInt:
return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
case spv::OpTypeFloat:
return FORMAT_TYPE_FLOAT;
case spv::OpTypeVector:
case spv::OpTypeMatrix:
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeImage:
return GetFundamentalType(src, insn.word(2));
case spv::OpTypePointer:
return GetFundamentalType(src, insn.word(3));
default:
return 0;
}
}
static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
uint32_t bit_pos = uint32_t(u_ffs(stage));
return bit_pos - 1;
}
static spirv_inst_iter GetStructType(SHADER_MODULE_STATE const *src, spirv_inst_iter def, bool is_array_of_verts) {
while (true) {
if (def.opcode() == spv::OpTypePointer) {
def = src->get_def(def.word(3));
} else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
def = src->get_def(def.word(2));
is_array_of_verts = false;
} else if (def.opcode() == spv::OpTypeStruct) {
return def;
} else {
return src->end();
}
}
}
static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
int /*first_location*/) {
// Walk down the type_id presented, trying to determine whether it's actually an interface block.
auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
// This isn't an interface block.
return false;
}
std::unordered_map<unsigned, unsigned> member_components;
std::unordered_map<unsigned, unsigned> member_relaxed_precision;
std::unordered_map<unsigned, unsigned> member_patch;
// Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
unsigned member_index = insn.word(2);
if (insn.word(3) == spv::DecorationComponent) {
unsigned component = insn.word(4);
member_components[member_index] = component;
}
if (insn.word(3) == spv::DecorationRelaxedPrecision) {
member_relaxed_precision[member_index] = 1;
}
if (insn.word(3) == spv::DecorationPatch) {
member_patch[member_index] = 1;
}
}
}
// TODO: correctly handle location assignment from outside
// Second pass -- produce the output, from Location decorations
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
unsigned member_index = insn.word(2);
unsigned member_type_id = type.word(2 + member_index);
if (insn.word(3) == spv::DecorationLocation) {
unsigned location = insn.word(4);
unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
auto component_it = member_components.find(member_index);
unsigned component = component_it == member_components.end() ? 0 : component_it->second;
bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
for (unsigned int offset = 0; offset < num_locations; offset++) {
interface_var v = {};
v.id = id;
// TODO: member index in interface_var too?
v.type_id = member_type_id;
v.offset = offset;
v.is_patch = member_is_patch;
v.is_block_member = true;
v.is_relaxed_precision = is_relaxed_precision;
(*out)[std::make_pair(location + offset, component)] = v;
}
}
}
}
return true;
}
static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
assert(entrypoint.opcode() == spv::OpEntryPoint);
std::vector<uint32_t> interfaces;
// Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
// rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
uint32_t word = 3;
while (entrypoint.word(word) & 0xff000000u) {
++word;
}
++word;
for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
return interfaces;
}
static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
spv::StorageClass sinterface, bool is_array_of_verts) {
// TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
std::map<location_t, interface_var> out;
for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
auto insn = src->get_def(iid);
assert(insn != src->end());
assert(insn.opcode() == spv::OpVariable);
if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
auto d = src->get_decorations(iid);
unsigned id = insn.word(2);
unsigned type = insn.word(1);
int location = d.location;
int builtin = d.builtin;
unsigned component = d.component;
bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
if (builtin != -1) {
continue;
} else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
// A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
// one result for each.
unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
for (unsigned int offset = 0; offset < num_locations; offset++) {
interface_var v = {};
v.id = id;
v.type_id = type;
v.offset = offset;
v.is_patch = is_patch;
v.is_relaxed_precision = is_relaxed_precision;
out[std::make_pair(location + offset, component)] = v;
}
}
}
}
return out;
}
static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
uint32_t storageClass) {
std::vector<uint32_t> variables;
std::vector<uint32_t> builtin_struct_members;
std::vector<uint32_t> builtin_decorations;
for (auto insn : *src) {
switch (insn.opcode()) {
// Find all built-in member decorations
case spv::OpMemberDecorate:
if (insn.word(3) == spv::DecorationBuiltIn) {
builtin_struct_members.push_back(insn.word(1));
}
break;
// Find all built-in decorations
case spv::OpDecorate:
switch (insn.word(2)) {
case spv::DecorationBlock: {
uint32_t block_id = insn.word(1);
for (auto built_in_block_id : builtin_struct_members) {
// Check if one of the members of the block are built-in -> the block is built-in
if (block_id == built_in_block_id) {
builtin_decorations.push_back(block_id);
break;
}
}
break;
}
case spv::DecorationBuiltIn:
builtin_decorations.push_back(insn.word(1));
break;
default:
break;
}
break;
default:
break;
}
}
// Find all interface variables belonging to the entrypoint and matching the storage class
for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
auto def = src->get_def(id);
assert(def != src->end());
assert(def.opcode() == spv::OpVariable);
if (def.word(3) == storageClass) variables.push_back(def.word(1));
}
// Find all members belonging to the builtin block selected
std::vector<uint32_t> builtin_block_members;
for (auto &var : variables) {
auto def = src->get_def(src->get_def(var).word(3));
// It could be an array of IO blocks. The element type should be the struct defining the block contents
if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
// Now find all members belonging to the struct defining the IO block
if (def.opcode() == spv::OpTypeStruct) {
for (auto built_in_id : builtin_decorations) {
if (built_in_id == def.word(1)) {
for (int i = 2; i < static_cast<int>(def.len()); i++) {
builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
}
// These shouldn't be left after replacing.
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == built_in_id &&
insn.word(3) == spv::DecorationBuiltIn) {
auto struct_index = insn.word(2);
assert(struct_index < builtin_block_members.size());
builtin_block_members[struct_index] = insn.word(4);
}
}
}
}
}
}
return builtin_block_members;
}
static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
std::vector<std::pair<uint32_t, interface_var>> out;
for (auto insn : *src) {
if (insn.opcode() == spv::OpDecorate) {
if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
auto attachment_index = insn.word(3);
auto id = insn.word(1);
if (accessible_ids.count(id)) {
auto def = src->get_def(id);
assert(def != src->end());
if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
for (unsigned int offset = 0; offset < num_locations; offset++) {
interface_var v = {};
v.id = id;
v.type_id = def.word(1);
v.offset = offset;
out.emplace_back(attachment_index + offset, v);
}
}
}
}
}
}
return out;
}
static bool AtomicOperation(uint32_t opcode) {
switch (opcode) {
case spv::OpAtomicLoad:
case spv::OpAtomicStore:
case spv::OpAtomicExchange:
case spv::OpAtomicCompareExchange:
case spv::OpAtomicCompareExchangeWeak:
case spv::OpAtomicIIncrement:
case spv::OpAtomicIDecrement:
case spv::OpAtomicIAdd:
case spv::OpAtomicISub:
case spv::OpAtomicSMin:
case spv::OpAtomicUMin:
case spv::OpAtomicSMax:
case spv::OpAtomicUMax:
case spv::OpAtomicAnd:
case spv::OpAtomicOr:
case spv::OpAtomicXor:
case spv::OpAtomicFAddEXT:
return true;
default:
return false;
}
return false;
}
// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
// covered with VUID 01090
static bool GroupOperation(uint32_t opcode) {
switch (opcode) {
case spv::OpGroupNonUniformElect:
case spv::OpGroupNonUniformAll:
case spv::OpGroupNonUniformAny:
case spv::OpGroupNonUniformAllEqual:
case spv::OpGroupNonUniformBroadcast:
case spv::OpGroupNonUniformBroadcastFirst:
case spv::OpGroupNonUniformBallot:
case spv::OpGroupNonUniformInverseBallot:
case spv::OpGroupNonUniformBallotBitExtract:
case spv::OpGroupNonUniformBallotBitCount:
case spv::OpGroupNonUniformBallotFindLSB:
case spv::OpGroupNonUniformBallotFindMSB:
case spv::OpGroupNonUniformShuffle:
case spv::OpGroupNonUniformShuffleXor:
case spv::OpGroupNonUniformShuffleUp:
case spv::OpGroupNonUniformShuffleDown:
case spv::OpGroupNonUniformIAdd:
case spv::OpGroupNonUniformFAdd:
case spv::OpGroupNonUniformIMul:
case spv::OpGroupNonUniformFMul:
case spv::OpGroupNonUniformSMin:
case spv::OpGroupNonUniformUMin:
case spv::OpGroupNonUniformFMin:
case spv::OpGroupNonUniformSMax:
case spv::OpGroupNonUniformUMax:
case spv::OpGroupNonUniformFMax:
case spv::OpGroupNonUniformBitwiseAnd:
case spv::OpGroupNonUniformBitwiseOr:
case spv::OpGroupNonUniformBitwiseXor:
case spv::OpGroupNonUniformLogicalAnd:
case spv::OpGroupNonUniformLogicalOr:
case spv::OpGroupNonUniformLogicalXor:
case spv::OpGroupNonUniformQuadBroadcast:
case spv::OpGroupNonUniformQuadSwap:
case spv::OpGroupNonUniformPartitionNV:
return true;
default:
return false;
}
return false;
}
bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
const std::unordered_map<unsigned, unsigned> &load_members,
const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
for (auto load_id : operator_members) {
if (object_id == load_id) return true;
auto load_it = load_members.find(load_id);
if (load_it == load_members.end()) {
continue;
}
if (load_it->second == object_id) {
return true;
}
auto accesschain_it = accesschain_members.find(load_it->second);
if (accesschain_it == accesschain_members.end()) {
continue;
}
if (accesschain_it->second.first == object_id) {
return true;
}
}
return false;
}
bool CheckImageOperandsBiasOffset(uint32_t type) {
return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |