blob: 1acaf65f127b660451524930489ff28791bb4c88 [file] [log] [blame]
Dave Houlton51653902018-06-22 17:32:13 -06001/* Copyright (c) 2015-2018 The Khronos Group Inc.
2 * Copyright (c) 2015-2018 Valve Corporation
3 * Copyright (c) 2015-2018 LunarG, Inc.
4 * Copyright (C) 2015-2018 Google Inc.
Chris Forbes47567b72017-06-09 12:09:45 -07005 *
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>
Dave Houlton51653902018-06-22 17:32:13 -060019 * Author: Dave Houlton <daveh@lunarg.com>
Chris Forbes47567b72017-06-09 12:09:45 -070020 */
21
22#include <cinttypes>
23#include <cassert>
24#include <vector>
25#include <unordered_map>
26#include <string>
27#include <sstream>
28#include <SPIRV/spirv.hpp>
29#include "vk_loader_platform.h"
30#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070031#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
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060070void shader_module::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -070071 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:
Jeff Bolz105d6492018-09-29 15:46:44 -050094 case spv::OpTypeAccelerationStructureNVX:
Chris Forbes47567b72017-06-09 12:09:45 -070095 def_index[insn.word(1)] = insn.offset();
96 break;
97
98 // Fixed constants
99 case spv::OpConstantTrue:
100 case spv::OpConstantFalse:
101 case spv::OpConstant:
102 case spv::OpConstantComposite:
103 case spv::OpConstantSampler:
104 case spv::OpConstantNull:
105 def_index[insn.word(2)] = insn.offset();
106 break;
107
108 // Specialization constants
109 case spv::OpSpecConstantTrue:
110 case spv::OpSpecConstantFalse:
111 case spv::OpSpecConstant:
112 case spv::OpSpecConstantComposite:
113 case spv::OpSpecConstantOp:
114 def_index[insn.word(2)] = insn.offset();
115 break;
116
117 // Variables
118 case spv::OpVariable:
119 def_index[insn.word(2)] = insn.offset();
120 break;
121
122 // Functions
123 case spv::OpFunction:
124 def_index[insn.word(2)] = insn.offset();
125 break;
126
127 default:
128 // We don't care about any other defs for now.
129 break;
130 }
131 }
132}
133
Jeff Bolz105d6492018-09-29 15:46:44 -0500134unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
135 switch (mode) {
136 case spv::ExecutionModelVertex:
137 return VK_SHADER_STAGE_VERTEX_BIT;
138 case spv::ExecutionModelTessellationControl:
139 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
140 case spv::ExecutionModelTessellationEvaluation:
141 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
142 case spv::ExecutionModelGeometry:
143 return VK_SHADER_STAGE_GEOMETRY_BIT;
144 case spv::ExecutionModelFragment:
145 return VK_SHADER_STAGE_FRAGMENT_BIT;
146 case spv::ExecutionModelGLCompute:
147 return VK_SHADER_STAGE_COMPUTE_BIT;
148 case spv::ExecutionModelRayGenerationNVX:
149 return VK_SHADER_STAGE_RAYGEN_BIT_NVX;
150 case spv::ExecutionModelAnyHitNVX:
151 return VK_SHADER_STAGE_ANY_HIT_BIT_NVX;
152 case spv::ExecutionModelClosestHitNVX:
153 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NVX;
154 case spv::ExecutionModelMissNVX:
155 return VK_SHADER_STAGE_MISS_BIT_NVX;
156 case spv::ExecutionModelIntersectionNVX:
157 return VK_SHADER_STAGE_INTERSECTION_BIT_NVX;
158 case spv::ExecutionModelCallableNVX:
159 return VK_SHADER_STAGE_CALLABLE_BIT_NVX;
160 case spv::ExecutionModelTaskNV:
161 return VK_SHADER_STAGE_TASK_BIT_NV;
162 case spv::ExecutionModelMeshNV:
163 return VK_SHADER_STAGE_MESH_BIT_NV;
164 default:
165 return 0;
166 }
167}
168
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600169static spirv_inst_iter FindEntrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
Chris Forbes47567b72017-06-09 12:09:45 -0700170 for (auto insn : *src) {
171 if (insn.opcode() == spv::OpEntryPoint) {
172 auto entrypointName = (char const *)&insn.word(3);
Jeff Bolz105d6492018-09-29 15:46:44 -0500173 auto executionModel = insn.word(1);
174 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
Chris Forbes47567b72017-06-09 12:09:45 -0700175
176 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
177 return insn;
178 }
179 }
180 }
181
182 return src->end();
183}
184
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600185static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700186 switch (sc) {
187 case spv::StorageClassInput:
188 return "input";
189 case spv::StorageClassOutput:
190 return "output";
191 case spv::StorageClassUniformConstant:
192 return "const uniform";
193 case spv::StorageClassUniform:
194 return "uniform";
195 case spv::StorageClassWorkgroup:
196 return "workgroup local";
197 case spv::StorageClassCrossWorkgroup:
198 return "workgroup global";
199 case spv::StorageClassPrivate:
200 return "private global";
201 case spv::StorageClassFunction:
202 return "function";
203 case spv::StorageClassGeneric:
204 return "generic";
205 case spv::StorageClassAtomicCounter:
206 return "atomic counter";
207 case spv::StorageClassImage:
208 return "image";
209 case spv::StorageClassPushConstant:
210 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800211 case spv::StorageClassStorageBuffer:
212 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700213 default:
214 return "unknown";
215 }
216}
217
218// Get the value of an integral constant
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600219unsigned GetConstantValue(shader_module const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700220 auto value = src->get_def(id);
221 assert(value != src->end());
222
223 if (value.opcode() != spv::OpConstant) {
224 // TODO: Either ensure that the specialization transform is already performed on a module we're
225 // considering here, OR -- specialize on the fly now.
226 return 1;
227 }
228
229 return value.word(3);
230}
231
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600232static void DescribeTypeInner(std::ostringstream &ss, shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700233 auto insn = src->get_def(type);
234 assert(insn != src->end());
235
236 switch (insn.opcode()) {
237 case spv::OpTypeBool:
238 ss << "bool";
239 break;
240 case spv::OpTypeInt:
241 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
242 break;
243 case spv::OpTypeFloat:
244 ss << "float" << insn.word(2);
245 break;
246 case spv::OpTypeVector:
247 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600248 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700249 break;
250 case spv::OpTypeMatrix:
251 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600252 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700253 break;
254 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600255 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
256 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700257 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700258 case spv::OpTypeRuntimeArray:
259 ss << "runtime arr[] of ";
260 DescribeTypeInner(ss, src, insn.word(2));
261 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700262 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600263 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
264 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700265 break;
266 case spv::OpTypeStruct: {
267 ss << "struct of (";
268 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600269 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700270 if (i == insn.len() - 1) {
271 ss << ")";
272 } else {
273 ss << ", ";
274 }
275 }
276 break;
277 }
278 case spv::OpTypeSampler:
279 ss << "sampler";
280 break;
281 case spv::OpTypeSampledImage:
282 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600283 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700284 break;
285 case spv::OpTypeImage:
286 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
287 break;
Jeff Bolz105d6492018-09-29 15:46:44 -0500288 case spv::OpTypeAccelerationStructureNVX:
289 ss << "accelerationStruture";
290 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700291 default:
292 ss << "oddtype";
293 break;
294 }
295}
296
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600297static std::string DescribeType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700298 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600299 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700300 return ss.str();
301}
302
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600303static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700304 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
305 return type.word(2) < 64;
306}
307
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600308static bool TypesMatch(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
309 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700310 // Walk two type trees together, and complain about differences
311 auto a_insn = a->get_def(a_type);
312 auto b_insn = b->get_def(b_type);
313 assert(a_insn != a->end());
314 assert(b_insn != b->end());
315
Chris Forbes062f1222018-08-21 15:34:15 -0700316 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
317
Chris Forbes47567b72017-06-09 12:09:45 -0700318 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600319 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700320 }
321
322 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
323 // We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600324 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700325 }
326
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600327 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
328 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700329 }
330
331 if (a_insn.opcode() != b_insn.opcode()) {
332 return false;
333 }
334
335 if (a_insn.opcode() == spv::OpTypePointer) {
336 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600337 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700338 }
339
340 if (a_arrayed || b_arrayed) {
341 // If we havent resolved array-of-verts by here, we're not going to.
342 return false;
343 }
344
345 switch (a_insn.opcode()) {
346 case spv::OpTypeBool:
347 return true;
348 case spv::OpTypeInt:
349 // Match on width, signedness
350 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
351 case spv::OpTypeFloat:
352 // Match on width
353 return a_insn.word(2) == b_insn.word(2);
354 case spv::OpTypeVector:
355 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600356 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
357 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700358 return a_insn.word(3) >= b_insn.word(3);
359 } else {
360 return a_insn.word(3) == b_insn.word(3);
361 }
362 case spv::OpTypeMatrix:
363 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600364 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700365 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700366 case spv::OpTypeArray:
367 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
368 // vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600369 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
370 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700371 case spv::OpTypeStruct:
372 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700373 {
374 if (a_insn.len() != b_insn.len()) {
375 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700376 }
Chris Forbes47567b72017-06-09 12:09:45 -0700377
Dave Houltona9df0ce2018-02-07 10:51:23 -0700378 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600379 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700380 return false;
381 }
382 }
383
384 return true;
385 }
Chris Forbes47567b72017-06-09 12:09:45 -0700386 default:
387 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
388 return false;
389 }
390}
391
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600392static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700393 auto it = map.find(id);
394 if (it == map.end())
395 return def;
396 else
397 return it->second;
398}
399
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600400static unsigned GetLocationsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700401 auto insn = src->get_def(type);
402 assert(insn != src->end());
403
404 switch (insn.opcode()) {
405 case spv::OpTypePointer:
406 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
407 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600408 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700409 case spv::OpTypeArray:
410 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600411 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700412 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600413 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700414 }
415 case spv::OpTypeMatrix:
416 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600417 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700418 case spv::OpTypeVector: {
419 auto scalar_type = src->get_def(insn.word(2));
420 auto bit_width =
421 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
422
423 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
424 return (bit_width * insn.word(3) + 127) / 128;
425 }
426 default:
427 // Everything else is just 1.
428 return 1;
429
430 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
431 }
432}
433
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600434static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700435 switch (format) {
436 case VK_FORMAT_R64G64B64A64_SFLOAT:
437 case VK_FORMAT_R64G64B64A64_SINT:
438 case VK_FORMAT_R64G64B64A64_UINT:
439 case VK_FORMAT_R64G64B64_SFLOAT:
440 case VK_FORMAT_R64G64B64_SINT:
441 case VK_FORMAT_R64G64B64_UINT:
442 return 2;
443 default:
444 return 1;
445 }
446}
447
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600448static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700449 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
450 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
451 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
452 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700453 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
454 return FORMAT_TYPE_FLOAT;
455}
456
457// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
Chris Forbes062f1222018-08-21 15:34:15 -0700458// also used for input attachments, as we statically know their format.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600459static unsigned GetFundamentalType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700460 auto insn = src->get_def(type);
461 assert(insn != src->end());
462
463 switch (insn.opcode()) {
464 case spv::OpTypeInt:
465 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
466 case spv::OpTypeFloat:
467 return FORMAT_TYPE_FLOAT;
468 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700469 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700470 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700471 case spv::OpTypeRuntimeArray:
472 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600473 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700474 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600475 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700476
477 default:
478 return 0;
479 }
480}
481
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600482static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700483 uint32_t bit_pos = uint32_t(u_ffs(stage));
484 return bit_pos - 1;
485}
486
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600487static spirv_inst_iter GetStructType(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700488 while (true) {
489 if (def.opcode() == spv::OpTypePointer) {
490 def = src->get_def(def.word(3));
491 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
492 def = src->get_def(def.word(2));
493 is_array_of_verts = false;
494 } else if (def.opcode() == spv::OpTypeStruct) {
495 return def;
496 } else {
497 return src->end();
498 }
499 }
500}
501
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600502static bool CollectInterfaceBlockMembers(shader_module const *src, std::map<location_t, interface_var> *out,
503 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts, uint32_t id,
504 uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700505 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600506 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700507 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
508 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700509 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700510 }
511
512 std::unordered_map<unsigned, unsigned> member_components;
513 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700514 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700515
516 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
517 for (auto insn : *src) {
518 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
519 unsigned member_index = insn.word(2);
520
521 if (insn.word(3) == spv::DecorationComponent) {
522 unsigned component = insn.word(4);
523 member_components[member_index] = component;
524 }
525
526 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
527 member_relaxed_precision[member_index] = 1;
528 }
Chris Forbesa313d772017-06-13 13:59:41 -0700529
530 if (insn.word(3) == spv::DecorationPatch) {
531 member_patch[member_index] = 1;
532 }
Chris Forbes47567b72017-06-09 12:09:45 -0700533 }
534 }
535
Chris Forbesa313d772017-06-13 13:59:41 -0700536 // TODO: correctly handle location assignment from outside
537
Chris Forbes47567b72017-06-09 12:09:45 -0700538 // Second pass -- produce the output, from Location decorations
539 for (auto insn : *src) {
540 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
541 unsigned member_index = insn.word(2);
542 unsigned member_type_id = type.word(2 + member_index);
543
544 if (insn.word(3) == spv::DecorationLocation) {
545 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600546 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700547 auto component_it = member_components.find(member_index);
548 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
549 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700550 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700551
552 for (unsigned int offset = 0; offset < num_locations; offset++) {
553 interface_var v = {};
554 v.id = id;
555 // TODO: member index in interface_var too?
556 v.type_id = member_type_id;
557 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700558 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700559 v.is_block_member = true;
560 v.is_relaxed_precision = is_relaxed_precision;
561 (*out)[std::make_pair(location + offset, component)] = v;
562 }
563 }
564 }
565 }
Chris Forbesa313d772017-06-13 13:59:41 -0700566
567 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700568}
569
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600570static std::map<location_t, interface_var> CollectInterfaceByLocation(shader_module const *src, spirv_inst_iter entrypoint,
571 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700572 std::unordered_map<unsigned, unsigned> var_locations;
573 std::unordered_map<unsigned, unsigned> var_builtins;
574 std::unordered_map<unsigned, unsigned> var_components;
575 std::unordered_map<unsigned, unsigned> blocks;
576 std::unordered_map<unsigned, unsigned> var_patch;
577 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
578
579 for (auto insn : *src) {
580 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
581 // fits neither model.
582 if (insn.opcode() == spv::OpDecorate) {
583 if (insn.word(2) == spv::DecorationLocation) {
584 var_locations[insn.word(1)] = insn.word(3);
585 }
586
587 if (insn.word(2) == spv::DecorationBuiltIn) {
588 var_builtins[insn.word(1)] = insn.word(3);
589 }
590
591 if (insn.word(2) == spv::DecorationComponent) {
592 var_components[insn.word(1)] = insn.word(3);
593 }
594
595 if (insn.word(2) == spv::DecorationBlock) {
596 blocks[insn.word(1)] = 1;
597 }
598
599 if (insn.word(2) == spv::DecorationPatch) {
600 var_patch[insn.word(1)] = 1;
601 }
602
603 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
604 var_relaxed_precision[insn.word(1)] = 1;
605 }
606 }
607 }
608
609 // TODO: handle grouped decorations
610 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
611
612 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
613 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
614 uint32_t word = 3;
615 while (entrypoint.word(word) & 0xff000000u) {
616 ++word;
617 }
618 ++word;
619
620 std::map<location_t, interface_var> out;
621
622 for (; word < entrypoint.len(); word++) {
623 auto insn = src->get_def(entrypoint.word(word));
624 assert(insn != src->end());
625 assert(insn.opcode() == spv::OpVariable);
626
627 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
628 unsigned id = insn.word(2);
629 unsigned type = insn.word(1);
630
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600631 int location = ValueOrDefault(var_locations, id, static_cast<unsigned>(-1));
632 int builtin = ValueOrDefault(var_builtins, id, static_cast<unsigned>(-1));
633 unsigned component = ValueOrDefault(var_components, id, 0); // Unspecified is OK, is 0
Chris Forbes47567b72017-06-09 12:09:45 -0700634 bool is_patch = var_patch.find(id) != var_patch.end();
635 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
636
Dave Houltona9df0ce2018-02-07 10:51:23 -0700637 if (builtin != -1)
638 continue;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600639 else if (!CollectInterfaceBlockMembers(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700640 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
641 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600642 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700643 for (unsigned int offset = 0; offset < num_locations; offset++) {
644 interface_var v = {};
645 v.id = id;
646 v.type_id = type;
647 v.offset = offset;
648 v.is_patch = is_patch;
649 v.is_relaxed_precision = is_relaxed_precision;
650 out[std::make_pair(location + offset, component)] = v;
651 }
Chris Forbes47567b72017-06-09 12:09:45 -0700652 }
653 }
654 }
655
656 return out;
657}
658
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600659static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Chris Forbes47567b72017-06-09 12:09:45 -0700660 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
661 std::vector<std::pair<uint32_t, interface_var>> out;
662
663 for (auto insn : *src) {
664 if (insn.opcode() == spv::OpDecorate) {
665 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
666 auto attachment_index = insn.word(3);
667 auto id = insn.word(1);
668
669 if (accessible_ids.count(id)) {
670 auto def = src->get_def(id);
671 assert(def != src->end());
672
673 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600674 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700675 for (unsigned int offset = 0; offset < num_locations; offset++) {
676 interface_var v = {};
677 v.id = id;
678 v.type_id = def.word(1);
679 v.offset = offset;
680 out.emplace_back(attachment_index + offset, v);
681 }
682 }
683 }
684 }
685 }
686 }
687
688 return out;
689}
690
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700691static bool IsWritableDescriptorType(shader_module const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800692 auto type = module->get_def(type_id);
693
694 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
Chris Forbes062f1222018-08-21 15:34:15 -0700695 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
696 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700697 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800698 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700699 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800700 }
701 }
702
703 switch (type.opcode()) {
704 case spv::OpTypeImage: {
705 auto dim = type.word(3);
706 auto sampled = type.word(7);
707 return sampled == 2 && dim != spv::DimSubpassData;
708 }
709
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700710 case spv::OpTypeStruct: {
711 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8af24522018-03-07 11:37:45 -0800712 for (auto insn : *module) {
713 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
714 if (insn.word(2) == spv::DecorationBufferBlock) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700715 // Legacy storage block in the Uniform storage class
716 // has its struct type decorated with BufferBlock.
717 is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800718 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700719 } else if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
720 insn.word(3) == spv::DecorationNonWritable) {
721 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800722 }
723 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700724
725 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
726 // as nonwritable.
727 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
728 }
Chris Forbes8af24522018-03-07 11:37:45 -0800729 }
730
731 return false;
732}
733
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600734static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Chris Forbes8af24522018-03-07 11:37:45 -0800735 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
736 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700737 std::unordered_map<unsigned, unsigned> var_sets;
738 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800739 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700740
741 for (auto insn : *src) {
742 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
743 // DecorationDescriptorSet and DecorationBinding.
744 if (insn.opcode() == spv::OpDecorate) {
745 if (insn.word(2) == spv::DecorationDescriptorSet) {
746 var_sets[insn.word(1)] = insn.word(3);
747 }
748
749 if (insn.word(2) == spv::DecorationBinding) {
750 var_bindings[insn.word(1)] = insn.word(3);
751 }
Chris Forbes8af24522018-03-07 11:37:45 -0800752
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700753 // Note: do toplevel DecorationNonWritable out here; it applies to
754 // the OpVariable rather than the type.
Chris Forbes8af24522018-03-07 11:37:45 -0800755 if (insn.word(2) == spv::DecorationNonWritable) {
756 var_nonwritable[insn.word(1)] = 1;
757 }
Chris Forbes47567b72017-06-09 12:09:45 -0700758 }
759 }
760
761 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
762
763 for (auto id : accessible_ids) {
764 auto insn = src->get_def(id);
765 assert(insn != src->end());
766
767 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800768 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
769 insn.word(3) == spv::StorageClassStorageBuffer)) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600770 unsigned set = ValueOrDefault(var_sets, insn.word(2), 0);
771 unsigned binding = ValueOrDefault(var_bindings, insn.word(2), 0);
Chris Forbes47567b72017-06-09 12:09:45 -0700772
773 interface_var v = {};
774 v.id = insn.word(2);
775 v.type_id = insn.word(1);
776 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800777
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700778 if (var_nonwritable.find(id) == var_nonwritable.end() &&
779 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800780 *has_writable_descriptor = true;
781 }
Chris Forbes47567b72017-06-09 12:09:45 -0700782 }
783 }
784
785 return out;
786}
787
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600788static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700789 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
790 // be specified only once.
791 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
792 bool skip = false;
793
794 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
795 auto desc = &vi->pVertexBindingDescriptions[i];
796 auto &binding = bindings[desc->binding];
797 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600798 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600799 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -0600800 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700801 desc->binding);
802 } else {
803 binding = desc;
804 }
805 }
806
807 return skip;
808}
809
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600810static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
811 shader_module const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700812 bool skip = false;
813
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600814 auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700815
816 // Build index by location
817 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
818 if (vi) {
819 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600820 auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
Chris Forbes47567b72017-06-09 12:09:45 -0700821 for (auto j = 0u; j < num_locations; j++) {
822 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
823 }
824 }
825 }
826
827 auto it_a = attribs.begin();
828 auto it_b = inputs.begin();
829 bool used = false;
830
831 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
832 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
833 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
834 auto a_first = a_at_end ? 0 : it_a->first;
835 auto b_first = b_at_end ? 0 : it_b->first.first;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600836
Chris Forbes47567b72017-06-09 12:09:45 -0700837 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600838 if (!used &&
839 log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600840 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600841 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700842 skip = true;
843 }
844 used = false;
845 it_a++;
846 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600847 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600848 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600849 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700850 it_b++;
851 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600852 unsigned attrib_type = GetFormatType(it_a->second->format);
853 unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700854
855 // Type checking
856 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600857 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600858 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700859 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600860 string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700861 }
862
863 // OK!
864 used = true;
865 it_b++;
866 }
867 }
868
869 return skip;
870}
871
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600872static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, shader_module const *fs,
873 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100874 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700875
Chris Forbes47567b72017-06-09 12:09:45 -0700876 std::map<uint32_t, VkFormat> color_attachments;
877 auto subpass = rpci->pSubpasses[subpass_index];
878 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
879 uint32_t attachment = subpass.pColorAttachments[i].attachment;
880 if (attachment == VK_ATTACHMENT_UNUSED) continue;
881 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
882 color_attachments[i] = rpci->pAttachments[attachment].format;
883 }
884 }
885
886 bool skip = false;
887
888 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
889
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600890 auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700891
892 auto it_a = outputs.begin();
893 auto it_b = color_attachments.begin();
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600894 bool used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700895
896 // Walk attachment list and outputs together
897
898 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
899 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
900 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
901
902 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600903 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -0600904 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Chris Forbes47567b72017-06-09 12:09:45 -0700905 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
906 it_a++;
907 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700908 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
909 // shader to not produce a matching output.
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600910 if (!used) {
911 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700912 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600913 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Chris Forbescfe4dca2018-10-05 10:15:00 -0700914 "Attachment %d not written by fragment shader; undefined values will be written to attachment",
915 it_b->first);
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600916 }
Chris Forbesefdd4082017-07-20 11:19:16 -0700917 }
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600918 used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700919 it_b++;
920 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600921 unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
922 unsigned att_type = GetFormatType(it_b->second);
Chris Forbes47567b72017-06-09 12:09:45 -0700923
924 // Type checking
925 if (!(output_type & att_type)) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700926 skip |= log_msg(
927 report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
928 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
929 "Attachment %d of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
930 it_b->first, string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700931 }
932
933 // OK!
934 it_a++;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600935 used = true;
Chris Forbes47567b72017-06-09 12:09:45 -0700936 }
937 }
938
939 return skip;
940}
941
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600942// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
943// This function examines instructions in the static call tree for a write to this variable.
944static bool IsPointSizeWritten(shader_module const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
945 auto type = builtin_instr.opcode();
946 uint32_t target_id = builtin_instr.word(1);
947 bool init_complete = false;
948
949 if (type == spv::OpMemberDecorate) {
950 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
951 auto insn = entrypoint;
952 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
953 switch (insn.opcode()) {
954 case spv::OpTypePointer:
955 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
956 target_id = insn.word(1);
957 }
958 break;
959 case spv::OpVariable:
960 if (insn.word(1) == target_id) {
961 target_id = insn.word(2);
962 init_complete = true;
963 }
964 break;
965 }
966 insn++;
967 }
968 }
969
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -0600970 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
971
972 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600973 std::unordered_set<uint32_t> worklist;
974 worklist.insert(entrypoint.word(2));
975
976 // Follow instructions in call graph looking for writes to target
977 while (!worklist.empty() && !found_write) {
978 auto id_iter = worklist.begin();
979 auto id = *id_iter;
980 worklist.erase(id_iter);
981
982 auto insn = src->get_def(id);
983 if (insn == src->end()) {
984 continue;
985 }
986
987 if (insn.opcode() == spv::OpFunction) {
988 // Scan body of function looking for other function calls or items in our ID chain
989 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
990 switch (insn.opcode()) {
991 case spv::OpAccessChain:
992 if (insn.word(3) == target_id) {
993 if (type == spv::OpMemberDecorate) {
994 auto value = GetConstantValue(src, insn.word(4));
995 if (value == builtin_instr.word(2)) {
996 target_id = insn.word(2);
997 }
998 } else {
999 target_id = insn.word(2);
1000 }
1001 }
1002 break;
1003 case spv::OpStore:
1004 if (insn.word(1) == target_id) {
1005 found_write = true;
1006 }
1007 break;
1008 case spv::OpFunctionCall:
1009 worklist.insert(insn.word(3));
1010 break;
1011 }
1012 }
1013 }
1014 }
1015 return found_write;
1016}
1017
Chris Forbes47567b72017-06-09 12:09:45 -07001018// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1019// important for identifying the set of shader resources actually used by an entrypoint, for example.
1020// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1021// - NOT the shader input/output interfaces.
1022//
1023// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1024// converting parts of this to be generated from the machine-readable spec instead.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001025static std::unordered_set<uint32_t> MarkAccessibleIds(shader_module const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001026 std::unordered_set<uint32_t> ids;
1027 std::unordered_set<uint32_t> worklist;
1028 worklist.insert(entrypoint.word(2));
1029
1030 while (!worklist.empty()) {
1031 auto id_iter = worklist.begin();
1032 auto id = *id_iter;
1033 worklist.erase(id_iter);
1034
1035 auto insn = src->get_def(id);
1036 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001037 // ID is something we didn't collect in BuildDefIndex. that's OK -- we'll stumble across all kinds of things here
Chris Forbes47567b72017-06-09 12:09:45 -07001038 // that we may not care about.
1039 continue;
1040 }
1041
1042 // Try to add to the output set
1043 if (!ids.insert(id).second) {
1044 continue; // If we already saw this id, we don't want to walk it again.
1045 }
1046
1047 switch (insn.opcode()) {
1048 case spv::OpFunction:
1049 // Scan whole body of the function, enlisting anything interesting
1050 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1051 switch (insn.opcode()) {
1052 case spv::OpLoad:
1053 case spv::OpAtomicLoad:
1054 case spv::OpAtomicExchange:
1055 case spv::OpAtomicCompareExchange:
1056 case spv::OpAtomicCompareExchangeWeak:
1057 case spv::OpAtomicIIncrement:
1058 case spv::OpAtomicIDecrement:
1059 case spv::OpAtomicIAdd:
1060 case spv::OpAtomicISub:
1061 case spv::OpAtomicSMin:
1062 case spv::OpAtomicUMin:
1063 case spv::OpAtomicSMax:
1064 case spv::OpAtomicUMax:
1065 case spv::OpAtomicAnd:
1066 case spv::OpAtomicOr:
1067 case spv::OpAtomicXor:
1068 worklist.insert(insn.word(3)); // ptr
1069 break;
1070 case spv::OpStore:
1071 case spv::OpAtomicStore:
1072 worklist.insert(insn.word(1)); // ptr
1073 break;
1074 case spv::OpAccessChain:
1075 case spv::OpInBoundsAccessChain:
1076 worklist.insert(insn.word(3)); // base ptr
1077 break;
1078 case spv::OpSampledImage:
1079 case spv::OpImageSampleImplicitLod:
1080 case spv::OpImageSampleExplicitLod:
1081 case spv::OpImageSampleDrefImplicitLod:
1082 case spv::OpImageSampleDrefExplicitLod:
1083 case spv::OpImageSampleProjImplicitLod:
1084 case spv::OpImageSampleProjExplicitLod:
1085 case spv::OpImageSampleProjDrefImplicitLod:
1086 case spv::OpImageSampleProjDrefExplicitLod:
1087 case spv::OpImageFetch:
1088 case spv::OpImageGather:
1089 case spv::OpImageDrefGather:
1090 case spv::OpImageRead:
1091 case spv::OpImage:
1092 case spv::OpImageQueryFormat:
1093 case spv::OpImageQueryOrder:
1094 case spv::OpImageQuerySizeLod:
1095 case spv::OpImageQuerySize:
1096 case spv::OpImageQueryLod:
1097 case spv::OpImageQueryLevels:
1098 case spv::OpImageQuerySamples:
1099 case spv::OpImageSparseSampleImplicitLod:
1100 case spv::OpImageSparseSampleExplicitLod:
1101 case spv::OpImageSparseSampleDrefImplicitLod:
1102 case spv::OpImageSparseSampleDrefExplicitLod:
1103 case spv::OpImageSparseSampleProjImplicitLod:
1104 case spv::OpImageSparseSampleProjExplicitLod:
1105 case spv::OpImageSparseSampleProjDrefImplicitLod:
1106 case spv::OpImageSparseSampleProjDrefExplicitLod:
1107 case spv::OpImageSparseFetch:
1108 case spv::OpImageSparseGather:
1109 case spv::OpImageSparseDrefGather:
1110 case spv::OpImageTexelPointer:
1111 worklist.insert(insn.word(3)); // Image or sampled image
1112 break;
1113 case spv::OpImageWrite:
1114 worklist.insert(insn.word(1)); // Image -- different operand order to above
1115 break;
1116 case spv::OpFunctionCall:
1117 for (uint32_t i = 3; i < insn.len(); i++) {
1118 worklist.insert(insn.word(i)); // fn itself, and all args
1119 }
1120 break;
1121
1122 case spv::OpExtInst:
1123 for (uint32_t i = 5; i < insn.len(); i++) {
1124 worklist.insert(insn.word(i)); // Operands to ext inst
1125 }
1126 break;
1127 }
1128 }
1129 break;
1130 }
1131 }
1132
1133 return ids;
1134}
1135
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001136static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1137 std::vector<VkPushConstantRange> const *push_constant_ranges,
1138 shader_module const *src, spirv_inst_iter type, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001139 bool skip = false;
1140
1141 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001142 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001143 assert(type != src->end());
1144
1145 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1146 // TODO: arrays, matrices, weird sizes
1147 for (auto insn : *src) {
1148 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1149 if (insn.word(3) == spv::DecorationOffset) {
1150 unsigned offset = insn.word(4);
1151 auto size = 4; // Bytes; TODO: calculate this based on the type
1152
1153 bool found_range = false;
1154 for (auto const &range : *push_constant_ranges) {
1155 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1156 found_range = true;
1157
1158 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001159 skip |=
1160 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001161 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001162 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1163 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001164 }
1165
1166 break;
1167 }
1168 }
1169
1170 if (!found_range) {
1171 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001172 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001173 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001174 }
1175 }
1176 }
1177 }
1178
1179 return skip;
1180}
1181
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001182static bool ValidatePushConstantUsage(debug_report_data const *report_data,
1183 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1184 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001185 bool skip = false;
1186
1187 for (auto id : accessible_ids) {
1188 auto def_insn = src->get_def(id);
1189 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001190 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1191 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001192 }
1193 }
1194
1195 return skip;
1196}
1197
1198// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001199static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001200 bool skip = false;
1201
1202 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1203
1204 if (spec) {
1205 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001206 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001207 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001208 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06001209 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001210 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001211 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001212 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001213 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001214 }
1215 }
1216 }
1217
1218 return skip;
1219}
1220
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001221// TODO (jbolz): Can this return a const reference?
Jeff Bolze54ae892018-09-08 12:16:29 -05001222static std::set<uint32_t> TypeToDescriptorTypeSet(shader_module const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001223 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001224 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001225 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001226 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001227
1228 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
Jeff Bolzfdf96072018-04-10 14:32:18 -05001229 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1230 if (type.opcode() == spv::OpTypeRuntimeArray) {
1231 descriptor_count = 0;
1232 type = module->get_def(type.word(2));
1233 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001234 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001235 type = module->get_def(type.word(2));
1236 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001237 if (type.word(2) == spv::StorageClassStorageBuffer) {
1238 is_storage_buffer = true;
1239 }
Chris Forbes47567b72017-06-09 12:09:45 -07001240 type = module->get_def(type.word(3));
1241 }
1242 }
1243
1244 switch (type.opcode()) {
1245 case spv::OpTypeStruct: {
1246 for (auto insn : *module) {
1247 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1248 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001249 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001250 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1251 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1252 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001253 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001254 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1255 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1256 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1257 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001258 }
Chris Forbes47567b72017-06-09 12:09:45 -07001259 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001260 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1261 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1262 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001263 }
1264 }
1265 }
1266
1267 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001268 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001269 }
1270
1271 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001272 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1273 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1274 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001275
Chris Forbes73c00bf2018-06-22 16:28:06 -07001276 case spv::OpTypeSampledImage: {
1277 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1278 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1279 auto image_type = module->get_def(type.word(2));
1280 auto dim = image_type.word(3);
1281 auto sampled = image_type.word(7);
1282 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001283 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1284 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001285 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001286 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001287 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1288 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001289
1290 case spv::OpTypeImage: {
1291 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1292 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1293 auto dim = type.word(3);
1294 auto sampled = type.word(7);
1295
1296 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001297 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1298 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001299 } else if (dim == spv::DimBuffer) {
1300 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001301 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1302 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001303 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001304 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1305 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001306 }
1307 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001308 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1309 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1310 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001311 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001312 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1313 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001314 }
1315 }
Jeff Bolz105d6492018-09-29 15:46:44 -05001316 case spv::OpTypeAccelerationStructureNVX:
1317 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NVX);
1318 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001319
1320 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1321 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001322 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001323 }
1324}
1325
Jeff Bolze54ae892018-09-08 12:16:29 -05001326static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001327 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001328 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1329 if (ss.tellp()) ss << ", ";
1330 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001331 }
1332 return ss.str();
1333}
1334
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001335static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001336 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001337 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001338 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001339 return true;
1340 }
1341 }
1342
1343 return false;
1344}
1345
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001346static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001347 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001348 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001349 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001350 extension_name)) {
1351 return true;
1352 }
1353 }
1354
1355 return false;
1356}
1357
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001358static bool ValidateShaderCapabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1359 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001360 bool skip = false;
1361
1362 auto report_data = GetReportData(dev_data);
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001363 auto const &features = GetEnabledFeatures(dev_data);
Cort Strattond2742852018-05-03 13:42:10 -04001364 auto const &extensions = GetDeviceExtensions(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001365
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001366 struct FeaturePointer {
1367 // Callable object to test if this feature is enabled in the given aggregate feature struct
1368 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1369
1370 // Test if feature pointer is populated
1371 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1372
1373 // Default and nullptr constructor to create an empty FeaturePointer
1374 FeaturePointer() : IsEnabled(nullptr) {}
1375 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1376
1377 // Constructors to populate FeaturePointer based on given pointer to member
1378 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1379 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1380 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1381 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1382 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1383 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
1384 };
1385
Chris Forbes47567b72017-06-09 12:09:45 -07001386 struct CapabilityInfo {
1387 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001388 FeaturePointer feature;
1389 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001390 };
1391
Chris Forbes47567b72017-06-09 12:09:45 -07001392 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001393 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001394 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1395 // feature bits.
1396 {spv::CapabilityMatrix, {nullptr}},
1397 {spv::CapabilityShader, {nullptr}},
1398 {spv::CapabilityInputAttachment, {nullptr}},
1399 {spv::CapabilitySampled1D, {nullptr}},
1400 {spv::CapabilityImage1D, {nullptr}},
1401 {spv::CapabilitySampledBuffer, {nullptr}},
1402 {spv::CapabilityImageQuery, {nullptr}},
1403 {spv::CapabilityDerivativeControl, {nullptr}},
1404
1405 // Capabilities that are optionally supported, but require a feature to
1406 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001407 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1408 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1409 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1410 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1411 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1412 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1413 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1414 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1415 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1416 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1417 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1418 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1419 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1420 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1421 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1422 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1423 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1424 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1425 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1426 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1427 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats}},
1428 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1429 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1430 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1431 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001432
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001433 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1434 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1435 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1436 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1437 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1438 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1439 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1440 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1441 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1442 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1443 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
1444 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001445
1446 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001447 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1448 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1449 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1450 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1451 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1452 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1453 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1454 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001455
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001456 {spv::CapabilityStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1457 {spv::CapabilityUniformAndStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1458 {spv::CapabilityStoragePushConstant8 , {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Chris Forbes47567b72017-06-09 12:09:45 -07001459 };
1460 // clang-format on
1461
1462 for (auto insn : *src) {
1463 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001464 size_t n = capabilities.count(insn.word(1));
1465 if (1 == n) { // key occurs exactly once
1466 auto it = capabilities.find(insn.word(1));
1467 if (it != capabilities.end()) {
1468 if (it->second.feature) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001469 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(*features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001470 }
1471 if (it->second.extension) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001472 skip |= RequireExtension(report_data, extensions->*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001473 }
Chris Forbes47567b72017-06-09 12:09:45 -07001474 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001475 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1476 bool needs_feature = false, has_feature = false;
1477 bool needs_ext = false, has_ext = false;
1478 std::string feature_names = "(one of) [ ";
1479 std::string extension_names = feature_names;
1480 auto caps = capabilities.equal_range(insn.word(1));
1481 for (auto it = caps.first; it != caps.second; ++it) {
1482 if (it->second.feature) {
1483 needs_feature = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001484 has_feature = has_feature || it->second.feature.IsEnabled(*features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001485 feature_names += it->second.name;
1486 feature_names += " ";
1487 }
1488 if (it->second.extension) {
1489 needs_ext = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001490 has_ext = has_ext || extensions->*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001491 extension_names += it->second.name;
1492 extension_names += " ";
1493 }
1494 }
1495 if (needs_feature) {
1496 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001497 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001498 }
1499 if (needs_ext) {
1500 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001501 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001502 }
1503 }
1504 }
1505 }
1506
Chris Forbes349b3132018-03-07 11:38:08 -08001507 if (has_writable_descriptor) {
1508 switch (stage) {
1509 case VK_SHADER_STAGE_COMPUTE_BIT:
1510 /* No feature requirements for writes and atomics from compute
1511 * stage */
1512 break;
1513 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001514 skip |= RequireFeature(report_data, features->core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001515 break;
1516 default:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001517 skip |=
1518 RequireFeature(report_data, features->core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001519 break;
1520 }
1521 }
1522
Chris Forbes47567b72017-06-09 12:09:45 -07001523 return skip;
1524}
1525
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001526static uint32_t DescriptorTypeToReqs(shader_module const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07001527 auto type = module->get_def(type_id);
1528
1529 while (true) {
1530 switch (type.opcode()) {
1531 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07001532 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07001533 case spv::OpTypeSampledImage:
1534 type = module->get_def(type.word(2));
1535 break;
1536 case spv::OpTypePointer:
1537 type = module->get_def(type.word(3));
1538 break;
1539 case spv::OpTypeImage: {
1540 auto dim = type.word(3);
1541 auto arrayed = type.word(5);
1542 auto msaa = type.word(6);
1543
Chris Forbes74ba2232018-08-27 15:19:27 -07001544 uint32_t bits = 0;
1545 switch (GetFundamentalType(module, type.word(2))) {
1546 case FORMAT_TYPE_FLOAT:
1547 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
1548 break;
1549 case FORMAT_TYPE_UINT:
1550 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
1551 break;
1552 case FORMAT_TYPE_SINT:
1553 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
1554 break;
1555 default:
1556 break;
1557 }
1558
Chris Forbes47567b72017-06-09 12:09:45 -07001559 switch (dim) {
1560 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001561 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1562 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001563 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001564 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1565 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
1566 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001567 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001568 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
1569 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001570 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07001571 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1572 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001573 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07001574 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1575 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001576 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07001577 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001578 }
1579 }
1580 default:
1581 return 0;
1582 }
1583 }
1584}
1585
1586// For given pipelineLayout verify that the set_layout_node at slot.first
1587// has the requested binding at slot.second and return ptr to that binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001588static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1589 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07001590 if (!pipelineLayout) return nullptr;
1591
1592 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1593
1594 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1595}
1596
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001597static void ProcessExecutionModes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05001598 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07001599 bool is_point_mode = false;
1600
1601 for (auto insn : *src) {
1602 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
1603 switch (insn.word(2)) {
1604 case spv::ExecutionModePointMode:
1605 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
1606 is_point_mode = true;
1607 break;
1608
1609 case spv::ExecutionModeOutputPoints:
1610 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1611 break;
1612
1613 case spv::ExecutionModeIsolines:
1614 case spv::ExecutionModeOutputLineStrip:
1615 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
1616 break;
1617
1618 case spv::ExecutionModeTriangles:
1619 case spv::ExecutionModeQuads:
1620 case spv::ExecutionModeOutputTriangleStrip:
1621 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
1622 break;
1623 }
1624 }
1625 }
1626
1627 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1628}
1629
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001630// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
1631// o If there is only a vertex shader : gl_PointSize must be written when using points
1632// o If there is a geometry or tessellation shader:
1633// - If shaderTessellationAndGeometryPointSize feature is enabled:
1634// * gl_PointSize must be written in the final geometry stage
1635// - If shaderTessellationAndGeometryPointSize feature is disabled:
1636// * gl_PointSize must NOT be written and a default of 1.0 is assumed
1637bool ValidatePointListShaderState(const layer_data *dev_data, const PIPELINE_STATE *pipeline, shader_module const *src,
1638 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) {
1639 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1640 return false;
1641 }
1642
1643 bool pointsize_written = false;
1644 bool skip = false;
1645
1646 // Search for PointSize built-in decorations
1647 std::vector<uint32_t> pointsize_builtin_offsets;
1648 spirv_inst_iter insn = entrypoint;
1649 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
1650 if (insn.opcode() == spv::OpMemberDecorate) {
1651 if (insn.word(3) == spv::DecorationBuiltIn) {
1652 if (insn.word(4) == spv::BuiltInPointSize) {
1653 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1654 }
1655 }
1656 } else if (insn.opcode() == spv::OpDecorate) {
1657 if (insn.word(2) == spv::DecorationBuiltIn) {
1658 if (insn.word(3) == spv::BuiltInPointSize) {
1659 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1660 }
1661 }
1662 }
1663
1664 insn++;
1665 }
1666
1667 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
1668 !GetEnabledFeatures(dev_data)->core.shaderTessellationAndGeometryPointSize) {
1669 if (pointsize_written) {
1670 skip |= log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1671 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
1672 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
1673 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
1674 }
1675 } else if (!pointsize_written) {
1676 skip |=
1677 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1678 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
1679 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
1680 string_VkShaderStageFlagBits(stage));
1681 }
1682 return skip;
1683}
1684
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001685static bool ValidatePipelineShaderStage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001686 PIPELINE_STATE *pipeline, shader_module const **out_module, spirv_inst_iter *out_entrypoint,
1687 bool check_point_size) {
Chris Forbes47567b72017-06-09 12:09:45 -07001688 bool skip = false;
1689 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1690 auto report_data = GetReportData(dev_data);
1691
1692 if (!module->has_valid_spirv) return false;
1693
1694 // Find the entrypoint
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001695 auto entrypoint = *out_entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001696 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001697 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton78d09922018-05-17 15:48:45 -06001698 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
1699 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001700 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1701 }
1702 }
1703
Chris Forbes47567b72017-06-09 12:09:45 -07001704 // Mark accessible ids
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001705 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
1706 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07001707
1708 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08001709 bool has_writable_descriptor = false;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001710 auto descriptor_uses = CollectInterfaceByDescriptorSlot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07001711
Chris Forbes349b3132018-03-07 11:38:08 -08001712 // Validate shader capabilities against enabled device features
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001713 skip |= ValidateShaderCapabilities(dev_data, module, pStage->stage, has_writable_descriptor);
Chris Forbes349b3132018-03-07 11:38:08 -08001714
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001715 skip |= ValidateSpecializationOffsets(report_data, pStage);
1716 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
1717 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05001718 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001719 skip |= ValidatePointListShaderState(dev_data, pipeline, module, entrypoint, pStage->stage);
1720 }
Chris Forbes47567b72017-06-09 12:09:45 -07001721
1722 // Validate descriptor use
1723 for (auto use : descriptor_uses) {
1724 // While validating shaders capture which slots are used by the pipeline
1725 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001726 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
Chris Forbes47567b72017-06-09 12:09:45 -07001727
1728 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001729 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001730 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05001731 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07001732
1733 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001734 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001735 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001736 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05001737 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001738 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001739 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001740 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001741 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
1742 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05001743 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001744 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001745 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001746 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05001747 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001748 string_VkDescriptorType(binding->descriptorType));
1749 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001750 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001751 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001752 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
1753 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07001754 }
1755 }
1756
1757 // Validate use of input attachments against subpass structure
1758 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001759 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07001760
Petr Krause91f7a12017-12-14 20:57:36 +01001761 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001762 auto subpass = pipeline->graphicsPipelineCI.subpass;
1763
1764 for (auto use : input_attachment_uses) {
1765 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1766 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001767 ? input_attachments[use.first].attachment
1768 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001769
1770 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001771 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001772 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07001773 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001774 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001775 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001776 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
Dave Houlton51653902018-06-22 17:32:13 -06001777 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001778 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001779 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001780 }
1781 }
1782 }
1783
1784 return skip;
1785}
1786
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001787static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, shader_module const *producer,
1788 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1789 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1790 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001791 bool skip = false;
1792
1793 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001794 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1795 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07001796
1797 auto a_it = outputs.begin();
1798 auto b_it = inputs.begin();
1799
1800 // Maps sorted by key (location); walk them together to find mismatches
1801 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1802 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1803 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1804 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1805 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1806
1807 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06001808 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001809 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06001810 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1811 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001812 a_it++;
1813 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06001814 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001815 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06001816 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
1817 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001818 b_it++;
1819 } else {
1820 // subtleties of arrayed interfaces:
1821 // - if is_patch, then the member is not arrayed, even though the interface may be.
1822 // - if is_block_member, then the extra array level of an arrayed interface is not
1823 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001824 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1825 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1826 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06001827 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001828 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06001829 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001830 DescribeType(producer, a_it->second.type_id).c_str(),
1831 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001832 }
1833 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06001834 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001835 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001836 "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 -07001837 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1838 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1839 }
1840 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06001841 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06001842 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001843 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1844 a_first.second, producer_stage->name, consumer_stage->name);
1845 }
1846 a_it++;
1847 b_it++;
1848 }
1849 }
1850
1851 return skip;
1852}
1853
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001854static inline uint32_t DetermineFinalGeomStage(PIPELINE_STATE *pipeline, VkGraphicsPipelineCreateInfo *pCreateInfo) {
1855 uint32_t stage_mask = 0;
1856 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1857 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1858 stage_mask |= pCreateInfo->pStages[i].stage;
1859 }
1860 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05001861 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
1862 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
1863 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001864 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
1865 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
1866 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
1867 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
1868 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001869 }
1870 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001871 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001872}
1873
Chris Forbes47567b72017-06-09 12:09:45 -07001874// Validate that the shaders used by the given pipeline and store the active_slots
1875// that are actually used by the pipeline into pPipeline->active_slots
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001876bool ValidateAndCapturePipelineShaderState(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07001877 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001878 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
1879 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07001880 auto report_data = GetReportData(dev_data);
1881
Jeff Bolz7e35c392018-09-04 15:30:41 -05001882 shader_module const *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07001883 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05001884 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07001885 memset(entrypoints, 0, sizeof(entrypoints));
1886 bool skip = false;
1887
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001888 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
1889
Chris Forbes47567b72017-06-09 12:09:45 -07001890 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1891 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001892 auto stage_id = GetShaderStageId(pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001893 skip |= ValidatePipelineShaderStage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id],
1894 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001895 }
1896
1897 // if the shader stages are no good individually, cross-stage validation is pointless.
1898 if (skip) return true;
1899
1900 auto vi = pCreateInfo->pVertexInputState;
1901
1902 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001903 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07001904 }
1905
1906 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001907 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07001908 }
1909
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001910 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
1911 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07001912
1913 while (!shaders[producer] && producer != fragment_stage) {
1914 producer++;
1915 consumer++;
1916 }
1917
1918 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1919 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001920 if (shaders[consumer]) {
1921 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001922 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
1923 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1924 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001925 }
Chris Forbes47567b72017-06-09 12:09:45 -07001926
1927 producer = consumer;
1928 }
1929 }
1930
1931 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001932 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
1933 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07001934 }
1935
1936 return skip;
1937}
1938
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001939bool ValidateComputePipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07001940 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001941
1942 shader_module const *module;
1943 spirv_inst_iter entrypoint;
1944
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001945 return ValidatePipelineShaderStage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001946}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001947
Jeff Bolzfbe51582018-09-13 10:01:35 -05001948bool ValidateRaytracingPipelineNVX(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1949 auto pCreateInfo = pipeline->raytracingPipelineCI.ptr();
1950
1951 shader_module const *module;
1952 spirv_inst_iter entrypoint;
1953
1954 return ValidatePipelineShaderStage(dev_data, pCreateInfo->pStages, pipeline, &module, &entrypoint, false);
1955}
1956
Dave Houltona9df0ce2018-02-07 10:51:23 -07001957uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07001958
Dave Houltona9df0ce2018-02-07 10:51:23 -07001959static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07001960 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
1961 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
1962 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
1963 }
1964
1965 return nullptr;
1966}
1967
Chris Forbes4ae55b32017-06-09 14:42:56 -07001968bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1969 bool skip = false;
1970 spv_result_t spv_valid = SPV_SUCCESS;
1971 auto report_data = GetReportData(dev_data);
1972
1973 if (GetDisables(dev_data)->shader_validation) {
1974 return false;
1975 }
1976
Cort Strattond2742852018-05-03 13:42:10 -04001977 auto have_glsl_shader = GetDeviceExtensions(dev_data)->vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07001978
1979 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Dave Houlton78d09922018-05-17 15:48:45 -06001980 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1981 "VUID-VkShaderModuleCreateInfo-pCode-01376",
1982 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
1983 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07001984 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07001985 auto cache = GetValidationCacheInfo(pCreateInfo);
1986 uint32_t hash = 0;
1987 if (cache) {
1988 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001989 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07001990 }
1991
Chris Forbes4ae55b32017-06-09 14:42:56 -07001992 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06001993 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
1994 if (GetApiVersion(dev_data) >= VK_API_VERSION_1_1) {
1995 spirv_environment = SPV_ENV_VULKAN_1_1;
1996 }
1997 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001998 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07001999 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06002000 spv_validator_options options = spvValidatorOptionsCreate();
2001 if (GetDeviceExtensions(dev_data)->vk_khr_relaxed_block_layout) {
2002 spvValidatorOptionsSetRelaxBlockLayout(options, true);
2003 }
2004 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002005 if (spv_valid != SPV_SUCCESS) {
2006 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07002007 skip |=
2008 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
Dave Houlton51653902018-06-22 17:32:13 -06002009 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002010 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07002011 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002012 } else {
2013 if (cache) {
2014 cache->Insert(hash);
2015 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002016 }
2017
Karl Schultzfda1b382018-08-08 18:56:11 -06002018 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002019 spvDiagnosticDestroy(diag);
2020 spvContextDestroy(ctx);
2021 }
2022
2023 *spirv_valid = (spv_valid == SPV_SUCCESS);
2024 return skip;
2025}