blob: 019d1a7683889d75807e8bd854135b5a8419857d [file] [log] [blame]
Chris Forbes47567b72017-06-09 12:09:45 -07001/* Copyright (c) 2015-2017 The Khronos Group Inc.
2 * Copyright (c) 2015-2017 Valve Corporation
3 * Copyright (c) 2015-2017 LunarG, Inc.
4 * Copyright (C) 2015-2017 Google Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Chris Forbes <chrisf@ijw.co.nz>
19 */
20
21#include <cinttypes>
22#include <cassert>
23#include <vector>
24#include <unordered_map>
25#include <string>
26#include <sstream>
27#include <SPIRV/spirv.hpp>
28#include "vk_loader_platform.h"
29#include "vk_enum_string_helper.h"
30#include "vk_layer_table.h"
31#include "vk_layer_data.h"
32#include "vk_layer_extension_utils.h"
33#include "vk_layer_utils.h"
34#include "core_validation.h"
35#include "core_validation_types.h"
36#include "shader_validation.h"
Chris Forbes4ae55b32017-06-09 14:42:56 -070037#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070038#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039
40enum FORMAT_TYPE {
41 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
42 FORMAT_TYPE_SINT = 2,
43 FORMAT_TYPE_UINT = 4,
44};
45
46typedef std::pair<unsigned, unsigned> location_t;
47
48struct interface_var {
49 uint32_t id;
50 uint32_t type_id;
51 uint32_t offset;
52 bool is_patch;
53 bool is_block_member;
54 bool is_relaxed_precision;
55 // TODO: collect the name, too? Isn't required to be present.
56};
57
58struct shader_stage_attributes {
59 char const *const name;
60 bool arrayed_input;
61 bool arrayed_output;
62};
63
64static shader_stage_attributes shader_stage_attribs[] = {
65 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
66 {"geometry shader", true, false}, {"fragment shader", false, false},
67};
68
69// SPIRV utility functions
70void shader_module::build_def_index() {
71 for (auto insn : *this) {
72 switch (insn.opcode()) {
73 // Types
74 case spv::OpTypeVoid:
75 case spv::OpTypeBool:
76 case spv::OpTypeInt:
77 case spv::OpTypeFloat:
78 case spv::OpTypeVector:
79 case spv::OpTypeMatrix:
80 case spv::OpTypeImage:
81 case spv::OpTypeSampler:
82 case spv::OpTypeSampledImage:
83 case spv::OpTypeArray:
84 case spv::OpTypeRuntimeArray:
85 case spv::OpTypeStruct:
86 case spv::OpTypeOpaque:
87 case spv::OpTypePointer:
88 case spv::OpTypeFunction:
89 case spv::OpTypeEvent:
90 case spv::OpTypeDeviceEvent:
91 case spv::OpTypeReserveId:
92 case spv::OpTypeQueue:
93 case spv::OpTypePipe:
94 def_index[insn.word(1)] = insn.offset();
95 break;
96
97 // Fixed constants
98 case spv::OpConstantTrue:
99 case spv::OpConstantFalse:
100 case spv::OpConstant:
101 case spv::OpConstantComposite:
102 case spv::OpConstantSampler:
103 case spv::OpConstantNull:
104 def_index[insn.word(2)] = insn.offset();
105 break;
106
107 // Specialization constants
108 case spv::OpSpecConstantTrue:
109 case spv::OpSpecConstantFalse:
110 case spv::OpSpecConstant:
111 case spv::OpSpecConstantComposite:
112 case spv::OpSpecConstantOp:
113 def_index[insn.word(2)] = insn.offset();
114 break;
115
116 // Variables
117 case spv::OpVariable:
118 def_index[insn.word(2)] = insn.offset();
119 break;
120
121 // Functions
122 case spv::OpFunction:
123 def_index[insn.word(2)] = insn.offset();
124 break;
125
126 default:
127 // We don't care about any other defs for now.
128 break;
129 }
130 }
131}
132
133static spirv_inst_iter find_entrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
134 for (auto insn : *src) {
135 if (insn.opcode() == spv::OpEntryPoint) {
136 auto entrypointName = (char const *)&insn.word(3);
137 auto entrypointStageBits = 1u << insn.word(1);
138
139 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
140 return insn;
141 }
142 }
143 }
144
145 return src->end();
146}
147
148static char const *storage_class_name(unsigned sc) {
149 switch (sc) {
150 case spv::StorageClassInput:
151 return "input";
152 case spv::StorageClassOutput:
153 return "output";
154 case spv::StorageClassUniformConstant:
155 return "const uniform";
156 case spv::StorageClassUniform:
157 return "uniform";
158 case spv::StorageClassWorkgroup:
159 return "workgroup local";
160 case spv::StorageClassCrossWorkgroup:
161 return "workgroup global";
162 case spv::StorageClassPrivate:
163 return "private global";
164 case spv::StorageClassFunction:
165 return "function";
166 case spv::StorageClassGeneric:
167 return "generic";
168 case spv::StorageClassAtomicCounter:
169 return "atomic counter";
170 case spv::StorageClassImage:
171 return "image";
172 case spv::StorageClassPushConstant:
173 return "push constant";
174 default:
175 return "unknown";
176 }
177}
178
179// Get the value of an integral constant
180unsigned get_constant_value(shader_module const *src, unsigned id) {
181 auto value = src->get_def(id);
182 assert(value != src->end());
183
184 if (value.opcode() != spv::OpConstant) {
185 // TODO: Either ensure that the specialization transform is already performed on a module we're
186 // considering here, OR -- specialize on the fly now.
187 return 1;
188 }
189
190 return value.word(3);
191}
192
193static void describe_type_inner(std::ostringstream &ss, shader_module const *src, unsigned type) {
194 auto insn = src->get_def(type);
195 assert(insn != src->end());
196
197 switch (insn.opcode()) {
198 case spv::OpTypeBool:
199 ss << "bool";
200 break;
201 case spv::OpTypeInt:
202 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
203 break;
204 case spv::OpTypeFloat:
205 ss << "float" << insn.word(2);
206 break;
207 case spv::OpTypeVector:
208 ss << "vec" << insn.word(3) << " of ";
209 describe_type_inner(ss, src, insn.word(2));
210 break;
211 case spv::OpTypeMatrix:
212 ss << "mat" << insn.word(3) << " of ";
213 describe_type_inner(ss, src, insn.word(2));
214 break;
215 case spv::OpTypeArray:
216 ss << "arr[" << get_constant_value(src, insn.word(3)) << "] of ";
217 describe_type_inner(ss, src, insn.word(2));
218 break;
219 case spv::OpTypePointer:
220 ss << "ptr to " << storage_class_name(insn.word(2)) << " ";
221 describe_type_inner(ss, src, insn.word(3));
222 break;
223 case spv::OpTypeStruct: {
224 ss << "struct of (";
225 for (unsigned i = 2; i < insn.len(); i++) {
226 describe_type_inner(ss, src, insn.word(i));
227 if (i == insn.len() - 1) {
228 ss << ")";
229 } else {
230 ss << ", ";
231 }
232 }
233 break;
234 }
235 case spv::OpTypeSampler:
236 ss << "sampler";
237 break;
238 case spv::OpTypeSampledImage:
239 ss << "sampler+";
240 describe_type_inner(ss, src, insn.word(2));
241 break;
242 case spv::OpTypeImage:
243 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
244 break;
245 default:
246 ss << "oddtype";
247 break;
248 }
249}
250
251static std::string describe_type(shader_module const *src, unsigned type) {
252 std::ostringstream ss;
253 describe_type_inner(ss, src, type);
254 return ss.str();
255}
256
257static bool is_narrow_numeric_type(spirv_inst_iter type) {
258 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
259 return type.word(2) < 64;
260}
261
262static bool types_match(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
263 bool b_arrayed, bool relaxed) {
264 // Walk two type trees together, and complain about differences
265 auto a_insn = a->get_def(a_type);
266 auto b_insn = b->get_def(b_type);
267 assert(a_insn != a->end());
268 assert(b_insn != b->end());
269
270 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
271 return types_match(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
272 }
273
274 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
275 // We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
276 return types_match(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
277 }
278
279 if (a_insn.opcode() == spv::OpTypeVector && relaxed && is_narrow_numeric_type(b_insn)) {
280 return types_match(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
281 }
282
283 if (a_insn.opcode() != b_insn.opcode()) {
284 return false;
285 }
286
287 if (a_insn.opcode() == spv::OpTypePointer) {
288 // Match on pointee type. storage class is expected to differ
289 return types_match(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
290 }
291
292 if (a_arrayed || b_arrayed) {
293 // If we havent resolved array-of-verts by here, we're not going to.
294 return false;
295 }
296
297 switch (a_insn.opcode()) {
298 case spv::OpTypeBool:
299 return true;
300 case spv::OpTypeInt:
301 // Match on width, signedness
302 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
303 case spv::OpTypeFloat:
304 // Match on width
305 return a_insn.word(2) == b_insn.word(2);
306 case spv::OpTypeVector:
307 // Match on element type, count.
308 if (!types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
309 if (relaxed && is_narrow_numeric_type(a->get_def(a_insn.word(2)))) {
310 return a_insn.word(3) >= b_insn.word(3);
311 } else {
312 return a_insn.word(3) == b_insn.word(3);
313 }
314 case spv::OpTypeMatrix:
315 // Match on element type, count.
316 return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700317 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700318 case spv::OpTypeArray:
319 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
320 // vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
321 return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700322 get_constant_value(a, a_insn.word(3)) == get_constant_value(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700323 case spv::OpTypeStruct:
324 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700325 {
326 if (a_insn.len() != b_insn.len()) {
327 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700328 }
Chris Forbes47567b72017-06-09 12:09:45 -0700329
Dave Houltona9df0ce2018-02-07 10:51:23 -0700330 for (unsigned i = 2; i < a_insn.len(); i++) {
331 if (!types_match(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
332 return false;
333 }
334 }
335
336 return true;
337 }
Chris Forbes47567b72017-06-09 12:09:45 -0700338 default:
339 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
340 return false;
341 }
342}
343
344static unsigned value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
345 auto it = map.find(id);
346 if (it == map.end())
347 return def;
348 else
349 return it->second;
350}
351
352static unsigned get_locations_consumed_by_type(shader_module const *src, unsigned type, bool strip_array_level) {
353 auto insn = src->get_def(type);
354 assert(insn != src->end());
355
356 switch (insn.opcode()) {
357 case spv::OpTypePointer:
358 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
359 // pointers around.
360 return get_locations_consumed_by_type(src, insn.word(3), strip_array_level);
361 case spv::OpTypeArray:
362 if (strip_array_level) {
363 return get_locations_consumed_by_type(src, insn.word(2), false);
364 } else {
365 return get_constant_value(src, insn.word(3)) * get_locations_consumed_by_type(src, insn.word(2), false);
366 }
367 case spv::OpTypeMatrix:
368 // Num locations is the dimension * element size
369 return insn.word(3) * get_locations_consumed_by_type(src, insn.word(2), false);
370 case spv::OpTypeVector: {
371 auto scalar_type = src->get_def(insn.word(2));
372 auto bit_width =
373 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
374
375 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
376 return (bit_width * insn.word(3) + 127) / 128;
377 }
378 default:
379 // Everything else is just 1.
380 return 1;
381
382 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
383 }
384}
385
386static unsigned get_locations_consumed_by_format(VkFormat format) {
387 switch (format) {
388 case VK_FORMAT_R64G64B64A64_SFLOAT:
389 case VK_FORMAT_R64G64B64A64_SINT:
390 case VK_FORMAT_R64G64B64A64_UINT:
391 case VK_FORMAT_R64G64B64_SFLOAT:
392 case VK_FORMAT_R64G64B64_SINT:
393 case VK_FORMAT_R64G64B64_UINT:
394 return 2;
395 default:
396 return 1;
397 }
398}
399
400static unsigned get_format_type(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700401 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
402 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
403 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
404 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700405 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
406 return FORMAT_TYPE_FLOAT;
407}
408
409// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
410static unsigned get_fundamental_type(shader_module const *src, unsigned type) {
411 auto insn = src->get_def(type);
412 assert(insn != src->end());
413
414 switch (insn.opcode()) {
415 case spv::OpTypeInt:
416 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
417 case spv::OpTypeFloat:
418 return FORMAT_TYPE_FLOAT;
419 case spv::OpTypeVector:
420 return get_fundamental_type(src, insn.word(2));
421 case spv::OpTypeMatrix:
422 return get_fundamental_type(src, insn.word(2));
423 case spv::OpTypeArray:
424 return get_fundamental_type(src, insn.word(2));
425 case spv::OpTypePointer:
426 return get_fundamental_type(src, insn.word(3));
427 case spv::OpTypeImage:
428 return get_fundamental_type(src, insn.word(2));
429
430 default:
431 return 0;
432 }
433}
434
435static uint32_t get_shader_stage_id(VkShaderStageFlagBits stage) {
436 uint32_t bit_pos = uint32_t(u_ffs(stage));
437 return bit_pos - 1;
438}
439
440static spirv_inst_iter get_struct_type(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
441 while (true) {
442 if (def.opcode() == spv::OpTypePointer) {
443 def = src->get_def(def.word(3));
444 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
445 def = src->get_def(def.word(2));
446 is_array_of_verts = false;
447 } else if (def.opcode() == spv::OpTypeStruct) {
448 return def;
449 } else {
450 return src->end();
451 }
452 }
453}
454
Chris Forbesa313d772017-06-13 13:59:41 -0700455static bool collect_interface_block_members(shader_module const *src, std::map<location_t, interface_var> *out,
Chris Forbes47567b72017-06-09 12:09:45 -0700456 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts,
Chris Forbesa313d772017-06-13 13:59:41 -0700457 uint32_t id, uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700458 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
459 auto type = get_struct_type(src, src->get_def(type_id), is_array_of_verts && !is_patch);
460 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
461 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700462 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700463 }
464
465 std::unordered_map<unsigned, unsigned> member_components;
466 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700467 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700468
469 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
470 for (auto insn : *src) {
471 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
472 unsigned member_index = insn.word(2);
473
474 if (insn.word(3) == spv::DecorationComponent) {
475 unsigned component = insn.word(4);
476 member_components[member_index] = component;
477 }
478
479 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
480 member_relaxed_precision[member_index] = 1;
481 }
Chris Forbesa313d772017-06-13 13:59:41 -0700482
483 if (insn.word(3) == spv::DecorationPatch) {
484 member_patch[member_index] = 1;
485 }
Chris Forbes47567b72017-06-09 12:09:45 -0700486 }
487 }
488
Chris Forbesa313d772017-06-13 13:59:41 -0700489 // TODO: correctly handle location assignment from outside
490
Chris Forbes47567b72017-06-09 12:09:45 -0700491 // Second pass -- produce the output, from Location decorations
492 for (auto insn : *src) {
493 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
494 unsigned member_index = insn.word(2);
495 unsigned member_type_id = type.word(2 + member_index);
496
497 if (insn.word(3) == spv::DecorationLocation) {
498 unsigned location = insn.word(4);
499 unsigned num_locations = get_locations_consumed_by_type(src, member_type_id, false);
500 auto component_it = member_components.find(member_index);
501 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
502 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700503 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700504
505 for (unsigned int offset = 0; offset < num_locations; offset++) {
506 interface_var v = {};
507 v.id = id;
508 // TODO: member index in interface_var too?
509 v.type_id = member_type_id;
510 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700511 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700512 v.is_block_member = true;
513 v.is_relaxed_precision = is_relaxed_precision;
514 (*out)[std::make_pair(location + offset, component)] = v;
515 }
516 }
517 }
518 }
Chris Forbesa313d772017-06-13 13:59:41 -0700519
520 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700521}
522
523static std::map<location_t, interface_var> collect_interface_by_location(shader_module const *src, spirv_inst_iter entrypoint,
524 spv::StorageClass sinterface, bool is_array_of_verts) {
525 std::unordered_map<unsigned, unsigned> var_locations;
526 std::unordered_map<unsigned, unsigned> var_builtins;
527 std::unordered_map<unsigned, unsigned> var_components;
528 std::unordered_map<unsigned, unsigned> blocks;
529 std::unordered_map<unsigned, unsigned> var_patch;
530 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
531
532 for (auto insn : *src) {
533 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
534 // fits neither model.
535 if (insn.opcode() == spv::OpDecorate) {
536 if (insn.word(2) == spv::DecorationLocation) {
537 var_locations[insn.word(1)] = insn.word(3);
538 }
539
540 if (insn.word(2) == spv::DecorationBuiltIn) {
541 var_builtins[insn.word(1)] = insn.word(3);
542 }
543
544 if (insn.word(2) == spv::DecorationComponent) {
545 var_components[insn.word(1)] = insn.word(3);
546 }
547
548 if (insn.word(2) == spv::DecorationBlock) {
549 blocks[insn.word(1)] = 1;
550 }
551
552 if (insn.word(2) == spv::DecorationPatch) {
553 var_patch[insn.word(1)] = 1;
554 }
555
556 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
557 var_relaxed_precision[insn.word(1)] = 1;
558 }
559 }
560 }
561
562 // TODO: handle grouped decorations
563 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
564
565 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
566 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
567 uint32_t word = 3;
568 while (entrypoint.word(word) & 0xff000000u) {
569 ++word;
570 }
571 ++word;
572
573 std::map<location_t, interface_var> out;
574
575 for (; word < entrypoint.len(); word++) {
576 auto insn = src->get_def(entrypoint.word(word));
577 assert(insn != src->end());
578 assert(insn.opcode() == spv::OpVariable);
579
580 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
581 unsigned id = insn.word(2);
582 unsigned type = insn.word(1);
583
Jamie Madill061d1112017-11-08 16:25:22 -0500584 int location = value_or_default(var_locations, id, static_cast<unsigned>(-1));
585 int builtin = value_or_default(var_builtins, id, static_cast<unsigned>(-1));
Chris Forbes47567b72017-06-09 12:09:45 -0700586 unsigned component = value_or_default(var_components, id, 0); // Unspecified is OK, is 0
587 bool is_patch = var_patch.find(id) != var_patch.end();
588 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
589
Dave Houltona9df0ce2018-02-07 10:51:23 -0700590 if (builtin != -1)
591 continue;
Chris Forbesa313d772017-06-13 13:59:41 -0700592 else if (!collect_interface_block_members(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700593 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
594 // one result for each.
595 unsigned num_locations = get_locations_consumed_by_type(src, type, is_array_of_verts && !is_patch);
596 for (unsigned int offset = 0; offset < num_locations; offset++) {
597 interface_var v = {};
598 v.id = id;
599 v.type_id = type;
600 v.offset = offset;
601 v.is_patch = is_patch;
602 v.is_relaxed_precision = is_relaxed_precision;
603 out[std::make_pair(location + offset, component)] = v;
604 }
Chris Forbes47567b72017-06-09 12:09:45 -0700605 }
606 }
607 }
608
609 return out;
610}
611
612static std::vector<std::pair<uint32_t, interface_var>> collect_interface_by_input_attachment_index(
613 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
614 std::vector<std::pair<uint32_t, interface_var>> out;
615
616 for (auto insn : *src) {
617 if (insn.opcode() == spv::OpDecorate) {
618 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
619 auto attachment_index = insn.word(3);
620 auto id = insn.word(1);
621
622 if (accessible_ids.count(id)) {
623 auto def = src->get_def(id);
624 assert(def != src->end());
625
626 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
627 auto num_locations = get_locations_consumed_by_type(src, def.word(1), false);
628 for (unsigned int offset = 0; offset < num_locations; offset++) {
629 interface_var v = {};
630 v.id = id;
631 v.type_id = def.word(1);
632 v.offset = offset;
633 out.emplace_back(attachment_index + offset, v);
634 }
635 }
636 }
637 }
638 }
639 }
640
641 return out;
642}
643
Chris Forbes8af24522018-03-07 11:37:45 -0800644static bool is_writable_descriptor_type(shader_module const *module, uint32_t type_id) {
645 auto type = module->get_def(type_id);
646
647 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
648 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
649 if (type.opcode() == spv::OpTypeArray) {
650 type = module->get_def(type.word(2));
651 } else {
652 type = module->get_def(type.word(3));
653 }
654 }
655
656 switch (type.opcode()) {
657 case spv::OpTypeImage: {
658 auto dim = type.word(3);
659 auto sampled = type.word(7);
660 return sampled == 2 && dim != spv::DimSubpassData;
661 }
662
663 case spv::OpTypeStruct:
664 for (auto insn : *module) {
665 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
666 if (insn.word(2) == spv::DecorationBufferBlock) {
667 return true;
668 }
669 }
670 }
671 }
672
673 return false;
674}
675
Chris Forbes47567b72017-06-09 12:09:45 -0700676static std::vector<std::pair<descriptor_slot_t, interface_var>> collect_interface_by_descriptor_slot(
Chris Forbes8af24522018-03-07 11:37:45 -0800677 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
678 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700679 std::unordered_map<unsigned, unsigned> var_sets;
680 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800681 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700682
683 for (auto insn : *src) {
684 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
685 // DecorationDescriptorSet and DecorationBinding.
686 if (insn.opcode() == spv::OpDecorate) {
687 if (insn.word(2) == spv::DecorationDescriptorSet) {
688 var_sets[insn.word(1)] = insn.word(3);
689 }
690
691 if (insn.word(2) == spv::DecorationBinding) {
692 var_bindings[insn.word(1)] = insn.word(3);
693 }
Chris Forbes8af24522018-03-07 11:37:45 -0800694
695 if (insn.word(2) == spv::DecorationNonWritable) {
696 var_nonwritable[insn.word(1)] = 1;
697 }
Chris Forbes47567b72017-06-09 12:09:45 -0700698 }
699 }
700
701 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
702
703 for (auto id : accessible_ids) {
704 auto insn = src->get_def(id);
705 assert(insn != src->end());
706
707 if (insn.opcode() == spv::OpVariable &&
708 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant)) {
709 unsigned set = value_or_default(var_sets, insn.word(2), 0);
710 unsigned binding = value_or_default(var_bindings, insn.word(2), 0);
711
712 interface_var v = {};
713 v.id = insn.word(2);
714 v.type_id = insn.word(1);
715 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800716
717 if (var_nonwritable.find(id) == var_nonwritable.end() && is_writable_descriptor_type(src, insn.word(1))) {
718 *has_writable_descriptor = true;
719 }
Chris Forbes47567b72017-06-09 12:09:45 -0700720 }
721 }
722
723 return out;
724}
725
Chris Forbes47567b72017-06-09 12:09:45 -0700726static bool validate_vi_consistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
727 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
728 // be specified only once.
729 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
730 bool skip = false;
731
732 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
733 auto desc = &vi->pVertexBindingDescriptions[i];
734 auto &binding = bindings[desc->binding];
735 if (binding) {
736 // TODO: VALIDATION_ERROR_096005cc perhaps?
737 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
738 SHADER_CHECKER_INCONSISTENT_VI, "SC", "Duplicate vertex input binding descriptions for binding %d",
739 desc->binding);
740 } else {
741 binding = desc;
742 }
743 }
744
745 return skip;
746}
747
748static bool validate_vi_against_vs_inputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
749 shader_module const *vs, spirv_inst_iter entrypoint) {
750 bool skip = false;
751
752 auto inputs = collect_interface_by_location(vs, entrypoint, spv::StorageClassInput, false);
753
754 // Build index by location
755 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
756 if (vi) {
757 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
758 auto num_locations = get_locations_consumed_by_format(vi->pVertexAttributeDescriptions[i].format);
759 for (auto j = 0u; j < num_locations; j++) {
760 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
761 }
762 }
763 }
764
765 auto it_a = attribs.begin();
766 auto it_b = inputs.begin();
767 bool used = false;
768
769 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
770 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
771 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
772 auto a_first = a_at_end ? 0 : it_a->first;
773 auto b_first = b_at_end ? 0 : it_b->first.first;
774 if (!a_at_end && (b_at_end || a_first < b_first)) {
775 if (!used && log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
776 0, __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
777 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
778 skip = true;
779 }
780 used = false;
781 it_a++;
782 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
783 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
784 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Vertex shader consumes input at location %d but not provided",
785 b_first);
786 it_b++;
787 } else {
788 unsigned attrib_type = get_format_type(it_a->second->format);
789 unsigned input_type = get_fundamental_type(vs, it_b->second.type_id);
790
791 // Type checking
792 if (!(attrib_type & input_type)) {
793 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
794 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
795 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
796 string_VkFormat(it_a->second->format), a_first, describe_type(vs, it_b->second.type_id).c_str());
797 }
798
799 // OK!
800 used = true;
801 it_b++;
802 }
803 }
804
805 return skip;
806}
807
808static bool validate_fs_outputs_against_render_pass(debug_report_data const *report_data, shader_module const *fs,
Chris Forbesa400a8a2017-07-20 13:10:24 -0700809 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline,
Chris Forbes47567b72017-06-09 12:09:45 -0700810 uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100811 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700812
Chris Forbes47567b72017-06-09 12:09:45 -0700813 std::map<uint32_t, VkFormat> color_attachments;
814 auto subpass = rpci->pSubpasses[subpass_index];
815 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
816 uint32_t attachment = subpass.pColorAttachments[i].attachment;
817 if (attachment == VK_ATTACHMENT_UNUSED) continue;
818 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
819 color_attachments[i] = rpci->pAttachments[attachment].format;
820 }
821 }
822
823 bool skip = false;
824
825 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
826
827 auto outputs = collect_interface_by_location(fs, entrypoint, spv::StorageClassOutput, false);
828
829 auto it_a = outputs.begin();
830 auto it_b = color_attachments.begin();
831
832 // Walk attachment list and outputs together
833
834 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
835 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
836 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
837
838 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
839 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
840 SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
841 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
842 it_a++;
843 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700844 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
845 // shader to not produce a matching output.
Chris Forbesa400a8a2017-07-20 13:10:24 -0700846 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700847 skip |=
848 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
Chris Forbes47567b72017-06-09 12:09:45 -0700849 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Attachment %d not written by fragment shader", it_b->first);
Chris Forbesefdd4082017-07-20 11:19:16 -0700850 }
Chris Forbes47567b72017-06-09 12:09:45 -0700851 it_b++;
852 } else {
853 unsigned output_type = get_fundamental_type(fs, it_a->second.type_id);
854 unsigned att_type = get_format_type(it_b->second);
855
856 // Type checking
857 if (!(output_type & att_type)) {
858 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
859 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
860 "Attachment %d of type `%s` does not match fragment shader output type of `%s`", it_b->first,
861 string_VkFormat(it_b->second), describe_type(fs, it_a->second.type_id).c_str());
862 }
863
864 // OK!
865 it_a++;
866 it_b++;
867 }
868 }
869
870 return skip;
871}
872
873// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
874// important for identifying the set of shader resources actually used by an entrypoint, for example.
875// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
876// - NOT the shader input/output interfaces.
877//
878// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
879// converting parts of this to be generated from the machine-readable spec instead.
880static std::unordered_set<uint32_t> mark_accessible_ids(shader_module const *src, spirv_inst_iter entrypoint) {
881 std::unordered_set<uint32_t> ids;
882 std::unordered_set<uint32_t> worklist;
883 worklist.insert(entrypoint.word(2));
884
885 while (!worklist.empty()) {
886 auto id_iter = worklist.begin();
887 auto id = *id_iter;
888 worklist.erase(id_iter);
889
890 auto insn = src->get_def(id);
891 if (insn == src->end()) {
892 // ID is something we didn't collect in build_def_index. that's OK -- we'll stumble across all kinds of things here
893 // that we may not care about.
894 continue;
895 }
896
897 // Try to add to the output set
898 if (!ids.insert(id).second) {
899 continue; // If we already saw this id, we don't want to walk it again.
900 }
901
902 switch (insn.opcode()) {
903 case spv::OpFunction:
904 // Scan whole body of the function, enlisting anything interesting
905 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
906 switch (insn.opcode()) {
907 case spv::OpLoad:
908 case spv::OpAtomicLoad:
909 case spv::OpAtomicExchange:
910 case spv::OpAtomicCompareExchange:
911 case spv::OpAtomicCompareExchangeWeak:
912 case spv::OpAtomicIIncrement:
913 case spv::OpAtomicIDecrement:
914 case spv::OpAtomicIAdd:
915 case spv::OpAtomicISub:
916 case spv::OpAtomicSMin:
917 case spv::OpAtomicUMin:
918 case spv::OpAtomicSMax:
919 case spv::OpAtomicUMax:
920 case spv::OpAtomicAnd:
921 case spv::OpAtomicOr:
922 case spv::OpAtomicXor:
923 worklist.insert(insn.word(3)); // ptr
924 break;
925 case spv::OpStore:
926 case spv::OpAtomicStore:
927 worklist.insert(insn.word(1)); // ptr
928 break;
929 case spv::OpAccessChain:
930 case spv::OpInBoundsAccessChain:
931 worklist.insert(insn.word(3)); // base ptr
932 break;
933 case spv::OpSampledImage:
934 case spv::OpImageSampleImplicitLod:
935 case spv::OpImageSampleExplicitLod:
936 case spv::OpImageSampleDrefImplicitLod:
937 case spv::OpImageSampleDrefExplicitLod:
938 case spv::OpImageSampleProjImplicitLod:
939 case spv::OpImageSampleProjExplicitLod:
940 case spv::OpImageSampleProjDrefImplicitLod:
941 case spv::OpImageSampleProjDrefExplicitLod:
942 case spv::OpImageFetch:
943 case spv::OpImageGather:
944 case spv::OpImageDrefGather:
945 case spv::OpImageRead:
946 case spv::OpImage:
947 case spv::OpImageQueryFormat:
948 case spv::OpImageQueryOrder:
949 case spv::OpImageQuerySizeLod:
950 case spv::OpImageQuerySize:
951 case spv::OpImageQueryLod:
952 case spv::OpImageQueryLevels:
953 case spv::OpImageQuerySamples:
954 case spv::OpImageSparseSampleImplicitLod:
955 case spv::OpImageSparseSampleExplicitLod:
956 case spv::OpImageSparseSampleDrefImplicitLod:
957 case spv::OpImageSparseSampleDrefExplicitLod:
958 case spv::OpImageSparseSampleProjImplicitLod:
959 case spv::OpImageSparseSampleProjExplicitLod:
960 case spv::OpImageSparseSampleProjDrefImplicitLod:
961 case spv::OpImageSparseSampleProjDrefExplicitLod:
962 case spv::OpImageSparseFetch:
963 case spv::OpImageSparseGather:
964 case spv::OpImageSparseDrefGather:
965 case spv::OpImageTexelPointer:
966 worklist.insert(insn.word(3)); // Image or sampled image
967 break;
968 case spv::OpImageWrite:
969 worklist.insert(insn.word(1)); // Image -- different operand order to above
970 break;
971 case spv::OpFunctionCall:
972 for (uint32_t i = 3; i < insn.len(); i++) {
973 worklist.insert(insn.word(i)); // fn itself, and all args
974 }
975 break;
976
977 case spv::OpExtInst:
978 for (uint32_t i = 5; i < insn.len(); i++) {
979 worklist.insert(insn.word(i)); // Operands to ext inst
980 }
981 break;
982 }
983 }
984 break;
985 }
986 }
987
988 return ids;
989}
990
991static bool validate_push_constant_block_against_pipeline(debug_report_data const *report_data,
992 std::vector<VkPushConstantRange> const *push_constant_ranges,
993 shader_module const *src, spirv_inst_iter type,
994 VkShaderStageFlagBits stage) {
995 bool skip = false;
996
997 // Strip off ptrs etc
998 type = get_struct_type(src, type, false);
999 assert(type != src->end());
1000
1001 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1002 // TODO: arrays, matrices, weird sizes
1003 for (auto insn : *src) {
1004 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1005 if (insn.word(3) == spv::DecorationOffset) {
1006 unsigned offset = insn.word(4);
1007 auto size = 4; // Bytes; TODO: calculate this based on the type
1008
1009 bool found_range = false;
1010 for (auto const &range : *push_constant_ranges) {
1011 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1012 found_range = true;
1013
1014 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001015 skip |=
1016 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1017 __LINE__, SHADER_CHECKER_PUSH_CONSTANT_NOT_ACCESSIBLE_FROM_STAGE, "SC",
1018 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1019 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001020 }
1021
1022 break;
1023 }
1024 }
1025
1026 if (!found_range) {
1027 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1028 __LINE__, SHADER_CHECKER_PUSH_CONSTANT_OUT_OF_RANGE, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001029 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001030 }
1031 }
1032 }
1033 }
1034
1035 return skip;
1036}
1037
1038static bool validate_push_constant_usage(debug_report_data const *report_data,
1039 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1040 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
1041 bool skip = false;
1042
1043 for (auto id : accessible_ids) {
1044 auto def_insn = src->get_def(id);
1045 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
1046 skip |= validate_push_constant_block_against_pipeline(report_data, push_constant_ranges, src,
1047 src->get_def(def_insn.word(1)), stage);
1048 }
1049 }
1050
1051 return skip;
1052}
1053
1054// Validate that data for each specialization entry is fully contained within the buffer.
1055static bool validate_specialization_offsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
1056 bool skip = false;
1057
1058 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1059
1060 if (spec) {
1061 for (auto i = 0u; i < spec->mapEntryCount; i++) {
1062 // TODO: This is a good place for VALIDATION_ERROR_1360060a.
1063 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
1064 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1065 VALIDATION_ERROR_1360060c, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001066 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1067 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided). %s.",
1068 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1069 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize,
1070 validation_error_map[VALIDATION_ERROR_1360060c]);
Chris Forbes47567b72017-06-09 12:09:45 -07001071 }
1072 }
1073 }
1074
1075 return skip;
1076}
1077
1078static bool descriptor_type_match(shader_module const *module, uint32_t type_id, VkDescriptorType descriptor_type,
1079 unsigned &descriptor_count) {
1080 auto type = module->get_def(type_id);
1081
1082 descriptor_count = 1;
1083
1084 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
1085 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
1086 if (type.opcode() == spv::OpTypeArray) {
1087 descriptor_count *= get_constant_value(module, type.word(3));
1088 type = module->get_def(type.word(2));
1089 } else {
1090 type = module->get_def(type.word(3));
1091 }
1092 }
1093
1094 switch (type.opcode()) {
1095 case spv::OpTypeStruct: {
1096 for (auto insn : *module) {
1097 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1098 if (insn.word(2) == spv::DecorationBlock) {
1099 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001100 descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
Chris Forbes47567b72017-06-09 12:09:45 -07001101 } else if (insn.word(2) == spv::DecorationBufferBlock) {
1102 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001103 descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
Chris Forbes47567b72017-06-09 12:09:45 -07001104 }
1105 }
1106 }
1107
1108 // Invalid
1109 return false;
1110 }
1111
1112 case spv::OpTypeSampler:
1113 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLER || descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1114
1115 case spv::OpTypeSampledImage:
1116 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) {
1117 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1118 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1119 auto image_type = module->get_def(type.word(2));
1120 auto dim = image_type.word(3);
1121 auto sampled = image_type.word(7);
1122 return dim == spv::DimBuffer && sampled == 1;
1123 }
1124 return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1125
1126 case spv::OpTypeImage: {
1127 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1128 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1129 auto dim = type.word(3);
1130 auto sampled = type.word(7);
1131
1132 if (dim == spv::DimSubpassData) {
1133 return descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
1134 } else if (dim == spv::DimBuffer) {
1135 if (sampled == 1) {
1136 return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
1137 } else {
1138 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1139 }
1140 } else if (sampled == 1) {
1141 return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
Dave Houltona9df0ce2018-02-07 10:51:23 -07001142 descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
Chris Forbes47567b72017-06-09 12:09:45 -07001143 } else {
1144 return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
1145 }
1146 }
1147
1148 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1149 default:
1150 return false; // Mismatch
1151 }
1152}
1153
1154static bool require_feature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
1155 if (!feature) {
1156 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1157 SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001158 "Shader requires VkPhysicalDeviceFeatures::%s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001159 return true;
1160 }
1161 }
1162
1163 return false;
1164}
1165
1166static bool require_extension(debug_report_data const *report_data, bool extension, char const *extension_name) {
1167 if (!extension) {
1168 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001169 SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC", "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001170 extension_name)) {
1171 return true;
1172 }
1173 }
1174
1175 return false;
1176}
1177
Chris Forbes349b3132018-03-07 11:38:08 -08001178static bool validate_shader_capabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1179 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001180 bool skip = false;
1181
1182 auto report_data = GetReportData(dev_data);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001183 auto const &enabledFeatures = GetEnabledFeatures(dev_data);
1184 auto const &extensions = GetEnabledExtensions(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001185
1186 struct CapabilityInfo {
1187 char const *name;
1188 VkBool32 const VkPhysicalDeviceFeatures::*feature;
1189 bool const DeviceExtensions::*extension;
1190 };
1191
1192 using F = VkPhysicalDeviceFeatures;
1193 using E = DeviceExtensions;
1194
1195 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001196 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001197 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1198 // feature bits.
1199 {spv::CapabilityMatrix, {nullptr}},
1200 {spv::CapabilityShader, {nullptr}},
1201 {spv::CapabilityInputAttachment, {nullptr}},
1202 {spv::CapabilitySampled1D, {nullptr}},
1203 {spv::CapabilityImage1D, {nullptr}},
1204 {spv::CapabilitySampledBuffer, {nullptr}},
1205 {spv::CapabilityImageQuery, {nullptr}},
1206 {spv::CapabilityDerivativeControl, {nullptr}},
1207
1208 // Capabilities that are optionally supported, but require a feature to
1209 // be enabled on the device
1210 {spv::CapabilityGeometry, {"geometryShader", &F::geometryShader}},
1211 {spv::CapabilityTessellation, {"tessellationShader", &F::tessellationShader}},
1212 {spv::CapabilityFloat64, {"shaderFloat64", &F::shaderFloat64}},
1213 {spv::CapabilityInt64, {"shaderInt64", &F::shaderInt64}},
1214 {spv::CapabilityTessellationPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1215 {spv::CapabilityGeometryPointSize, {"shaderTessellationAndGeometryPointSize", &F::shaderTessellationAndGeometryPointSize}},
1216 {spv::CapabilityImageGatherExtended, {"shaderImageGatherExtended", &F::shaderImageGatherExtended}},
1217 {spv::CapabilityStorageImageMultisample, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1218 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"shaderUniformBufferArrayDynamicIndexing", &F::shaderUniformBufferArrayDynamicIndexing}},
1219 {spv::CapabilitySampledImageArrayDynamicIndexing, {"shaderSampledImageArrayDynamicIndexing", &F::shaderSampledImageArrayDynamicIndexing}},
1220 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"shaderStorageBufferArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1221 {spv::CapabilityStorageImageArrayDynamicIndexing, {"shaderStorageImageArrayDynamicIndexing", &F::shaderStorageBufferArrayDynamicIndexing}},
1222 {spv::CapabilityClipDistance, {"shaderClipDistance", &F::shaderClipDistance}},
1223 {spv::CapabilityCullDistance, {"shaderCullDistance", &F::shaderCullDistance}},
1224 {spv::CapabilityImageCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1225 {spv::CapabilitySampleRateShading, {"sampleRateShading", &F::sampleRateShading}},
1226 {spv::CapabilitySparseResidency, {"shaderResourceResidency", &F::shaderResourceResidency}},
1227 {spv::CapabilityMinLod, {"shaderResourceMinLod", &F::shaderResourceMinLod}},
1228 {spv::CapabilitySampledCubeArray, {"imageCubeArray", &F::imageCubeArray}},
1229 {spv::CapabilityImageMSArray, {"shaderStorageImageMultisample", &F::shaderStorageImageMultisample}},
1230 {spv::CapabilityStorageImageExtendedFormats, {"shaderStorageImageExtendedFormats", &F::shaderStorageImageExtendedFormats}},
1231 {spv::CapabilityInterpolationFunction, {"sampleRateShading", &F::sampleRateShading}},
1232 {spv::CapabilityStorageImageReadWithoutFormat, {"shaderStorageImageReadWithoutFormat", &F::shaderStorageImageReadWithoutFormat}},
1233 {spv::CapabilityStorageImageWriteWithoutFormat, {"shaderStorageImageWriteWithoutFormat", &F::shaderStorageImageWriteWithoutFormat}},
1234 {spv::CapabilityMultiViewport, {"multiViewport", &F::multiViewport}},
1235
1236 // Capabilities that require an extension
1237 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &E::vk_khr_shader_draw_parameters}},
1238 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &E::vk_nv_geometry_shader_passthrough}},
1239 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &E::vk_nv_sample_mask_override_coverage}},
Dave Houltoneb10ea82017-12-22 12:21:50 -07001240 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &E::vk_ext_shader_viewport_index_layer}},
Chris Forbes47567b72017-06-09 12:09:45 -07001241 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1242 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &E::vk_nv_viewport_array2}},
1243 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_ballot }},
1244 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &E::vk_ext_shader_subgroup_vote }},
1245 };
1246 // clang-format on
1247
1248 for (auto insn : *src) {
1249 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001250 size_t n = capabilities.count(insn.word(1));
1251 if (1 == n) { // key occurs exactly once
1252 auto it = capabilities.find(insn.word(1));
1253 if (it != capabilities.end()) {
1254 if (it->second.feature) {
1255 skip |= require_feature(report_data, enabledFeatures->*(it->second.feature), it->second.name);
1256 }
1257 if (it->second.extension) {
1258 skip |= require_extension(report_data, extensions->*(it->second.extension), it->second.name);
1259 }
Chris Forbes47567b72017-06-09 12:09:45 -07001260 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001261 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1262 bool needs_feature = false, has_feature = false;
1263 bool needs_ext = false, has_ext = false;
1264 std::string feature_names = "(one of) [ ";
1265 std::string extension_names = feature_names;
1266 auto caps = capabilities.equal_range(insn.word(1));
1267 for (auto it = caps.first; it != caps.second; ++it) {
1268 if (it->second.feature) {
1269 needs_feature = true;
1270 has_feature = has_feature || enabledFeatures->*(it->second.feature);
1271 feature_names += it->second.name;
1272 feature_names += " ";
1273 }
1274 if (it->second.extension) {
1275 needs_ext = true;
1276 has_ext = has_ext || extensions->*(it->second.extension);
1277 extension_names += it->second.name;
1278 extension_names += " ";
1279 }
1280 }
1281 if (needs_feature) {
1282 feature_names += "]";
1283 skip |= require_feature(report_data, has_feature, feature_names.c_str());
1284 }
1285 if (needs_ext) {
1286 extension_names += "]";
1287 skip |= require_extension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001288 }
1289 }
1290 }
1291 }
1292
Chris Forbes349b3132018-03-07 11:38:08 -08001293 if (has_writable_descriptor) {
1294 switch (stage) {
1295 case VK_SHADER_STAGE_COMPUTE_BIT:
1296 /* No feature requirements for writes and atomics from compute
1297 * stage */
1298 break;
1299 case VK_SHADER_STAGE_FRAGMENT_BIT:
1300 skip |= require_feature(report_data, enabledFeatures->fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
1301 break;
1302 default:
1303 skip |=
1304 require_feature(report_data, enabledFeatures->vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
1305 break;
1306 }
1307 }
1308
Chris Forbes47567b72017-06-09 12:09:45 -07001309 return skip;
1310}
1311
1312static uint32_t descriptor_type_to_reqs(shader_module const *module, uint32_t type_id) {
1313 auto type = module->get_def(type_id);
1314
1315 while (true) {
1316 switch (type.opcode()) {
1317 case spv::OpTypeArray:
1318 case spv::OpTypeSampledImage:
1319 type = module->get_def(type.word(2));
1320 break;
1321 case spv::OpTypePointer:
1322 type = module->get_def(type.word(3));
1323 break;
1324 case spv::OpTypeImage: {
1325 auto dim = type.word(3);
1326 auto arrayed = type.word(5);
1327 auto msaa = type.word(6);
1328
1329 switch (dim) {
1330 case spv::Dim1D:
1331 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1332 case spv::Dim2D:
1333 return (msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE) |
Dave Houltona9df0ce2018-02-07 10:51:23 -07001334 (arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D);
Chris Forbes47567b72017-06-09 12:09:45 -07001335 case spv::Dim3D:
1336 return DESCRIPTOR_REQ_VIEW_TYPE_3D;
1337 case spv::DimCube:
1338 return arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1339 case spv::DimSubpassData:
1340 return msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1341 default: // buffer, etc.
1342 return 0;
1343 }
1344 }
1345 default:
1346 return 0;
1347 }
1348 }
1349}
1350
1351// For given pipelineLayout verify that the set_layout_node at slot.first
1352// has the requested binding at slot.second and return ptr to that binding
1353static VkDescriptorSetLayoutBinding const *get_descriptor_binding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1354 descriptor_slot_t slot) {
1355 if (!pipelineLayout) return nullptr;
1356
1357 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1358
1359 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1360}
1361
Dave Houltona9df0ce2018-02-07 10:51:23 -07001362static bool validate_pipeline_shader_stage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
1363 PIPELINE_STATE *pipeline, shader_module const **out_module,
1364 spirv_inst_iter *out_entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001365 bool skip = false;
1366 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1367 auto report_data = GetReportData(dev_data);
1368
1369 if (!module->has_valid_spirv) return false;
1370
1371 // Find the entrypoint
1372 auto entrypoint = *out_entrypoint = find_entrypoint(module, pStage->pName, pStage->stage);
1373 if (entrypoint == module->end()) {
1374 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1375 VALIDATION_ERROR_10600586, "SC", "No entrypoint found named `%s` for stage %s. %s.", pStage->pName,
1376 string_VkShaderStageFlagBits(pStage->stage), validation_error_map[VALIDATION_ERROR_10600586])) {
1377 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1378 }
1379 }
1380
Chris Forbes47567b72017-06-09 12:09:45 -07001381 // Mark accessible ids
1382 auto accessible_ids = mark_accessible_ids(module, entrypoint);
1383
1384 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08001385 bool has_writable_descriptor = false;
1386 auto descriptor_uses = collect_interface_by_descriptor_slot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07001387
Chris Forbes349b3132018-03-07 11:38:08 -08001388 // Validate shader capabilities against enabled device features
1389 skip |= validate_shader_capabilities(dev_data, module, pStage->stage, has_writable_descriptor);
1390
Chris Forbes47567b72017-06-09 12:09:45 -07001391 skip |= validate_specialization_offsets(report_data, pStage);
John Zulauff0d06392018-02-16 13:07:24 -07001392 skip |= validate_push_constant_usage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001393 pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001394
1395 // Validate descriptor use
1396 for (auto use : descriptor_uses) {
1397 // While validating shaders capture which slots are used by the pipeline
1398 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
1399 reqs = descriptor_req(reqs | descriptor_type_to_reqs(module, use.second.type_id));
1400
1401 // Verify given pipelineLayout has requested setLayout with requested binding
Chris Forbesc2f751a2017-06-21 11:34:16 -07001402 const auto &binding = get_descriptor_binding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001403 unsigned required_descriptor_count;
1404
1405 if (!binding) {
1406 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1407 SHADER_CHECKER_MISSING_DESCRIPTOR, "SC",
1408 "Shader uses descriptor slot %u.%u (used as type `%s`) but not declared in pipeline layout",
1409 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str());
1410 } else if (~binding->stageFlags & pStage->stage) {
1411 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1412 SHADER_CHECKER_DESCRIPTOR_NOT_ACCESSIBLE_FROM_STAGE, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001413 "Shader uses descriptor slot %u.%u (used as type `%s`) but descriptor not accessible from stage %s",
Chris Forbes47567b72017-06-09 12:09:45 -07001414 use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str(),
1415 string_VkShaderStageFlagBits(pStage->stage));
1416 } else if (!descriptor_type_match(module, use.second.type_id, binding->descriptorType, required_descriptor_count)) {
1417 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1418 SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001419 "Type mismatch on descriptor slot %u.%u (used as type `%s`) but descriptor of type %s", use.first.first,
1420 use.first.second, describe_type(module, use.second.type_id).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001421 string_VkDescriptorType(binding->descriptorType));
1422 } else if (binding->descriptorCount < required_descriptor_count) {
1423 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1424 SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
1425 "Shader expects at least %u descriptors for binding %u.%u (used as type `%s`) but only %u provided",
1426 required_descriptor_count, use.first.first, use.first.second,
1427 describe_type(module, use.second.type_id).c_str(), binding->descriptorCount);
1428 }
1429 }
1430
1431 // Validate use of input attachments against subpass structure
1432 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
1433 auto input_attachment_uses = collect_interface_by_input_attachment_index(module, accessible_ids);
1434
Petr Krause91f7a12017-12-14 20:57:36 +01001435 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001436 auto subpass = pipeline->graphicsPipelineCI.subpass;
1437
1438 for (auto use : input_attachment_uses) {
1439 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1440 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001441 ? input_attachments[use.first].attachment
1442 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001443
1444 if (index == VK_ATTACHMENT_UNUSED) {
1445 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1446 SHADER_CHECKER_MISSING_INPUT_ATTACHMENT, "SC",
1447 "Shader consumes input attachment index %d but not provided in subpass", use.first);
1448 } else if (!(get_format_type(rpci->pAttachments[index].format) & get_fundamental_type(module, use.second.type_id))) {
1449 skip |=
1450 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1451 SHADER_CHECKER_INPUT_ATTACHMENT_TYPE_MISMATCH, "SC",
1452 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
1453 string_VkFormat(rpci->pAttachments[index].format), describe_type(module, use.second.type_id).c_str());
1454 }
1455 }
1456 }
1457
1458 return skip;
1459}
1460
1461static bool validate_interface_between_stages(debug_report_data const *report_data, shader_module const *producer,
1462 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1463 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1464 shader_stage_attributes const *consumer_stage) {
1465 bool skip = false;
1466
1467 auto outputs =
1468 collect_interface_by_location(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1469 auto inputs =
1470 collect_interface_by_location(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
1471
1472 auto a_it = outputs.begin();
1473 auto b_it = inputs.begin();
1474
1475 // Maps sorted by key (location); walk them together to find mismatches
1476 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1477 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1478 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1479 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1480 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1481
1482 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
1483 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1484 __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1485 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1486 a_first.second, consumer_stage->name);
1487 a_it++;
1488 } else if (a_at_end || a_first > b_first) {
1489 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1490 SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "%s consumes input location %u.%u which is not written by %s",
1491 consumer_stage->name, b_first.first, b_first.second, producer_stage->name);
1492 b_it++;
1493 } else {
1494 // subtleties of arrayed interfaces:
1495 // - if is_patch, then the member is not arrayed, even though the interface may be.
1496 // - if is_block_member, then the extra array level of an arrayed interface is not
1497 // expressed in the member type -- it's expressed in the block type.
1498 if (!types_match(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1499 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1500 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
1501 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1502 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC", "Type mismatch on location %u.%u: '%s' vs '%s'",
1503 a_first.first, a_first.second, describe_type(producer, a_it->second.type_id).c_str(),
1504 describe_type(consumer, b_it->second.type_id).c_str());
1505 }
1506 if (a_it->second.is_patch != b_it->second.is_patch) {
1507 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1508 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001509 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
Chris Forbes47567b72017-06-09 12:09:45 -07001510 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1511 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1512 }
1513 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
1514 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0, __LINE__,
1515 SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1516 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1517 a_first.second, producer_stage->name, consumer_stage->name);
1518 }
1519 a_it++;
1520 b_it++;
1521 }
1522 }
1523
1524 return skip;
1525}
1526
1527// Validate that the shaders used by the given pipeline and store the active_slots
1528// that are actually used by the pipeline into pPipeline->active_slots
Chris Forbesa400a8a2017-07-20 13:10:24 -07001529bool validate_and_capture_pipeline_shader_state(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1530 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001531 int vertex_stage = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1532 int fragment_stage = get_shader_stage_id(VK_SHADER_STAGE_FRAGMENT_BIT);
1533 auto report_data = GetReportData(dev_data);
1534
1535 shader_module const *shaders[5];
1536 memset(shaders, 0, sizeof(shaders));
1537 spirv_inst_iter entrypoints[5];
1538 memset(entrypoints, 0, sizeof(entrypoints));
1539 bool skip = false;
1540
1541 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1542 auto pStage = &pCreateInfo->pStages[i];
1543 auto stage_id = get_shader_stage_id(pStage->stage);
Chris Forbesa400a8a2017-07-20 13:10:24 -07001544 skip |= validate_pipeline_shader_stage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id]);
Chris Forbes47567b72017-06-09 12:09:45 -07001545 }
1546
1547 // if the shader stages are no good individually, cross-stage validation is pointless.
1548 if (skip) return true;
1549
1550 auto vi = pCreateInfo->pVertexInputState;
1551
1552 if (vi) {
1553 skip |= validate_vi_consistency(report_data, vi);
1554 }
1555
1556 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
1557 skip |= validate_vi_against_vs_inputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
1558 }
1559
1560 int producer = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
1561 int consumer = get_shader_stage_id(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
1562
1563 while (!shaders[producer] && producer != fragment_stage) {
1564 producer++;
1565 consumer++;
1566 }
1567
1568 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1569 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001570 if (shaders[consumer]) {
1571 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
1572 skip |= validate_interface_between_stages(report_data, shaders[producer], entrypoints[producer],
1573 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1574 &shader_stage_attribs[consumer]);
1575 }
Chris Forbes47567b72017-06-09 12:09:45 -07001576
1577 producer = consumer;
1578 }
1579 }
1580
1581 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001582 skip |= validate_fs_outputs_against_render_pass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
1583 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07001584 }
1585
1586 return skip;
1587}
1588
Chris Forbesa400a8a2017-07-20 13:10:24 -07001589bool validate_compute_pipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1590 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001591
1592 shader_module const *module;
1593 spirv_inst_iter entrypoint;
1594
Chris Forbesa400a8a2017-07-20 13:10:24 -07001595 return validate_pipeline_shader_stage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint);
Chris Forbes47567b72017-06-09 12:09:45 -07001596}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001597
Dave Houltona9df0ce2018-02-07 10:51:23 -07001598uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07001599
Dave Houltona9df0ce2018-02-07 10:51:23 -07001600static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07001601 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
1602 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
1603 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
1604 }
1605
1606 return nullptr;
1607}
1608
Chris Forbes4ae55b32017-06-09 14:42:56 -07001609bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1610 bool skip = false;
1611 spv_result_t spv_valid = SPV_SUCCESS;
1612 auto report_data = GetReportData(dev_data);
1613
1614 if (GetDisables(dev_data)->shader_validation) {
1615 return false;
1616 }
1617
1618 auto have_glsl_shader = GetEnabledExtensions(dev_data)->vk_nv_glsl_shader;
1619
1620 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001621 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,
1622 VALIDATION_ERROR_12a00ac0, "SC",
Chris Forbes4ae55b32017-06-09 14:42:56 -07001623 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ". %s",
1624 pCreateInfo->codeSize, validation_error_map[VALIDATION_ERROR_12a00ac0]);
1625 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07001626 auto cache = GetValidationCacheInfo(pCreateInfo);
1627 uint32_t hash = 0;
1628 if (cache) {
1629 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001630 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07001631 }
1632
Chris Forbes4ae55b32017-06-09 14:42:56 -07001633 // Use SPIRV-Tools validator to try and catch any issues with the module itself
1634 spv_context ctx = spvContextCreate(SPV_ENV_VULKAN_1_0);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001635 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07001636 spv_diagnostic diag = nullptr;
1637
1638 spv_valid = spvValidate(ctx, &binary, &diag);
1639 if (spv_valid != SPV_SUCCESS) {
1640 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001641 skip |=
1642 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
1643 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__, SHADER_CHECKER_INCONSISTENT_SPIRV, "SC",
1644 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07001645 }
Chris Forbes9a61e082017-07-24 15:35:29 -07001646 } else {
1647 if (cache) {
1648 cache->Insert(hash);
1649 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07001650 }
1651
1652 spvDiagnosticDestroy(diag);
1653 spvContextDestroy(ctx);
1654 }
1655
1656 *spirv_valid = (spv_valid == SPV_SUCCESS);
1657 return skip;
1658}