blob: 85edd86e0522beaa22e824bfc493771220e923d8 [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
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600691static bool IsWritableDescriptorType(shader_module const *module, uint32_t type_id) {
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) {
697 // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800698 type = module->get_def(type.word(2));
699 } else {
Chris Forbes928b2bd2018-03-14 09:28:35 -0700700 if (type.word(2) == spv::StorageClassStorageBuffer) {
701 return true;
702 }
Chris Forbes8af24522018-03-07 11:37:45 -0800703 type = module->get_def(type.word(3));
704 }
705 }
706
707 switch (type.opcode()) {
708 case spv::OpTypeImage: {
709 auto dim = type.word(3);
710 auto sampled = type.word(7);
711 return sampled == 2 && dim != spv::DimSubpassData;
712 }
713
714 case spv::OpTypeStruct:
715 for (auto insn : *module) {
716 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
717 if (insn.word(2) == spv::DecorationBufferBlock) {
718 return true;
719 }
720 }
721 }
722 }
723
724 return false;
725}
726
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600727static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Chris Forbes8af24522018-03-07 11:37:45 -0800728 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
729 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700730 std::unordered_map<unsigned, unsigned> var_sets;
731 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800732 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700733
734 for (auto insn : *src) {
735 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
736 // DecorationDescriptorSet and DecorationBinding.
737 if (insn.opcode() == spv::OpDecorate) {
738 if (insn.word(2) == spv::DecorationDescriptorSet) {
739 var_sets[insn.word(1)] = insn.word(3);
740 }
741
742 if (insn.word(2) == spv::DecorationBinding) {
743 var_bindings[insn.word(1)] = insn.word(3);
744 }
Chris Forbes8af24522018-03-07 11:37:45 -0800745
746 if (insn.word(2) == spv::DecorationNonWritable) {
747 var_nonwritable[insn.word(1)] = 1;
748 }
Chris Forbes47567b72017-06-09 12:09:45 -0700749 }
750 }
751
752 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
753
754 for (auto id : accessible_ids) {
755 auto insn = src->get_def(id);
756 assert(insn != src->end());
757
758 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800759 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
760 insn.word(3) == spv::StorageClassStorageBuffer)) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600761 unsigned set = ValueOrDefault(var_sets, insn.word(2), 0);
762 unsigned binding = ValueOrDefault(var_bindings, insn.word(2), 0);
Chris Forbes47567b72017-06-09 12:09:45 -0700763
764 interface_var v = {};
765 v.id = insn.word(2);
766 v.type_id = insn.word(1);
767 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800768
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600769 if (var_nonwritable.find(id) == var_nonwritable.end() && IsWritableDescriptorType(src, insn.word(1))) {
Chris Forbes8af24522018-03-07 11:37:45 -0800770 *has_writable_descriptor = true;
771 }
Chris Forbes47567b72017-06-09 12:09:45 -0700772 }
773 }
774
775 return out;
776}
777
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600778static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700779 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
780 // be specified only once.
781 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
782 bool skip = false;
783
784 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
785 auto desc = &vi->pVertexBindingDescriptions[i];
786 auto &binding = bindings[desc->binding];
787 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600788 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600789 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 -0600790 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700791 desc->binding);
792 } else {
793 binding = desc;
794 }
795 }
796
797 return skip;
798}
799
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600800static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
801 shader_module const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700802 bool skip = false;
803
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600804 auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700805
806 // Build index by location
807 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
808 if (vi) {
809 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600810 auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
Chris Forbes47567b72017-06-09 12:09:45 -0700811 for (auto j = 0u; j < num_locations; j++) {
812 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
813 }
814 }
815 }
816
817 auto it_a = attribs.begin();
818 auto it_b = inputs.begin();
819 bool used = false;
820
821 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
822 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
823 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
824 auto a_first = a_at_end ? 0 : it_a->first;
825 auto b_first = b_at_end ? 0 : it_b->first.first;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600826
Chris Forbes47567b72017-06-09 12:09:45 -0700827 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600828 if (!used &&
829 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 -0600830 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600831 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700832 skip = true;
833 }
834 used = false;
835 it_a++;
836 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600837 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 -0600838 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600839 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700840 it_b++;
841 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600842 unsigned attrib_type = GetFormatType(it_a->second->format);
843 unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700844
845 // Type checking
846 if (!(attrib_type & input_type)) {
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_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700849 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600850 string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700851 }
852
853 // OK!
854 used = true;
855 it_b++;
856 }
857 }
858
859 return skip;
860}
861
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600862static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, shader_module const *fs,
863 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100864 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700865
Chris Forbes47567b72017-06-09 12:09:45 -0700866 std::map<uint32_t, VkFormat> color_attachments;
867 auto subpass = rpci->pSubpasses[subpass_index];
868 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
869 uint32_t attachment = subpass.pColorAttachments[i].attachment;
870 if (attachment == VK_ATTACHMENT_UNUSED) continue;
871 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
872 color_attachments[i] = rpci->pAttachments[attachment].format;
873 }
874 }
875
876 bool skip = false;
877
878 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
879
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600880 auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700881
882 auto it_a = outputs.begin();
883 auto it_b = color_attachments.begin();
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600884 bool used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700885
886 // Walk attachment list and outputs together
887
888 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
889 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
890 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
891
892 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600893 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 -0600894 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Chris Forbes47567b72017-06-09 12:09:45 -0700895 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
896 it_a++;
897 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700898 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
899 // shader to not produce a matching output.
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600900 if (!used) {
901 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
902 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
903 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
904 "Attachment %d not written by fragment shader", it_b->first);
905 }
Chris Forbesefdd4082017-07-20 11:19:16 -0700906 }
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600907 used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700908 it_b++;
909 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600910 unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
911 unsigned att_type = GetFormatType(it_b->second);
Chris Forbes47567b72017-06-09 12:09:45 -0700912
913 // Type checking
914 if (!(output_type & att_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600915 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 -0600916 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700917 "Attachment %d of type `%s` does not match fragment shader output type of `%s`", it_b->first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600918 string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700919 }
920
921 // OK!
922 it_a++;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600923 used = true;
Chris Forbes47567b72017-06-09 12:09:45 -0700924 }
925 }
926
927 return skip;
928}
929
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600930// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
931// This function examines instructions in the static call tree for a write to this variable.
932static bool IsPointSizeWritten(shader_module const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
933 auto type = builtin_instr.opcode();
934 uint32_t target_id = builtin_instr.word(1);
935 bool init_complete = false;
936
937 if (type == spv::OpMemberDecorate) {
938 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
939 auto insn = entrypoint;
940 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
941 switch (insn.opcode()) {
942 case spv::OpTypePointer:
943 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
944 target_id = insn.word(1);
945 }
946 break;
947 case spv::OpVariable:
948 if (insn.word(1) == target_id) {
949 target_id = insn.word(2);
950 init_complete = true;
951 }
952 break;
953 }
954 insn++;
955 }
956 }
957
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -0600958 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
959
960 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -0600961 std::unordered_set<uint32_t> worklist;
962 worklist.insert(entrypoint.word(2));
963
964 // Follow instructions in call graph looking for writes to target
965 while (!worklist.empty() && !found_write) {
966 auto id_iter = worklist.begin();
967 auto id = *id_iter;
968 worklist.erase(id_iter);
969
970 auto insn = src->get_def(id);
971 if (insn == src->end()) {
972 continue;
973 }
974
975 if (insn.opcode() == spv::OpFunction) {
976 // Scan body of function looking for other function calls or items in our ID chain
977 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
978 switch (insn.opcode()) {
979 case spv::OpAccessChain:
980 if (insn.word(3) == target_id) {
981 if (type == spv::OpMemberDecorate) {
982 auto value = GetConstantValue(src, insn.word(4));
983 if (value == builtin_instr.word(2)) {
984 target_id = insn.word(2);
985 }
986 } else {
987 target_id = insn.word(2);
988 }
989 }
990 break;
991 case spv::OpStore:
992 if (insn.word(1) == target_id) {
993 found_write = true;
994 }
995 break;
996 case spv::OpFunctionCall:
997 worklist.insert(insn.word(3));
998 break;
999 }
1000 }
1001 }
1002 }
1003 return found_write;
1004}
1005
Chris Forbes47567b72017-06-09 12:09:45 -07001006// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1007// important for identifying the set of shader resources actually used by an entrypoint, for example.
1008// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1009// - NOT the shader input/output interfaces.
1010//
1011// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1012// converting parts of this to be generated from the machine-readable spec instead.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001013static std::unordered_set<uint32_t> MarkAccessibleIds(shader_module const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001014 std::unordered_set<uint32_t> ids;
1015 std::unordered_set<uint32_t> worklist;
1016 worklist.insert(entrypoint.word(2));
1017
1018 while (!worklist.empty()) {
1019 auto id_iter = worklist.begin();
1020 auto id = *id_iter;
1021 worklist.erase(id_iter);
1022
1023 auto insn = src->get_def(id);
1024 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001025 // 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 -07001026 // that we may not care about.
1027 continue;
1028 }
1029
1030 // Try to add to the output set
1031 if (!ids.insert(id).second) {
1032 continue; // If we already saw this id, we don't want to walk it again.
1033 }
1034
1035 switch (insn.opcode()) {
1036 case spv::OpFunction:
1037 // Scan whole body of the function, enlisting anything interesting
1038 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1039 switch (insn.opcode()) {
1040 case spv::OpLoad:
1041 case spv::OpAtomicLoad:
1042 case spv::OpAtomicExchange:
1043 case spv::OpAtomicCompareExchange:
1044 case spv::OpAtomicCompareExchangeWeak:
1045 case spv::OpAtomicIIncrement:
1046 case spv::OpAtomicIDecrement:
1047 case spv::OpAtomicIAdd:
1048 case spv::OpAtomicISub:
1049 case spv::OpAtomicSMin:
1050 case spv::OpAtomicUMin:
1051 case spv::OpAtomicSMax:
1052 case spv::OpAtomicUMax:
1053 case spv::OpAtomicAnd:
1054 case spv::OpAtomicOr:
1055 case spv::OpAtomicXor:
1056 worklist.insert(insn.word(3)); // ptr
1057 break;
1058 case spv::OpStore:
1059 case spv::OpAtomicStore:
1060 worklist.insert(insn.word(1)); // ptr
1061 break;
1062 case spv::OpAccessChain:
1063 case spv::OpInBoundsAccessChain:
1064 worklist.insert(insn.word(3)); // base ptr
1065 break;
1066 case spv::OpSampledImage:
1067 case spv::OpImageSampleImplicitLod:
1068 case spv::OpImageSampleExplicitLod:
1069 case spv::OpImageSampleDrefImplicitLod:
1070 case spv::OpImageSampleDrefExplicitLod:
1071 case spv::OpImageSampleProjImplicitLod:
1072 case spv::OpImageSampleProjExplicitLod:
1073 case spv::OpImageSampleProjDrefImplicitLod:
1074 case spv::OpImageSampleProjDrefExplicitLod:
1075 case spv::OpImageFetch:
1076 case spv::OpImageGather:
1077 case spv::OpImageDrefGather:
1078 case spv::OpImageRead:
1079 case spv::OpImage:
1080 case spv::OpImageQueryFormat:
1081 case spv::OpImageQueryOrder:
1082 case spv::OpImageQuerySizeLod:
1083 case spv::OpImageQuerySize:
1084 case spv::OpImageQueryLod:
1085 case spv::OpImageQueryLevels:
1086 case spv::OpImageQuerySamples:
1087 case spv::OpImageSparseSampleImplicitLod:
1088 case spv::OpImageSparseSampleExplicitLod:
1089 case spv::OpImageSparseSampleDrefImplicitLod:
1090 case spv::OpImageSparseSampleDrefExplicitLod:
1091 case spv::OpImageSparseSampleProjImplicitLod:
1092 case spv::OpImageSparseSampleProjExplicitLod:
1093 case spv::OpImageSparseSampleProjDrefImplicitLod:
1094 case spv::OpImageSparseSampleProjDrefExplicitLod:
1095 case spv::OpImageSparseFetch:
1096 case spv::OpImageSparseGather:
1097 case spv::OpImageSparseDrefGather:
1098 case spv::OpImageTexelPointer:
1099 worklist.insert(insn.word(3)); // Image or sampled image
1100 break;
1101 case spv::OpImageWrite:
1102 worklist.insert(insn.word(1)); // Image -- different operand order to above
1103 break;
1104 case spv::OpFunctionCall:
1105 for (uint32_t i = 3; i < insn.len(); i++) {
1106 worklist.insert(insn.word(i)); // fn itself, and all args
1107 }
1108 break;
1109
1110 case spv::OpExtInst:
1111 for (uint32_t i = 5; i < insn.len(); i++) {
1112 worklist.insert(insn.word(i)); // Operands to ext inst
1113 }
1114 break;
1115 }
1116 }
1117 break;
1118 }
1119 }
1120
1121 return ids;
1122}
1123
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001124static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1125 std::vector<VkPushConstantRange> const *push_constant_ranges,
1126 shader_module const *src, spirv_inst_iter type, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001127 bool skip = false;
1128
1129 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001130 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001131 assert(type != src->end());
1132
1133 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1134 // TODO: arrays, matrices, weird sizes
1135 for (auto insn : *src) {
1136 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1137 if (insn.word(3) == spv::DecorationOffset) {
1138 unsigned offset = insn.word(4);
1139 auto size = 4; // Bytes; TODO: calculate this based on the type
1140
1141 bool found_range = false;
1142 for (auto const &range : *push_constant_ranges) {
1143 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1144 found_range = true;
1145
1146 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001147 skip |=
1148 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 -06001149 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001150 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1151 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001152 }
1153
1154 break;
1155 }
1156 }
1157
1158 if (!found_range) {
1159 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 -06001160 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001161 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001162 }
1163 }
1164 }
1165 }
1166
1167 return skip;
1168}
1169
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001170static bool ValidatePushConstantUsage(debug_report_data const *report_data,
1171 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1172 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001173 bool skip = false;
1174
1175 for (auto id : accessible_ids) {
1176 auto def_insn = src->get_def(id);
1177 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001178 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1179 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001180 }
1181 }
1182
1183 return skip;
1184}
1185
1186// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001187static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001188 bool skip = false;
1189
1190 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1191
1192 if (spec) {
1193 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001194 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001195 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001196 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 -06001197 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001198 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001199 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001200 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001201 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001202 }
1203 }
1204 }
1205
1206 return skip;
1207}
1208
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001209// TODO (jbolz): Can this return a const reference?
Jeff Bolze54ae892018-09-08 12:16:29 -05001210static std::set<uint32_t> TypeToDescriptorTypeSet(shader_module const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001211 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001212 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001213 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001214 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001215
1216 // 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 -05001217 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1218 if (type.opcode() == spv::OpTypeRuntimeArray) {
1219 descriptor_count = 0;
1220 type = module->get_def(type.word(2));
1221 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001222 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001223 type = module->get_def(type.word(2));
1224 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001225 if (type.word(2) == spv::StorageClassStorageBuffer) {
1226 is_storage_buffer = true;
1227 }
Chris Forbes47567b72017-06-09 12:09:45 -07001228 type = module->get_def(type.word(3));
1229 }
1230 }
1231
1232 switch (type.opcode()) {
1233 case spv::OpTypeStruct: {
1234 for (auto insn : *module) {
1235 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1236 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001237 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001238 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1239 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1240 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001241 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001242 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1243 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1244 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1245 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001246 }
Chris Forbes47567b72017-06-09 12:09:45 -07001247 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001248 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1249 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1250 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001251 }
1252 }
1253 }
1254
1255 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001256 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001257 }
1258
1259 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001260 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1261 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1262 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001263
Chris Forbes73c00bf2018-06-22 16:28:06 -07001264 case spv::OpTypeSampledImage: {
1265 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1266 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1267 auto image_type = module->get_def(type.word(2));
1268 auto dim = image_type.word(3);
1269 auto sampled = image_type.word(7);
1270 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001271 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1272 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001273 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001274 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001275 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1276 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001277
1278 case spv::OpTypeImage: {
1279 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1280 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1281 auto dim = type.word(3);
1282 auto sampled = type.word(7);
1283
1284 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001285 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1286 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001287 } else if (dim == spv::DimBuffer) {
1288 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001289 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1290 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001291 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001292 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1293 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001294 }
1295 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001296 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1297 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1298 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001299 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001300 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1301 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001302 }
1303 }
Jeff Bolz105d6492018-09-29 15:46:44 -05001304 case spv::OpTypeAccelerationStructureNVX:
1305 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NVX);
1306 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001307
1308 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1309 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001310 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001311 }
1312}
1313
Jeff Bolze54ae892018-09-08 12:16:29 -05001314static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001315 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001316 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1317 if (ss.tellp()) ss << ", ";
1318 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001319 }
1320 return ss.str();
1321}
1322
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001323static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001324 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001325 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 -06001326 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001327 return true;
1328 }
1329 }
1330
1331 return false;
1332}
1333
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001334static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001335 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001336 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 -06001337 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001338 extension_name)) {
1339 return true;
1340 }
1341 }
1342
1343 return false;
1344}
1345
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001346static bool ValidateShaderCapabilities(layer_data *dev_data, shader_module const *src, VkShaderStageFlagBits stage,
1347 bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001348 bool skip = false;
1349
1350 auto report_data = GetReportData(dev_data);
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001351 auto const &features = GetEnabledFeatures(dev_data);
Cort Strattond2742852018-05-03 13:42:10 -04001352 auto const &extensions = GetDeviceExtensions(dev_data);
Chris Forbes47567b72017-06-09 12:09:45 -07001353
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001354 struct FeaturePointer {
1355 // Callable object to test if this feature is enabled in the given aggregate feature struct
1356 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1357
1358 // Test if feature pointer is populated
1359 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1360
1361 // Default and nullptr constructor to create an empty FeaturePointer
1362 FeaturePointer() : IsEnabled(nullptr) {}
1363 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1364
1365 // Constructors to populate FeaturePointer based on given pointer to member
1366 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1367 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1368 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1369 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1370 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1371 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
1372 };
1373
Chris Forbes47567b72017-06-09 12:09:45 -07001374 struct CapabilityInfo {
1375 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001376 FeaturePointer feature;
1377 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001378 };
1379
Chris Forbes47567b72017-06-09 12:09:45 -07001380 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001381 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001382 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1383 // feature bits.
1384 {spv::CapabilityMatrix, {nullptr}},
1385 {spv::CapabilityShader, {nullptr}},
1386 {spv::CapabilityInputAttachment, {nullptr}},
1387 {spv::CapabilitySampled1D, {nullptr}},
1388 {spv::CapabilityImage1D, {nullptr}},
1389 {spv::CapabilitySampledBuffer, {nullptr}},
1390 {spv::CapabilityImageQuery, {nullptr}},
1391 {spv::CapabilityDerivativeControl, {nullptr}},
1392
1393 // Capabilities that are optionally supported, but require a feature to
1394 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001395 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1396 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1397 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1398 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1399 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1400 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1401 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1402 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1403 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1404 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1405 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1406 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1407 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1408 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1409 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1410 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1411 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1412 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1413 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1414 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1415 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats}},
1416 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1417 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1418 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1419 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001420
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001421 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1422 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1423 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1424 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1425 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1426 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1427 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1428 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1429 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1430 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1431 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
1432 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001433
1434 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001435 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1436 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1437 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1438 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1439 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1440 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1441 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1442 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001443
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001444 {spv::CapabilityStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1445 {spv::CapabilityUniformAndStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1446 {spv::CapabilityStoragePushConstant8 , {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Chris Forbes47567b72017-06-09 12:09:45 -07001447 };
1448 // clang-format on
1449
1450 for (auto insn : *src) {
1451 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001452 size_t n = capabilities.count(insn.word(1));
1453 if (1 == n) { // key occurs exactly once
1454 auto it = capabilities.find(insn.word(1));
1455 if (it != capabilities.end()) {
1456 if (it->second.feature) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001457 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(*features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001458 }
1459 if (it->second.extension) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001460 skip |= RequireExtension(report_data, extensions->*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001461 }
Chris Forbes47567b72017-06-09 12:09:45 -07001462 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001463 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1464 bool needs_feature = false, has_feature = false;
1465 bool needs_ext = false, has_ext = false;
1466 std::string feature_names = "(one of) [ ";
1467 std::string extension_names = feature_names;
1468 auto caps = capabilities.equal_range(insn.word(1));
1469 for (auto it = caps.first; it != caps.second; ++it) {
1470 if (it->second.feature) {
1471 needs_feature = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001472 has_feature = has_feature || it->second.feature.IsEnabled(*features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001473 feature_names += it->second.name;
1474 feature_names += " ";
1475 }
1476 if (it->second.extension) {
1477 needs_ext = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001478 has_ext = has_ext || extensions->*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001479 extension_names += it->second.name;
1480 extension_names += " ";
1481 }
1482 }
1483 if (needs_feature) {
1484 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001485 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001486 }
1487 if (needs_ext) {
1488 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001489 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001490 }
1491 }
1492 }
1493 }
1494
Chris Forbes349b3132018-03-07 11:38:08 -08001495 if (has_writable_descriptor) {
1496 switch (stage) {
1497 case VK_SHADER_STAGE_COMPUTE_BIT:
1498 /* No feature requirements for writes and atomics from compute
1499 * stage */
1500 break;
1501 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001502 skip |= RequireFeature(report_data, features->core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001503 break;
1504 default:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001505 skip |=
1506 RequireFeature(report_data, features->core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001507 break;
1508 }
1509 }
1510
Chris Forbes47567b72017-06-09 12:09:45 -07001511 return skip;
1512}
1513
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001514static uint32_t DescriptorTypeToReqs(shader_module const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07001515 auto type = module->get_def(type_id);
1516
1517 while (true) {
1518 switch (type.opcode()) {
1519 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07001520 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07001521 case spv::OpTypeSampledImage:
1522 type = module->get_def(type.word(2));
1523 break;
1524 case spv::OpTypePointer:
1525 type = module->get_def(type.word(3));
1526 break;
1527 case spv::OpTypeImage: {
1528 auto dim = type.word(3);
1529 auto arrayed = type.word(5);
1530 auto msaa = type.word(6);
1531
Chris Forbes74ba2232018-08-27 15:19:27 -07001532 uint32_t bits = 0;
1533 switch (GetFundamentalType(module, type.word(2))) {
1534 case FORMAT_TYPE_FLOAT:
1535 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
1536 break;
1537 case FORMAT_TYPE_UINT:
1538 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
1539 break;
1540 case FORMAT_TYPE_SINT:
1541 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
1542 break;
1543 default:
1544 break;
1545 }
1546
Chris Forbes47567b72017-06-09 12:09:45 -07001547 switch (dim) {
1548 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001549 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1550 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001551 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001552 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1553 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
1554 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001555 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07001556 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
1557 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001558 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07001559 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1560 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001561 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07001562 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1563 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001564 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07001565 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07001566 }
1567 }
1568 default:
1569 return 0;
1570 }
1571 }
1572}
1573
1574// For given pipelineLayout verify that the set_layout_node at slot.first
1575// has the requested binding at slot.second and return ptr to that binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001576static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
1577 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07001578 if (!pipelineLayout) return nullptr;
1579
1580 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1581
1582 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1583}
1584
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001585static void ProcessExecutionModes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05001586 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07001587 bool is_point_mode = false;
1588
1589 for (auto insn : *src) {
1590 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
1591 switch (insn.word(2)) {
1592 case spv::ExecutionModePointMode:
1593 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
1594 is_point_mode = true;
1595 break;
1596
1597 case spv::ExecutionModeOutputPoints:
1598 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1599 break;
1600
1601 case spv::ExecutionModeIsolines:
1602 case spv::ExecutionModeOutputLineStrip:
1603 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
1604 break;
1605
1606 case spv::ExecutionModeTriangles:
1607 case spv::ExecutionModeQuads:
1608 case spv::ExecutionModeOutputTriangleStrip:
1609 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
1610 break;
1611 }
1612 }
1613 }
1614
1615 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
1616}
1617
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001618// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
1619// o If there is only a vertex shader : gl_PointSize must be written when using points
1620// o If there is a geometry or tessellation shader:
1621// - If shaderTessellationAndGeometryPointSize feature is enabled:
1622// * gl_PointSize must be written in the final geometry stage
1623// - If shaderTessellationAndGeometryPointSize feature is disabled:
1624// * gl_PointSize must NOT be written and a default of 1.0 is assumed
1625bool ValidatePointListShaderState(const layer_data *dev_data, const PIPELINE_STATE *pipeline, shader_module const *src,
1626 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) {
1627 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1628 return false;
1629 }
1630
1631 bool pointsize_written = false;
1632 bool skip = false;
1633
1634 // Search for PointSize built-in decorations
1635 std::vector<uint32_t> pointsize_builtin_offsets;
1636 spirv_inst_iter insn = entrypoint;
1637 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
1638 if (insn.opcode() == spv::OpMemberDecorate) {
1639 if (insn.word(3) == spv::DecorationBuiltIn) {
1640 if (insn.word(4) == spv::BuiltInPointSize) {
1641 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1642 }
1643 }
1644 } else if (insn.opcode() == spv::OpDecorate) {
1645 if (insn.word(2) == spv::DecorationBuiltIn) {
1646 if (insn.word(3) == spv::BuiltInPointSize) {
1647 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
1648 }
1649 }
1650 }
1651
1652 insn++;
1653 }
1654
1655 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
1656 !GetEnabledFeatures(dev_data)->core.shaderTessellationAndGeometryPointSize) {
1657 if (pointsize_written) {
1658 skip |= log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1659 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
1660 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
1661 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
1662 }
1663 } else if (!pointsize_written) {
1664 skip |=
1665 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1666 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
1667 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
1668 string_VkShaderStageFlagBits(stage));
1669 }
1670 return skip;
1671}
1672
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001673static bool ValidatePipelineShaderStage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001674 PIPELINE_STATE *pipeline, shader_module const **out_module, spirv_inst_iter *out_entrypoint,
1675 bool check_point_size) {
Chris Forbes47567b72017-06-09 12:09:45 -07001676 bool skip = false;
1677 auto module = *out_module = GetShaderModuleState(dev_data, pStage->module);
1678 auto report_data = GetReportData(dev_data);
1679
1680 if (!module->has_valid_spirv) return false;
1681
1682 // Find the entrypoint
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001683 auto entrypoint = *out_entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001684 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001685 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 -06001686 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
1687 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001688 return true; // no point continuing beyond here, any analysis is just going to be garbage.
1689 }
1690 }
1691
Chris Forbes47567b72017-06-09 12:09:45 -07001692 // Mark accessible ids
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001693 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
1694 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07001695
1696 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08001697 bool has_writable_descriptor = false;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001698 auto descriptor_uses = CollectInterfaceByDescriptorSlot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07001699
Chris Forbes349b3132018-03-07 11:38:08 -08001700 // Validate shader capabilities against enabled device features
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001701 skip |= ValidateShaderCapabilities(dev_data, module, pStage->stage, has_writable_descriptor);
Chris Forbes349b3132018-03-07 11:38:08 -08001702
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001703 skip |= ValidateSpecializationOffsets(report_data, pStage);
1704 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
1705 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05001706 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001707 skip |= ValidatePointListShaderState(dev_data, pipeline, module, entrypoint, pStage->stage);
1708 }
Chris Forbes47567b72017-06-09 12:09:45 -07001709
1710 // Validate descriptor use
1711 for (auto use : descriptor_uses) {
1712 // While validating shaders capture which slots are used by the pipeline
1713 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001714 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
Chris Forbes47567b72017-06-09 12:09:45 -07001715
1716 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001717 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001718 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05001719 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07001720
1721 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001722 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 -06001723 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001724 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05001725 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001726 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001727 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 -06001728 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001729 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
1730 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05001731 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001732 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 -06001733 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001734 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05001735 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07001736 string_VkDescriptorType(binding->descriptorType));
1737 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001738 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 -06001739 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07001740 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
1741 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07001742 }
1743 }
1744
1745 // Validate use of input attachments against subpass structure
1746 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001747 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07001748
Petr Krause91f7a12017-12-14 20:57:36 +01001749 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001750 auto subpass = pipeline->graphicsPipelineCI.subpass;
1751
1752 for (auto use : input_attachment_uses) {
1753 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1754 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001755 ? input_attachments[use.first].attachment
1756 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001757
1758 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001759 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 -06001760 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07001761 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001762 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001763 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001764 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 -06001765 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001766 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001767 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001768 }
1769 }
1770 }
1771
1772 return skip;
1773}
1774
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001775static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, shader_module const *producer,
1776 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1777 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1778 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001779 bool skip = false;
1780
1781 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001782 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1783 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07001784
1785 auto a_it = outputs.begin();
1786 auto b_it = inputs.begin();
1787
1788 // Maps sorted by key (location); walk them together to find mismatches
1789 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1790 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1791 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1792 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1793 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1794
1795 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06001796 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 -06001797 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06001798 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1799 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001800 a_it++;
1801 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06001802 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 -06001803 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06001804 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
1805 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001806 b_it++;
1807 } else {
1808 // subtleties of arrayed interfaces:
1809 // - if is_patch, then the member is not arrayed, even though the interface may be.
1810 // - if is_block_member, then the extra array level of an arrayed interface is not
1811 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001812 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1813 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1814 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06001815 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 -06001816 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06001817 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001818 DescribeType(producer, a_it->second.type_id).c_str(),
1819 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001820 }
1821 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06001822 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 -06001823 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001824 "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 -07001825 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1826 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
1827 }
1828 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06001829 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 -06001830 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07001831 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1832 a_first.second, producer_stage->name, consumer_stage->name);
1833 }
1834 a_it++;
1835 b_it++;
1836 }
1837 }
1838
1839 return skip;
1840}
1841
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001842static inline uint32_t DetermineFinalGeomStage(PIPELINE_STATE *pipeline, VkGraphicsPipelineCreateInfo *pCreateInfo) {
1843 uint32_t stage_mask = 0;
1844 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1845 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1846 stage_mask |= pCreateInfo->pStages[i].stage;
1847 }
1848 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05001849 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
1850 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
1851 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001852 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
1853 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
1854 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
1855 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
1856 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001857 }
1858 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001859 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001860}
1861
Chris Forbes47567b72017-06-09 12:09:45 -07001862// Validate that the shaders used by the given pipeline and store the active_slots
1863// that are actually used by the pipeline into pPipeline->active_slots
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001864bool ValidateAndCapturePipelineShaderState(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07001865 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001866 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
1867 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07001868 auto report_data = GetReportData(dev_data);
1869
Jeff Bolz7e35c392018-09-04 15:30:41 -05001870 shader_module const *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07001871 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05001872 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07001873 memset(entrypoints, 0, sizeof(entrypoints));
1874 bool skip = false;
1875
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001876 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
1877
Chris Forbes47567b72017-06-09 12:09:45 -07001878 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1879 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001880 auto stage_id = GetShaderStageId(pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001881 skip |= ValidatePipelineShaderStage(dev_data, pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id],
1882 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001883 }
1884
1885 // if the shader stages are no good individually, cross-stage validation is pointless.
1886 if (skip) return true;
1887
1888 auto vi = pCreateInfo->pVertexInputState;
1889
1890 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001891 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07001892 }
1893
1894 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001895 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07001896 }
1897
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001898 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
1899 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07001900
1901 while (!shaders[producer] && producer != fragment_stage) {
1902 producer++;
1903 consumer++;
1904 }
1905
1906 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
1907 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001908 if (shaders[consumer]) {
1909 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001910 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
1911 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
1912 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08001913 }
Chris Forbes47567b72017-06-09 12:09:45 -07001914
1915 producer = consumer;
1916 }
1917 }
1918
1919 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001920 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
1921 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07001922 }
1923
1924 return skip;
1925}
1926
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001927bool ValidateComputePipeline(layer_data *dev_data, PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07001928 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001929
1930 shader_module const *module;
1931 spirv_inst_iter entrypoint;
1932
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001933 return ValidatePipelineShaderStage(dev_data, &pCreateInfo->stage, pipeline, &module, &entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001934}
Chris Forbes4ae55b32017-06-09 14:42:56 -07001935
Jeff Bolzfbe51582018-09-13 10:01:35 -05001936bool ValidateRaytracingPipelineNVX(layer_data *dev_data, PIPELINE_STATE *pipeline) {
1937 auto pCreateInfo = pipeline->raytracingPipelineCI.ptr();
1938
1939 shader_module const *module;
1940 spirv_inst_iter entrypoint;
1941
1942 return ValidatePipelineShaderStage(dev_data, pCreateInfo->pStages, pipeline, &module, &entrypoint, false);
1943}
1944
Dave Houltona9df0ce2018-02-07 10:51:23 -07001945uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07001946
Dave Houltona9df0ce2018-02-07 10:51:23 -07001947static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Chris Forbes9a61e082017-07-24 15:35:29 -07001948 while ((pCreateInfo = (VkShaderModuleCreateInfo const *)pCreateInfo->pNext) != nullptr) {
1949 if (pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT)
1950 return (ValidationCache *)((VkShaderModuleValidationCacheCreateInfoEXT const *)pCreateInfo)->validationCache;
1951 }
1952
1953 return nullptr;
1954}
1955
Chris Forbes4ae55b32017-06-09 14:42:56 -07001956bool PreCallValidateCreateShaderModule(layer_data *dev_data, VkShaderModuleCreateInfo const *pCreateInfo, bool *spirv_valid) {
1957 bool skip = false;
1958 spv_result_t spv_valid = SPV_SUCCESS;
1959 auto report_data = GetReportData(dev_data);
1960
1961 if (GetDisables(dev_data)->shader_validation) {
1962 return false;
1963 }
1964
Cort Strattond2742852018-05-03 13:42:10 -04001965 auto have_glsl_shader = GetDeviceExtensions(dev_data)->vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07001966
1967 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Dave Houlton78d09922018-05-17 15:48:45 -06001968 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1969 "VUID-VkShaderModuleCreateInfo-pCode-01376",
1970 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
1971 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07001972 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07001973 auto cache = GetValidationCacheInfo(pCreateInfo);
1974 uint32_t hash = 0;
1975 if (cache) {
1976 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001977 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07001978 }
1979
Chris Forbes4ae55b32017-06-09 14:42:56 -07001980 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06001981 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
1982 if (GetApiVersion(dev_data) >= VK_API_VERSION_1_1) {
1983 spirv_environment = SPV_ENV_VULKAN_1_1;
1984 }
1985 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07001986 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07001987 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06001988 spv_validator_options options = spvValidatorOptionsCreate();
1989 if (GetDeviceExtensions(dev_data)->vk_khr_relaxed_block_layout) {
1990 spvValidatorOptionsSetRelaxBlockLayout(options, true);
1991 }
1992 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07001993 if (spv_valid != SPV_SUCCESS) {
1994 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001995 skip |=
1996 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 -06001997 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001998 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07001999 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002000 } else {
2001 if (cache) {
2002 cache->Insert(hash);
2003 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002004 }
2005
Karl Schultzfda1b382018-08-08 18:56:11 -06002006 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002007 spvDiagnosticDestroy(diag);
2008 spvContextDestroy(ctx);
2009 }
2010
2011 *spirv_valid = (spv_valid == SPV_SUCCESS);
2012 return skip;
2013}