blob: 156f27681341f2b573b2f491687eec4bfc6de8c2 [file] [log] [blame]
Karl Schultz7b024b42018-08-30 16:18:18 -06001/* Copyright (c) 2015-2019 The Khronos Group Inc.
2 * Copyright (c) 2015-2019 Valve Corporation
3 * Copyright (c) 2015-2019 LunarG, Inc.
4 * Copyright (C) 2015-2019 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>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020024#include <chrono>
Chris Forbes47567b72017-06-09 12:09:45 -070025#include <vector>
26#include <unordered_map>
27#include <string>
28#include <sstream>
29#include <SPIRV/spirv.hpp>
30#include "vk_loader_platform.h"
31#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070032#include "vk_layer_data.h"
33#include "vk_layer_extension_utils.h"
34#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070035#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070036#include "core_validation.h"
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "shader_validation.h"
Chris Forbes4ae55b32017-06-09 14:42:56 -070038#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070039#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070040
41enum FORMAT_TYPE {
42 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
43 FORMAT_TYPE_SINT = 2,
44 FORMAT_TYPE_UINT = 4,
45};
46
47typedef std::pair<unsigned, unsigned> location_t;
48
49struct interface_var {
50 uint32_t id;
51 uint32_t type_id;
52 uint32_t offset;
53 bool is_patch;
54 bool is_block_member;
55 bool is_relaxed_precision;
56 // TODO: collect the name, too? Isn't required to be present.
57};
58
59struct shader_stage_attributes {
60 char const *const name;
61 bool arrayed_input;
62 bool arrayed_output;
63};
64
65static shader_stage_attributes shader_stage_attribs[] = {
66 {"vertex shader", false, false}, {"tessellation control shader", true, true}, {"tessellation evaluation shader", true, false},
67 {"geometry shader", true, false}, {"fragment shader", false, false},
68};
69
70// SPIRV utility functions
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060071void shader_module::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -070072 for (auto insn : *this) {
73 switch (insn.opcode()) {
74 // Types
75 case spv::OpTypeVoid:
76 case spv::OpTypeBool:
77 case spv::OpTypeInt:
78 case spv::OpTypeFloat:
79 case spv::OpTypeVector:
80 case spv::OpTypeMatrix:
81 case spv::OpTypeImage:
82 case spv::OpTypeSampler:
83 case spv::OpTypeSampledImage:
84 case spv::OpTypeArray:
85 case spv::OpTypeRuntimeArray:
86 case spv::OpTypeStruct:
87 case spv::OpTypeOpaque:
88 case spv::OpTypePointer:
89 case spv::OpTypeFunction:
90 case spv::OpTypeEvent:
91 case spv::OpTypeDeviceEvent:
92 case spv::OpTypeReserveId:
93 case spv::OpTypeQueue:
94 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -060095 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -060096 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -070097 def_index[insn.word(1)] = insn.offset();
98 break;
99
100 // Fixed constants
101 case spv::OpConstantTrue:
102 case spv::OpConstantFalse:
103 case spv::OpConstant:
104 case spv::OpConstantComposite:
105 case spv::OpConstantSampler:
106 case spv::OpConstantNull:
107 def_index[insn.word(2)] = insn.offset();
108 break;
109
110 // Specialization constants
111 case spv::OpSpecConstantTrue:
112 case spv::OpSpecConstantFalse:
113 case spv::OpSpecConstant:
114 case spv::OpSpecConstantComposite:
115 case spv::OpSpecConstantOp:
116 def_index[insn.word(2)] = insn.offset();
117 break;
118
119 // Variables
120 case spv::OpVariable:
121 def_index[insn.word(2)] = insn.offset();
122 break;
123
124 // Functions
125 case spv::OpFunction:
126 def_index[insn.word(2)] = insn.offset();
127 break;
128
129 default:
130 // We don't care about any other defs for now.
131 break;
132 }
133 }
134}
135
Jeff Bolz105d6492018-09-29 15:46:44 -0500136unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
137 switch (mode) {
138 case spv::ExecutionModelVertex:
139 return VK_SHADER_STAGE_VERTEX_BIT;
140 case spv::ExecutionModelTessellationControl:
141 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
142 case spv::ExecutionModelTessellationEvaluation:
143 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
144 case spv::ExecutionModelGeometry:
145 return VK_SHADER_STAGE_GEOMETRY_BIT;
146 case spv::ExecutionModelFragment:
147 return VK_SHADER_STAGE_FRAGMENT_BIT;
148 case spv::ExecutionModelGLCompute:
149 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600150 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700151 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600152 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700153 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600154 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700155 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600156 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700157 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600158 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700159 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600160 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700161 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500162 case spv::ExecutionModelTaskNV:
163 return VK_SHADER_STAGE_TASK_BIT_NV;
164 case spv::ExecutionModelMeshNV:
165 return VK_SHADER_STAGE_MESH_BIT_NV;
166 default:
167 return 0;
168 }
169}
170
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600171static spirv_inst_iter FindEntrypoint(shader_module const *src, char const *name, VkShaderStageFlagBits stageBits) {
Chris Forbes47567b72017-06-09 12:09:45 -0700172 for (auto insn : *src) {
173 if (insn.opcode() == spv::OpEntryPoint) {
174 auto entrypointName = (char const *)&insn.word(3);
Jeff Bolz105d6492018-09-29 15:46:44 -0500175 auto executionModel = insn.word(1);
176 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
Chris Forbes47567b72017-06-09 12:09:45 -0700177
178 if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
179 return insn;
180 }
181 }
182 }
183
184 return src->end();
185}
186
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600187static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700188 switch (sc) {
189 case spv::StorageClassInput:
190 return "input";
191 case spv::StorageClassOutput:
192 return "output";
193 case spv::StorageClassUniformConstant:
194 return "const uniform";
195 case spv::StorageClassUniform:
196 return "uniform";
197 case spv::StorageClassWorkgroup:
198 return "workgroup local";
199 case spv::StorageClassCrossWorkgroup:
200 return "workgroup global";
201 case spv::StorageClassPrivate:
202 return "private global";
203 case spv::StorageClassFunction:
204 return "function";
205 case spv::StorageClassGeneric:
206 return "generic";
207 case spv::StorageClassAtomicCounter:
208 return "atomic counter";
209 case spv::StorageClassImage:
210 return "image";
211 case spv::StorageClassPushConstant:
212 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800213 case spv::StorageClassStorageBuffer:
214 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700215 default:
216 return "unknown";
217 }
218}
219
220// Get the value of an integral constant
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600221unsigned GetConstantValue(shader_module const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700222 auto value = src->get_def(id);
223 assert(value != src->end());
224
225 if (value.opcode() != spv::OpConstant) {
226 // TODO: Either ensure that the specialization transform is already performed on a module we're
227 // considering here, OR -- specialize on the fly now.
228 return 1;
229 }
230
231 return value.word(3);
232}
233
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600234static void DescribeTypeInner(std::ostringstream &ss, shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700235 auto insn = src->get_def(type);
236 assert(insn != src->end());
237
238 switch (insn.opcode()) {
239 case spv::OpTypeBool:
240 ss << "bool";
241 break;
242 case spv::OpTypeInt:
243 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
244 break;
245 case spv::OpTypeFloat:
246 ss << "float" << insn.word(2);
247 break;
248 case spv::OpTypeVector:
249 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600250 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700251 break;
252 case spv::OpTypeMatrix:
253 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600254 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700255 break;
256 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600257 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
258 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700259 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700260 case spv::OpTypeRuntimeArray:
261 ss << "runtime arr[] of ";
262 DescribeTypeInner(ss, src, insn.word(2));
263 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700264 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600265 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
266 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700267 break;
268 case spv::OpTypeStruct: {
269 ss << "struct of (";
270 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600271 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700272 if (i == insn.len() - 1) {
273 ss << ")";
274 } else {
275 ss << ", ";
276 }
277 }
278 break;
279 }
280 case spv::OpTypeSampler:
281 ss << "sampler";
282 break;
283 case spv::OpTypeSampledImage:
284 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600285 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700286 break;
287 case spv::OpTypeImage:
288 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
289 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600290 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500291 ss << "accelerationStruture";
292 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700293 default:
294 ss << "oddtype";
295 break;
296 }
297}
298
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600299static std::string DescribeType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700300 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600301 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700302 return ss.str();
303}
304
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600305static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700306 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
307 return type.word(2) < 64;
308}
309
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600310static bool TypesMatch(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
311 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700312 // Walk two type trees together, and complain about differences
313 auto a_insn = a->get_def(a_type);
314 auto b_insn = b->get_def(b_type);
315 assert(a_insn != a->end());
316 assert(b_insn != b->end());
317
Chris Forbes062f1222018-08-21 15:34:15 -0700318 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
319
Chris Forbes47567b72017-06-09 12:09:45 -0700320 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600321 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700322 }
323
324 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
325 // 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 -0600326 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700327 }
328
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600329 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
330 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700331 }
332
333 if (a_insn.opcode() != b_insn.opcode()) {
334 return false;
335 }
336
337 if (a_insn.opcode() == spv::OpTypePointer) {
338 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600339 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700340 }
341
342 if (a_arrayed || b_arrayed) {
343 // If we havent resolved array-of-verts by here, we're not going to.
344 return false;
345 }
346
347 switch (a_insn.opcode()) {
348 case spv::OpTypeBool:
349 return true;
350 case spv::OpTypeInt:
351 // Match on width, signedness
352 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
353 case spv::OpTypeFloat:
354 // Match on width
355 return a_insn.word(2) == b_insn.word(2);
356 case spv::OpTypeVector:
357 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600358 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
359 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700360 return a_insn.word(3) >= b_insn.word(3);
361 } else {
362 return a_insn.word(3) == b_insn.word(3);
363 }
364 case spv::OpTypeMatrix:
365 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600366 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700367 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700368 case spv::OpTypeArray:
369 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
370 // 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 -0600371 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
372 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700373 case spv::OpTypeStruct:
374 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700375 {
376 if (a_insn.len() != b_insn.len()) {
377 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700378 }
Chris Forbes47567b72017-06-09 12:09:45 -0700379
Dave Houltona9df0ce2018-02-07 10:51:23 -0700380 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600381 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700382 return false;
383 }
384 }
385
386 return true;
387 }
Chris Forbes47567b72017-06-09 12:09:45 -0700388 default:
389 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
390 return false;
391 }
392}
393
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600394static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700395 auto it = map.find(id);
396 if (it == map.end())
397 return def;
398 else
399 return it->second;
400}
401
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600402static unsigned GetLocationsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700403 auto insn = src->get_def(type);
404 assert(insn != src->end());
405
406 switch (insn.opcode()) {
407 case spv::OpTypePointer:
408 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
409 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600410 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700411 case spv::OpTypeArray:
412 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600413 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700414 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600415 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700416 }
417 case spv::OpTypeMatrix:
418 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600419 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700420 case spv::OpTypeVector: {
421 auto scalar_type = src->get_def(insn.word(2));
422 auto bit_width =
423 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
424
425 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
426 return (bit_width * insn.word(3) + 127) / 128;
427 }
428 default:
429 // Everything else is just 1.
430 return 1;
431
432 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
433 }
434}
435
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200436static unsigned GetComponentsConsumedByType(shader_module const *src, unsigned type, bool strip_array_level) {
437 auto insn = src->get_def(type);
438 assert(insn != src->end());
439
440 switch (insn.opcode()) {
441 case spv::OpTypePointer:
442 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
443 // pointers around.
444 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
445 case spv::OpTypeStruct: {
446 uint32_t sum = 0;
447 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
448 sum += GetComponentsConsumedByType(src, insn.word(i), false);
449 }
450 return sum;
451 }
452 case spv::OpTypeArray: {
453 uint32_t sum = 0;
454 for (uint32_t i = 2; i < insn.len(); i++) {
455 sum += GetComponentsConsumedByType(src, insn.word(i), false);
456 }
457 return sum;
458 }
459 case spv::OpTypeMatrix:
460 // Num locations is the dimension * element size
461 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
462 case spv::OpTypeVector: {
463 auto scalar_type = src->get_def(insn.word(2));
464 auto bit_width =
465 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
466 // One component is 32-bit
467 return (bit_width * insn.word(3) + 31) / 32;
468 }
469 case spv::OpTypeFloat: {
470 auto bit_width = insn.word(2);
471 return (bit_width + 31) / 32;
472 }
473 case spv::OpTypeInt: {
474 auto bit_width = insn.word(2);
475 return (bit_width + 31) / 32;
476 }
477 case spv::OpConstant:
478 return GetComponentsConsumedByType(src, insn.word(1), false);
479 default:
480 return 0;
481 }
482}
483
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600484static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700485 switch (format) {
486 case VK_FORMAT_R64G64B64A64_SFLOAT:
487 case VK_FORMAT_R64G64B64A64_SINT:
488 case VK_FORMAT_R64G64B64A64_UINT:
489 case VK_FORMAT_R64G64B64_SFLOAT:
490 case VK_FORMAT_R64G64B64_SINT:
491 case VK_FORMAT_R64G64B64_UINT:
492 return 2;
493 default:
494 return 1;
495 }
496}
497
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600498static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700499 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
500 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
501 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
502 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700503 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
504 return FORMAT_TYPE_FLOAT;
505}
506
507// 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 -0700508// also used for input attachments, as we statically know their format.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600509static unsigned GetFundamentalType(shader_module const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700510 auto insn = src->get_def(type);
511 assert(insn != src->end());
512
513 switch (insn.opcode()) {
514 case spv::OpTypeInt:
515 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
516 case spv::OpTypeFloat:
517 return FORMAT_TYPE_FLOAT;
518 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700519 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700520 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700521 case spv::OpTypeRuntimeArray:
522 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600523 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700524 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600525 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700526
527 default:
528 return 0;
529 }
530}
531
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600532static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700533 uint32_t bit_pos = uint32_t(u_ffs(stage));
534 return bit_pos - 1;
535}
536
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600537static spirv_inst_iter GetStructType(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700538 while (true) {
539 if (def.opcode() == spv::OpTypePointer) {
540 def = src->get_def(def.word(3));
541 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
542 def = src->get_def(def.word(2));
543 is_array_of_verts = false;
544 } else if (def.opcode() == spv::OpTypeStruct) {
545 return def;
546 } else {
547 return src->end();
548 }
549 }
550}
551
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600552static bool CollectInterfaceBlockMembers(shader_module const *src, std::map<location_t, interface_var> *out,
553 std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts, uint32_t id,
554 uint32_t type_id, bool is_patch, int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700555 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600556 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700557 if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
558 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700559 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700560 }
561
562 std::unordered_map<unsigned, unsigned> member_components;
563 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700564 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700565
566 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
567 for (auto insn : *src) {
568 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
569 unsigned member_index = insn.word(2);
570
571 if (insn.word(3) == spv::DecorationComponent) {
572 unsigned component = insn.word(4);
573 member_components[member_index] = component;
574 }
575
576 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
577 member_relaxed_precision[member_index] = 1;
578 }
Chris Forbesa313d772017-06-13 13:59:41 -0700579
580 if (insn.word(3) == spv::DecorationPatch) {
581 member_patch[member_index] = 1;
582 }
Chris Forbes47567b72017-06-09 12:09:45 -0700583 }
584 }
585
Chris Forbesa313d772017-06-13 13:59:41 -0700586 // TODO: correctly handle location assignment from outside
587
Chris Forbes47567b72017-06-09 12:09:45 -0700588 // Second pass -- produce the output, from Location decorations
589 for (auto insn : *src) {
590 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
591 unsigned member_index = insn.word(2);
592 unsigned member_type_id = type.word(2 + member_index);
593
594 if (insn.word(3) == spv::DecorationLocation) {
595 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600596 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700597 auto component_it = member_components.find(member_index);
598 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
599 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700600 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700601
602 for (unsigned int offset = 0; offset < num_locations; offset++) {
603 interface_var v = {};
604 v.id = id;
605 // TODO: member index in interface_var too?
606 v.type_id = member_type_id;
607 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700608 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700609 v.is_block_member = true;
610 v.is_relaxed_precision = is_relaxed_precision;
611 (*out)[std::make_pair(location + offset, component)] = v;
612 }
613 }
614 }
615 }
Chris Forbesa313d772017-06-13 13:59:41 -0700616
617 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700618}
619
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600620static std::map<location_t, interface_var> CollectInterfaceByLocation(shader_module const *src, spirv_inst_iter entrypoint,
621 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700622 std::unordered_map<unsigned, unsigned> var_locations;
623 std::unordered_map<unsigned, unsigned> var_builtins;
624 std::unordered_map<unsigned, unsigned> var_components;
625 std::unordered_map<unsigned, unsigned> blocks;
626 std::unordered_map<unsigned, unsigned> var_patch;
627 std::unordered_map<unsigned, unsigned> var_relaxed_precision;
628
629 for (auto insn : *src) {
630 // We consider two interface models: SSO rendezvous-by-location, and builtins. Complain about anything that
631 // fits neither model.
632 if (insn.opcode() == spv::OpDecorate) {
633 if (insn.word(2) == spv::DecorationLocation) {
634 var_locations[insn.word(1)] = insn.word(3);
635 }
636
637 if (insn.word(2) == spv::DecorationBuiltIn) {
638 var_builtins[insn.word(1)] = insn.word(3);
639 }
640
641 if (insn.word(2) == spv::DecorationComponent) {
642 var_components[insn.word(1)] = insn.word(3);
643 }
644
645 if (insn.word(2) == spv::DecorationBlock) {
646 blocks[insn.word(1)] = 1;
647 }
648
649 if (insn.word(2) == spv::DecorationPatch) {
650 var_patch[insn.word(1)] = 1;
651 }
652
653 if (insn.word(2) == spv::DecorationRelaxedPrecision) {
654 var_relaxed_precision[insn.word(1)] = 1;
655 }
656 }
657 }
658
659 // TODO: handle grouped decorations
660 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
661
662 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
663 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
664 uint32_t word = 3;
665 while (entrypoint.word(word) & 0xff000000u) {
666 ++word;
667 }
668 ++word;
669
670 std::map<location_t, interface_var> out;
671
672 for (; word < entrypoint.len(); word++) {
673 auto insn = src->get_def(entrypoint.word(word));
674 assert(insn != src->end());
675 assert(insn.opcode() == spv::OpVariable);
676
677 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
678 unsigned id = insn.word(2);
679 unsigned type = insn.word(1);
680
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600681 int location = ValueOrDefault(var_locations, id, static_cast<unsigned>(-1));
682 int builtin = ValueOrDefault(var_builtins, id, static_cast<unsigned>(-1));
683 unsigned component = ValueOrDefault(var_components, id, 0); // Unspecified is OK, is 0
Chris Forbes47567b72017-06-09 12:09:45 -0700684 bool is_patch = var_patch.find(id) != var_patch.end();
685 bool is_relaxed_precision = var_relaxed_precision.find(id) != var_relaxed_precision.end();
686
Dave Houltona9df0ce2018-02-07 10:51:23 -0700687 if (builtin != -1)
688 continue;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600689 else if (!CollectInterfaceBlockMembers(src, &out, blocks, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700690 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
691 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600692 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700693 for (unsigned int offset = 0; offset < num_locations; offset++) {
694 interface_var v = {};
695 v.id = id;
696 v.type_id = type;
697 v.offset = offset;
698 v.is_patch = is_patch;
699 v.is_relaxed_precision = is_relaxed_precision;
700 out[std::make_pair(location + offset, component)] = v;
701 }
Chris Forbes47567b72017-06-09 12:09:45 -0700702 }
703 }
704 }
705
706 return out;
707}
708
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600709static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Chris Forbes47567b72017-06-09 12:09:45 -0700710 shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids) {
711 std::vector<std::pair<uint32_t, interface_var>> out;
712
713 for (auto insn : *src) {
714 if (insn.opcode() == spv::OpDecorate) {
715 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
716 auto attachment_index = insn.word(3);
717 auto id = insn.word(1);
718
719 if (accessible_ids.count(id)) {
720 auto def = src->get_def(id);
721 assert(def != src->end());
722
723 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600724 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700725 for (unsigned int offset = 0; offset < num_locations; offset++) {
726 interface_var v = {};
727 v.id = id;
728 v.type_id = def.word(1);
729 v.offset = offset;
730 out.emplace_back(attachment_index + offset, v);
731 }
732 }
733 }
734 }
735 }
736 }
737
738 return out;
739}
740
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700741static bool IsWritableDescriptorType(shader_module const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800742 auto type = module->get_def(type_id);
743
744 // 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 -0700745 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
746 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700747 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800748 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700749 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800750 }
751 }
752
753 switch (type.opcode()) {
754 case spv::OpTypeImage: {
755 auto dim = type.word(3);
756 auto sampled = type.word(7);
757 return sampled == 2 && dim != spv::DimSubpassData;
758 }
759
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700760 case spv::OpTypeStruct: {
761 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8af24522018-03-07 11:37:45 -0800762 for (auto insn : *module) {
763 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
764 if (insn.word(2) == spv::DecorationBufferBlock) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700765 // Legacy storage block in the Uniform storage class
766 // has its struct type decorated with BufferBlock.
767 is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800768 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700769 } else if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
770 insn.word(3) == spv::DecorationNonWritable) {
771 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800772 }
773 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700774
775 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
776 // as nonwritable.
777 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
778 }
Chris Forbes8af24522018-03-07 11:37:45 -0800779 }
780
781 return false;
782}
783
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600784static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Chris Forbes8af24522018-03-07 11:37:45 -0800785 debug_report_data const *report_data, shader_module const *src, std::unordered_set<uint32_t> const &accessible_ids,
786 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700787 std::unordered_map<unsigned, unsigned> var_sets;
788 std::unordered_map<unsigned, unsigned> var_bindings;
Chris Forbes8af24522018-03-07 11:37:45 -0800789 std::unordered_map<unsigned, unsigned> var_nonwritable;
Chris Forbes47567b72017-06-09 12:09:45 -0700790
791 for (auto insn : *src) {
792 // All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
793 // DecorationDescriptorSet and DecorationBinding.
794 if (insn.opcode() == spv::OpDecorate) {
795 if (insn.word(2) == spv::DecorationDescriptorSet) {
796 var_sets[insn.word(1)] = insn.word(3);
797 }
798
799 if (insn.word(2) == spv::DecorationBinding) {
800 var_bindings[insn.word(1)] = insn.word(3);
801 }
Chris Forbes8af24522018-03-07 11:37:45 -0800802
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700803 // Note: do toplevel DecorationNonWritable out here; it applies to
804 // the OpVariable rather than the type.
Chris Forbes8af24522018-03-07 11:37:45 -0800805 if (insn.word(2) == spv::DecorationNonWritable) {
806 var_nonwritable[insn.word(1)] = 1;
807 }
Chris Forbes47567b72017-06-09 12:09:45 -0700808 }
809 }
810
811 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
812
813 for (auto id : accessible_ids) {
814 auto insn = src->get_def(id);
815 assert(insn != src->end());
816
817 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800818 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
819 insn.word(3) == spv::StorageClassStorageBuffer)) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600820 unsigned set = ValueOrDefault(var_sets, insn.word(2), 0);
821 unsigned binding = ValueOrDefault(var_bindings, insn.word(2), 0);
Chris Forbes47567b72017-06-09 12:09:45 -0700822
823 interface_var v = {};
824 v.id = insn.word(2);
825 v.type_id = insn.word(1);
826 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800827
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700828 if (var_nonwritable.find(id) == var_nonwritable.end() &&
829 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800830 *has_writable_descriptor = true;
831 }
Chris Forbes47567b72017-06-09 12:09:45 -0700832 }
833 }
834
835 return out;
836}
837
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600838static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700839 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
840 // be specified only once.
841 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
842 bool skip = false;
843
844 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
845 auto desc = &vi->pVertexBindingDescriptions[i];
846 auto &binding = bindings[desc->binding];
847 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600848 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600849 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 -0600850 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700851 desc->binding);
852 } else {
853 binding = desc;
854 }
855 }
856
857 return skip;
858}
859
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600860static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
861 shader_module const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700862 bool skip = false;
863
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600864 auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700865
866 // Build index by location
867 std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
868 if (vi) {
869 for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600870 auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
Chris Forbes47567b72017-06-09 12:09:45 -0700871 for (auto j = 0u; j < num_locations; j++) {
872 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
873 }
874 }
875 }
876
877 auto it_a = attribs.begin();
878 auto it_b = inputs.begin();
879 bool used = false;
880
881 while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
882 bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
883 bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
884 auto a_first = a_at_end ? 0 : it_a->first;
885 auto b_first = b_at_end ? 0 : it_b->first.first;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600886
Chris Forbes47567b72017-06-09 12:09:45 -0700887 if (!a_at_end && (b_at_end || a_first < b_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600888 if (!used &&
889 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 -0600890 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -0600891 "Vertex attribute at location %d not consumed by vertex shader", a_first)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700892 skip = true;
893 }
894 used = false;
895 it_a++;
896 } else if (!b_at_end && (a_at_end || b_first < a_first)) {
Mark Young4e919b22018-05-21 15:53:59 -0600897 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 -0600898 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -0600899 "Vertex shader consumes input at location %d but not provided", b_first);
Chris Forbes47567b72017-06-09 12:09:45 -0700900 it_b++;
901 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600902 unsigned attrib_type = GetFormatType(it_a->second->format);
903 unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700904
905 // Type checking
906 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600907 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 -0600908 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -0700909 "Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600910 string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700911 }
912
913 // OK!
914 used = true;
915 it_b++;
916 }
917 }
918
919 return skip;
920}
921
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600922static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, shader_module const *fs,
923 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Krause91f7a12017-12-14 20:57:36 +0100924 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes8bca1652017-07-20 11:10:09 -0700925
Chris Forbes47567b72017-06-09 12:09:45 -0700926 std::map<uint32_t, VkFormat> color_attachments;
927 auto subpass = rpci->pSubpasses[subpass_index];
928 for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
929 uint32_t attachment = subpass.pColorAttachments[i].attachment;
930 if (attachment == VK_ATTACHMENT_UNUSED) continue;
931 if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
932 color_attachments[i] = rpci->pAttachments[attachment].format;
933 }
934 }
935
936 bool skip = false;
937
938 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
939
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600940 auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700941
942 auto it_a = outputs.begin();
943 auto it_b = color_attachments.begin();
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600944 bool used = false;
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200945 bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
946 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
947 bool locationZeroHasAlpha = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700948
949 // Walk attachment list and outputs together
950
951 while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
952 bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
953 bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
954
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200955 if (!a_at_end && it_a->first.first == 0 && fs->get_def(it_a->second.type_id) != fs->end() &&
956 GetComponentsConsumedByType(fs, it_a->second.type_id, false) == 4)
957 locationZeroHasAlpha = true;
958
Chris Forbes47567b72017-06-09 12:09:45 -0700959 if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200960 if (!alphaToCoverageEnabled || it_a->first.first != 0) {
961 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
962 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
963 "fragment shader writes to output location %d with no matching attachment", it_a->first.first);
964 }
Chris Forbes47567b72017-06-09 12:09:45 -0700965 it_a++;
966 } else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
Chris Forbesefdd4082017-07-20 11:19:16 -0700967 // Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
968 // shader to not produce a matching output.
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600969 if (!used) {
970 if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700971 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600972 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Chris Forbescfe4dca2018-10-05 10:15:00 -0700973 "Attachment %d not written by fragment shader; undefined values will be written to attachment",
974 it_b->first);
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600975 }
Chris Forbesefdd4082017-07-20 11:19:16 -0700976 }
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600977 used = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700978 it_b++;
979 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600980 unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
981 unsigned att_type = GetFormatType(it_b->second);
Chris Forbes47567b72017-06-09 12:09:45 -0700982
983 // Type checking
984 if (!(output_type & att_type)) {
Chris Forbescfe4dca2018-10-05 10:15:00 -0700985 skip |= log_msg(
986 report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
987 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
988 "Attachment %d of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
989 it_b->first, string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700990 }
991
992 // OK!
993 it_a++;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600994 used = true;
Chris Forbes47567b72017-06-09 12:09:45 -0700995 }
996 }
997
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200998 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
999 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1000 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1001 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
1002 }
1003
Chris Forbes47567b72017-06-09 12:09:45 -07001004 return skip;
1005}
1006
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001007// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1008// This function examines instructions in the static call tree for a write to this variable.
1009static bool IsPointSizeWritten(shader_module const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
1010 auto type = builtin_instr.opcode();
1011 uint32_t target_id = builtin_instr.word(1);
1012 bool init_complete = false;
1013
1014 if (type == spv::OpMemberDecorate) {
1015 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1016 auto insn = entrypoint;
1017 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1018 switch (insn.opcode()) {
1019 case spv::OpTypePointer:
1020 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1021 target_id = insn.word(1);
1022 }
1023 break;
1024 case spv::OpVariable:
1025 if (insn.word(1) == target_id) {
1026 target_id = insn.word(2);
1027 init_complete = true;
1028 }
1029 break;
1030 }
1031 insn++;
1032 }
1033 }
1034
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001035 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1036
1037 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001038 std::unordered_set<uint32_t> worklist;
1039 worklist.insert(entrypoint.word(2));
1040
1041 // Follow instructions in call graph looking for writes to target
1042 while (!worklist.empty() && !found_write) {
1043 auto id_iter = worklist.begin();
1044 auto id = *id_iter;
1045 worklist.erase(id_iter);
1046
1047 auto insn = src->get_def(id);
1048 if (insn == src->end()) {
1049 continue;
1050 }
1051
1052 if (insn.opcode() == spv::OpFunction) {
1053 // Scan body of function looking for other function calls or items in our ID chain
1054 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1055 switch (insn.opcode()) {
1056 case spv::OpAccessChain:
1057 if (insn.word(3) == target_id) {
1058 if (type == spv::OpMemberDecorate) {
1059 auto value = GetConstantValue(src, insn.word(4));
1060 if (value == builtin_instr.word(2)) {
1061 target_id = insn.word(2);
1062 }
1063 } else {
1064 target_id = insn.word(2);
1065 }
1066 }
1067 break;
1068 case spv::OpStore:
1069 if (insn.word(1) == target_id) {
1070 found_write = true;
1071 }
1072 break;
1073 case spv::OpFunctionCall:
1074 worklist.insert(insn.word(3));
1075 break;
1076 }
1077 }
1078 }
1079 }
1080 return found_write;
1081}
1082
Chris Forbes47567b72017-06-09 12:09:45 -07001083// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1084// important for identifying the set of shader resources actually used by an entrypoint, for example.
1085// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1086// - NOT the shader input/output interfaces.
1087//
1088// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1089// converting parts of this to be generated from the machine-readable spec instead.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001090static std::unordered_set<uint32_t> MarkAccessibleIds(shader_module const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001091 std::unordered_set<uint32_t> ids;
1092 std::unordered_set<uint32_t> worklist;
1093 worklist.insert(entrypoint.word(2));
1094
1095 while (!worklist.empty()) {
1096 auto id_iter = worklist.begin();
1097 auto id = *id_iter;
1098 worklist.erase(id_iter);
1099
1100 auto insn = src->get_def(id);
1101 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001102 // 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 -07001103 // that we may not care about.
1104 continue;
1105 }
1106
1107 // Try to add to the output set
1108 if (!ids.insert(id).second) {
1109 continue; // If we already saw this id, we don't want to walk it again.
1110 }
1111
1112 switch (insn.opcode()) {
1113 case spv::OpFunction:
1114 // Scan whole body of the function, enlisting anything interesting
1115 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1116 switch (insn.opcode()) {
1117 case spv::OpLoad:
1118 case spv::OpAtomicLoad:
1119 case spv::OpAtomicExchange:
1120 case spv::OpAtomicCompareExchange:
1121 case spv::OpAtomicCompareExchangeWeak:
1122 case spv::OpAtomicIIncrement:
1123 case spv::OpAtomicIDecrement:
1124 case spv::OpAtomicIAdd:
1125 case spv::OpAtomicISub:
1126 case spv::OpAtomicSMin:
1127 case spv::OpAtomicUMin:
1128 case spv::OpAtomicSMax:
1129 case spv::OpAtomicUMax:
1130 case spv::OpAtomicAnd:
1131 case spv::OpAtomicOr:
1132 case spv::OpAtomicXor:
1133 worklist.insert(insn.word(3)); // ptr
1134 break;
1135 case spv::OpStore:
1136 case spv::OpAtomicStore:
1137 worklist.insert(insn.word(1)); // ptr
1138 break;
1139 case spv::OpAccessChain:
1140 case spv::OpInBoundsAccessChain:
1141 worklist.insert(insn.word(3)); // base ptr
1142 break;
1143 case spv::OpSampledImage:
1144 case spv::OpImageSampleImplicitLod:
1145 case spv::OpImageSampleExplicitLod:
1146 case spv::OpImageSampleDrefImplicitLod:
1147 case spv::OpImageSampleDrefExplicitLod:
1148 case spv::OpImageSampleProjImplicitLod:
1149 case spv::OpImageSampleProjExplicitLod:
1150 case spv::OpImageSampleProjDrefImplicitLod:
1151 case spv::OpImageSampleProjDrefExplicitLod:
1152 case spv::OpImageFetch:
1153 case spv::OpImageGather:
1154 case spv::OpImageDrefGather:
1155 case spv::OpImageRead:
1156 case spv::OpImage:
1157 case spv::OpImageQueryFormat:
1158 case spv::OpImageQueryOrder:
1159 case spv::OpImageQuerySizeLod:
1160 case spv::OpImageQuerySize:
1161 case spv::OpImageQueryLod:
1162 case spv::OpImageQueryLevels:
1163 case spv::OpImageQuerySamples:
1164 case spv::OpImageSparseSampleImplicitLod:
1165 case spv::OpImageSparseSampleExplicitLod:
1166 case spv::OpImageSparseSampleDrefImplicitLod:
1167 case spv::OpImageSparseSampleDrefExplicitLod:
1168 case spv::OpImageSparseSampleProjImplicitLod:
1169 case spv::OpImageSparseSampleProjExplicitLod:
1170 case spv::OpImageSparseSampleProjDrefImplicitLod:
1171 case spv::OpImageSparseSampleProjDrefExplicitLod:
1172 case spv::OpImageSparseFetch:
1173 case spv::OpImageSparseGather:
1174 case spv::OpImageSparseDrefGather:
1175 case spv::OpImageTexelPointer:
1176 worklist.insert(insn.word(3)); // Image or sampled image
1177 break;
1178 case spv::OpImageWrite:
1179 worklist.insert(insn.word(1)); // Image -- different operand order to above
1180 break;
1181 case spv::OpFunctionCall:
1182 for (uint32_t i = 3; i < insn.len(); i++) {
1183 worklist.insert(insn.word(i)); // fn itself, and all args
1184 }
1185 break;
1186
1187 case spv::OpExtInst:
1188 for (uint32_t i = 5; i < insn.len(); i++) {
1189 worklist.insert(insn.word(i)); // Operands to ext inst
1190 }
1191 break;
1192 }
1193 }
1194 break;
1195 }
1196 }
1197
1198 return ids;
1199}
1200
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001201static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1202 std::vector<VkPushConstantRange> const *push_constant_ranges,
1203 shader_module const *src, spirv_inst_iter type, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001204 bool skip = false;
1205
1206 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001207 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001208 assert(type != src->end());
1209
1210 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1211 // TODO: arrays, matrices, weird sizes
1212 for (auto insn : *src) {
1213 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1214 if (insn.word(3) == spv::DecorationOffset) {
1215 unsigned offset = insn.word(4);
1216 auto size = 4; // Bytes; TODO: calculate this based on the type
1217
1218 bool found_range = false;
1219 for (auto const &range : *push_constant_ranges) {
1220 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1221 found_range = true;
1222
1223 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001224 skip |=
1225 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 -06001226 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001227 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1228 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001229 }
1230
1231 break;
1232 }
1233 }
1234
1235 if (!found_range) {
1236 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 -06001237 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001238 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001239 }
1240 }
1241 }
1242 }
1243
1244 return skip;
1245}
1246
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001247static bool ValidatePushConstantUsage(debug_report_data const *report_data,
1248 std::vector<VkPushConstantRange> const *push_constant_ranges, shader_module const *src,
1249 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001250 bool skip = false;
1251
1252 for (auto id : accessible_ids) {
1253 auto def_insn = src->get_def(id);
1254 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001255 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1256 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001257 }
1258 }
1259
1260 return skip;
1261}
1262
1263// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001264static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001265 bool skip = false;
1266
1267 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1268
1269 if (spec) {
1270 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001271 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001272 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001273 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 -06001274 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001275 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001276 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001277 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001278 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001279 }
1280 }
1281 }
1282
1283 return skip;
1284}
1285
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001286// TODO (jbolz): Can this return a const reference?
Jeff Bolze54ae892018-09-08 12:16:29 -05001287static std::set<uint32_t> TypeToDescriptorTypeSet(shader_module const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001288 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001289 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001290 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001291 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001292
1293 // 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 -05001294 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1295 if (type.opcode() == spv::OpTypeRuntimeArray) {
1296 descriptor_count = 0;
1297 type = module->get_def(type.word(2));
1298 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001299 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001300 type = module->get_def(type.word(2));
1301 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001302 if (type.word(2) == spv::StorageClassStorageBuffer) {
1303 is_storage_buffer = true;
1304 }
Chris Forbes47567b72017-06-09 12:09:45 -07001305 type = module->get_def(type.word(3));
1306 }
1307 }
1308
1309 switch (type.opcode()) {
1310 case spv::OpTypeStruct: {
1311 for (auto insn : *module) {
1312 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1313 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001314 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001315 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1316 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1317 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001318 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001319 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1320 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1321 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1322 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001323 }
Chris Forbes47567b72017-06-09 12:09:45 -07001324 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001325 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1326 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1327 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001328 }
1329 }
1330 }
1331
1332 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001333 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001334 }
1335
1336 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001337 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1338 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1339 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001340
Chris Forbes73c00bf2018-06-22 16:28:06 -07001341 case spv::OpTypeSampledImage: {
1342 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1343 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1344 auto image_type = module->get_def(type.word(2));
1345 auto dim = image_type.word(3);
1346 auto sampled = image_type.word(7);
1347 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001348 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1349 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001350 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001351 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001352 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1353 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001354
1355 case spv::OpTypeImage: {
1356 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1357 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1358 auto dim = type.word(3);
1359 auto sampled = type.word(7);
1360
1361 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001362 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1363 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001364 } else if (dim == spv::DimBuffer) {
1365 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001366 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1367 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001368 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001369 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1370 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001371 }
1372 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001373 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1374 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1375 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001376 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001377 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1378 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001379 }
1380 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001381 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001382 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001383 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001384
1385 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1386 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001387 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001388 }
1389}
1390
Jeff Bolze54ae892018-09-08 12:16:29 -05001391static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001392 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001393 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1394 if (ss.tellp()) ss << ", ";
1395 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001396 }
1397 return ss.str();
1398}
1399
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001400static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001401 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001402 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 -06001403 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001404 return true;
1405 }
1406 }
1407
1408 return false;
1409}
1410
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001411static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001412 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001413 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 -06001414 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001415 extension_name)) {
1416 return true;
1417 }
1418 }
1419
1420 return false;
1421}
1422
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001423bool CoreChecks::ValidateShaderCapabilities(shader_module const *src, VkShaderStageFlagBits stage, bool has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001424 bool skip = false;
1425
Mark Lobodzinski60e79032019-03-07 10:22:31 -07001426 auto const &features = GetEnabledFeatures();
Chris Forbes47567b72017-06-09 12:09:45 -07001427
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001428 struct FeaturePointer {
1429 // Callable object to test if this feature is enabled in the given aggregate feature struct
1430 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1431
1432 // Test if feature pointer is populated
1433 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1434
1435 // Default and nullptr constructor to create an empty FeaturePointer
1436 FeaturePointer() : IsEnabled(nullptr) {}
1437 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1438
1439 // Constructors to populate FeaturePointer based on given pointer to member
1440 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1441 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1442 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1443 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1444 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1445 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001446 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1447 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001448 FeaturePointer(VkBool32 VkPhysicalDeviceFloat16Int8FeaturesKHR::*ptr)
1449 : IsEnabled([=](const DeviceFeatures &features) { return features.float16_int8.*ptr; }) {}
Tobias Hector6a0ece72018-12-10 12:24:05 +00001450 FeaturePointer(VkBool32 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT::*ptr)
1451 : IsEnabled([=](const DeviceFeatures &features) { return features.scalar_block_layout_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06001452 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
1453 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001454 FeaturePointer(VkBool32 VkPhysicalDeviceFloatControlsPropertiesKHR::*ptr)
1455 : IsEnabled([=](const DeviceFeatures &features) { return features.float_controls.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001456 };
1457
Chris Forbes47567b72017-06-09 12:09:45 -07001458 struct CapabilityInfo {
1459 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001460 FeaturePointer feature;
1461 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001462 };
1463
Chris Forbes47567b72017-06-09 12:09:45 -07001464 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001465 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001466 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1467 // feature bits.
1468 {spv::CapabilityMatrix, {nullptr}},
1469 {spv::CapabilityShader, {nullptr}},
1470 {spv::CapabilityInputAttachment, {nullptr}},
1471 {spv::CapabilitySampled1D, {nullptr}},
1472 {spv::CapabilityImage1D, {nullptr}},
1473 {spv::CapabilitySampledBuffer, {nullptr}},
1474 {spv::CapabilityImageQuery, {nullptr}},
1475 {spv::CapabilityDerivativeControl, {nullptr}},
1476
1477 // Capabilities that are optionally supported, but require a feature to
1478 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001479 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1480 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1481 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1482 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1483 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1484 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1485 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1486 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1487 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1488 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1489 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1490 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1491 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1492 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1493 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1494 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1495 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1496 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1497 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1498 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1499 {spv::CapabilityStorageImageExtendedFormats, {"VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats", &VkPhysicalDeviceFeatures::shaderStorageImageExtendedFormats}},
1500 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1501 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1502 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1503 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001504
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001505 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1506 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1507 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1508 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1509 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1510 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1511 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1512 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1513 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1514 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1515 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
1516 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT , {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001517
1518 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001519 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1520 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1521 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1522 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1523 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1524 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1525 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1526 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
aqnuep7033c702018-09-11 18:03:29 +02001527 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001528
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001529 {spv::CapabilityStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1530 {spv::CapabilityUniformAndStorageBuffer8BitAccess , {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1531 {spv::CapabilityStoragePushConstant8 , {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001532
1533 {spv::CapabilityTransformFeedback , { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001534 {spv::CapabilityGeometryStreams , { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
1535
1536 {spv::CapabilityFloat16 , {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1537 {spv::CapabilityInt8 , {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06001538
1539 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001540
1541 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1542 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1543 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1544 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1545 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1546 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1547 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1548 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1549 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1550 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1551 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1552 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1553 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1554 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1555 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
Chris Forbes47567b72017-06-09 12:09:45 -07001556 };
1557 // clang-format on
1558
1559 for (auto insn : *src) {
1560 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001561 size_t n = capabilities.count(insn.word(1));
1562 if (1 == n) { // key occurs exactly once
1563 auto it = capabilities.find(insn.word(1));
1564 if (it != capabilities.end()) {
1565 if (it->second.feature) {
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001566 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(*features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001567 }
1568 if (it->second.extension) {
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001569 skip |= RequireExtension(report_data, device_extensions.*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001570 }
Chris Forbes47567b72017-06-09 12:09:45 -07001571 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001572 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1573 bool needs_feature = false, has_feature = false;
1574 bool needs_ext = false, has_ext = false;
1575 std::string feature_names = "(one of) [ ";
1576 std::string extension_names = feature_names;
1577 auto caps = capabilities.equal_range(insn.word(1));
1578 for (auto it = caps.first; it != caps.second; ++it) {
1579 if (it->second.feature) {
1580 needs_feature = true;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001581 has_feature = has_feature || it->second.feature.IsEnabled(*features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001582 feature_names += it->second.name;
1583 feature_names += " ";
1584 }
1585 if (it->second.extension) {
1586 needs_ext = true;
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001587 has_ext = has_ext || device_extensions.*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001588 extension_names += it->second.name;
1589 extension_names += " ";
1590 }
1591 }
1592 if (needs_feature) {
1593 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001594 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001595 }
1596 if (needs_ext) {
1597 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001598 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001599 }
1600 }
1601 }
1602 }
1603
Chris Forbes349b3132018-03-07 11:38:08 -08001604 if (has_writable_descriptor) {
1605 switch (stage) {
1606 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06001607 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1608 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1609 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1610 case VK_SHADER_STAGE_MISS_BIT_NV:
1611 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1612 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1613 case VK_SHADER_STAGE_TASK_BIT_NV:
1614 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08001615 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06001616 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08001617 break;
1618 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001619 skip |= RequireFeature(report_data, features->core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001620 break;
1621 default:
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001622 skip |=
1623 RequireFeature(report_data, features->core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001624 break;
1625 }
1626 }
1627
Chris Forbes47567b72017-06-09 12:09:45 -07001628 return skip;
1629}
1630
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001631static bool VariableIsBuiltIn(shader_module const *src, const uint32_t ID, std::vector<uint32_t> const &builtInBlockIDs,
1632 std::vector<uint32_t> const &builtInIDs) {
1633 auto insn = src->get_def(ID);
1634
1635 switch (insn.opcode()) {
1636 case spv::OpVariable: {
1637 // First check if the variable is a "pure" built-in type, e.g. gl_ViewportIndex
1638 uint32_t ID = insn.word(2);
1639 for (auto builtInID : builtInIDs) {
1640 if (ID == builtInID) {
1641 return true;
1642 }
1643 }
1644
Ari Suonpaa89c60822019-03-25 14:13:02 +02001645 return VariableIsBuiltIn(src, insn.word(1), builtInBlockIDs, builtInIDs);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001646 }
1647 case spv::OpTypePointer:
Ari Suonpaa89c60822019-03-25 14:13:02 +02001648 return VariableIsBuiltIn(src, insn.word(3), builtInBlockIDs, builtInIDs);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001649 case spv::OpTypeArray:
Ari Suonpaa89c60822019-03-25 14:13:02 +02001650 return VariableIsBuiltIn(src, insn.word(2), builtInBlockIDs, builtInIDs);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001651 case spv::OpTypeStruct: {
1652 uint32_t ID = insn.word(1); // We only need to check the first member as either all will be, or none will be built-in
1653 for (auto builtInBlockID : builtInBlockIDs) {
1654 if (ID == builtInBlockID) {
1655 return true;
1656 }
1657 }
1658 return false;
1659 }
1660 default:
1661 return false;
1662 }
1663
1664 return false;
1665}
1666
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001667bool CoreChecks::ValidateShaderStageInputOutputLimits(shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1668 PIPELINE_STATE *pipeline) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001669 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
1670 pStage->stage == VK_SHADER_STAGE_ALL) {
1671 return false;
1672 }
1673
1674 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001675 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001676
1677 std::vector<uint32_t> builtInBlockIDs;
1678 std::vector<uint32_t> builtInIDs;
1679 struct Variable {
1680 uint32_t baseTypePtrID;
1681 uint32_t ID;
1682 uint32_t storageClass;
1683 };
1684 std::vector<Variable> variables;
1685
1686 for (auto insn : *src) {
1687 switch (insn.opcode()) {
1688 // Find all built-in member decorations
1689 case spv::OpMemberDecorate:
1690 if (insn.word(3) == spv::DecorationBuiltIn) {
1691 builtInBlockIDs.push_back(insn.word(1));
1692 }
1693 break;
1694 // Find all built-in decorations
1695 case spv::OpDecorate:
1696 switch (insn.word(2)) {
1697 case spv::DecorationBlock: {
1698 uint32_t blockID = insn.word(1);
1699 for (auto builtInBlockID : builtInBlockIDs) {
1700 // Check if one of the members of the block are built-in -> the block is built-in
1701 if (blockID == builtInBlockID) {
1702 builtInIDs.push_back(blockID);
1703 break;
1704 }
1705 }
1706 break;
1707 }
1708 case spv::DecorationBuiltIn:
1709 builtInIDs.push_back(insn.word(1));
1710 break;
1711 default:
1712 break;
1713 }
1714 break;
1715 // Find all input and output variables
1716 case spv::OpVariable: {
1717 Variable var = {};
1718 var.storageClass = insn.word(3);
1719 if (var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) {
1720 var.baseTypePtrID = insn.word(1);
1721 var.ID = insn.word(2);
1722 variables.push_back(var);
1723 }
1724 break;
1725 }
1726 default:
1727 break;
1728 }
1729 }
1730
1731 uint32_t numCompIn = 0, numCompOut = 0;
1732 for (auto &var : variables) {
1733 // Check the variable's ID
1734 if (VariableIsBuiltIn(src, var.ID, builtInBlockIDs, builtInIDs)) {
1735 continue;
1736 }
1737 // Check the variable's type's ID - e.g. gl_PerVertex is made of basic types, not built-in types
1738 if (VariableIsBuiltIn(src, src->get_def(var.baseTypePtrID).word(3), builtInBlockIDs, builtInIDs)) {
1739 continue;
1740 }
1741
1742 if (var.storageClass == spv::StorageClassInput) {
1743 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, false);
1744 } else { // var.storageClass == spv::StorageClassOutput
1745 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, false);
1746 }
1747 }
1748
1749 switch (pStage->stage) {
1750 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001751 if (numCompOut > limits.maxVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001752 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1753 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1754 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
1755 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
1756 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001757 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001758 }
1759 break;
1760
1761 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001762 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001763 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1764 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1765 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1766 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
1767 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001768 limits.maxTessellationControlPerVertexInputComponents,
1769 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001770 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001771 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001772 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1773 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1774 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1775 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
1776 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001777 limits.maxTessellationControlPerVertexOutputComponents,
1778 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001779 }
1780 break;
1781
1782 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001783 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001784 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1785 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1786 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1787 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
1788 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001789 limits.maxTessellationEvaluationInputComponents,
1790 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001791 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001792 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001793 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1794 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1795 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1796 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
1797 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001798 limits.maxTessellationEvaluationOutputComponents,
1799 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001800 }
1801 break;
1802
1803 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001804 if (numCompIn > limits.maxGeometryInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001805 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1806 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1807 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1808 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
1809 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001810 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001811 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001812 if (numCompOut > limits.maxGeometryOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001813 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1814 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1815 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1816 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
1817 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001818 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001819 }
1820 break;
1821
1822 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001823 if (numCompIn > limits.maxFragmentInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001824 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1825 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1826 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
1827 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
1828 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001829 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001830 }
1831 break;
1832
Jeff Bolz148d94e2018-12-13 21:25:56 -06001833 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1834 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1835 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1836 case VK_SHADER_STAGE_MISS_BIT_NV:
1837 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1838 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1839 case VK_SHADER_STAGE_TASK_BIT_NV:
1840 case VK_SHADER_STAGE_MESH_BIT_NV:
1841 break;
1842
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001843 default:
1844 assert(false); // This should never happen
1845 }
1846 return skip;
1847}
1848
Jeff Bolze4356752019-03-07 11:23:46 -06001849// copy the specialization constant value into buf, if it is present
1850void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
1851 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
1852
1853 if (spec && spec_id < spec->mapEntryCount) {
1854 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
1855 }
1856}
1857
1858// Fill in value with the constant or specialization constant value, if available.
1859// Returns true if the value has been accurately filled out.
1860static bool GetIntConstantValue(spirv_inst_iter insn, shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1861 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
1862 auto type_id = src->get_def(insn.word(1));
1863 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
1864 return false;
1865 }
1866 switch (insn.opcode()) {
1867 case spv::OpSpecConstant:
1868 *value = insn.word(3);
1869 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
1870 return true;
1871 case spv::OpConstant:
1872 *value = insn.word(3);
1873 return true;
1874 default:
1875 return false;
1876 }
1877}
1878
1879// Map SPIR-V type to VK_COMPONENT_TYPE enum
1880VkComponentTypeNV GetComponentType(spirv_inst_iter insn, shader_module const *src) {
1881 switch (insn.opcode()) {
1882 case spv::OpTypeInt:
1883 switch (insn.word(2)) {
1884 case 8:
1885 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
1886 case 16:
1887 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
1888 case 32:
1889 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
1890 case 64:
1891 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
1892 default:
1893 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1894 }
1895 case spv::OpTypeFloat:
1896 switch (insn.word(2)) {
1897 case 16:
1898 return VK_COMPONENT_TYPE_FLOAT16_NV;
1899 case 32:
1900 return VK_COMPONENT_TYPE_FLOAT32_NV;
1901 case 64:
1902 return VK_COMPONENT_TYPE_FLOAT64_NV;
1903 default:
1904 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1905 }
1906 default:
1907 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1908 }
1909}
1910
1911// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
1912// in SPIRV-Tools (e.g. due to specialization constant usage).
1913bool CoreChecks::ValidateCooperativeMatrix(shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1914 PIPELINE_STATE *pipeline) {
1915 bool skip = false;
1916
1917 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
1918 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
1919 // Map SPIR-V result ID to the ID of its type.
1920 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
1921
1922 struct CoopMatType {
1923 uint32_t scope, rows, cols;
1924 VkComponentTypeNV component_type;
1925 bool all_constant;
1926
1927 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
1928
1929 void Init(uint32_t id, shader_module const *src, VkPipelineShaderStageCreateInfo const *pStage,
1930 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
1931 spirv_inst_iter insn = src->get_def(id);
1932 uint32_t component_type_id = insn.word(2);
1933 uint32_t scope_id = insn.word(3);
1934 uint32_t rows_id = insn.word(4);
1935 uint32_t cols_id = insn.word(5);
1936 auto component_type_iter = src->get_def(component_type_id);
1937 auto scope_iter = src->get_def(scope_id);
1938 auto rows_iter = src->get_def(rows_id);
1939 auto cols_iter = src->get_def(cols_id);
1940
1941 all_constant = true;
1942 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
1943 all_constant = false;
1944 }
1945 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
1946 all_constant = false;
1947 }
1948 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
1949 all_constant = false;
1950 }
1951 component_type = GetComponentType(component_type_iter, src);
1952 }
1953 };
1954
1955 bool seen_coopmat_capability = false;
1956
1957 for (auto insn : *src) {
1958 // Whitelist instructions whose result can be a cooperative matrix type, and
1959 // keep track of their types. It would be nice if SPIRV-Headers generated code
1960 // to identify which instructions have a result type and result id. Lacking that,
1961 // this whitelist is based on the set of instructions that
1962 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
1963 switch (insn.opcode()) {
1964 case spv::OpLoad:
1965 case spv::OpCooperativeMatrixLoadNV:
1966 case spv::OpCooperativeMatrixMulAddNV:
1967 case spv::OpSNegate:
1968 case spv::OpFNegate:
1969 case spv::OpIAdd:
1970 case spv::OpFAdd:
1971 case spv::OpISub:
1972 case spv::OpFSub:
1973 case spv::OpFDiv:
1974 case spv::OpSDiv:
1975 case spv::OpUDiv:
1976 case spv::OpMatrixTimesScalar:
1977 case spv::OpConstantComposite:
1978 case spv::OpCompositeConstruct:
1979 case spv::OpConvertFToU:
1980 case spv::OpConvertFToS:
1981 case spv::OpConvertSToF:
1982 case spv::OpConvertUToF:
1983 case spv::OpUConvert:
1984 case spv::OpSConvert:
1985 case spv::OpFConvert:
1986 id_to_type_id[insn.word(2)] = insn.word(1);
1987 break;
1988 default:
1989 break;
1990 }
1991
1992 switch (insn.opcode()) {
1993 case spv::OpDecorate:
1994 if (insn.word(2) == spv::DecorationSpecId) {
1995 id_to_spec_id[insn.word(1)] = insn.word(3);
1996 }
1997 break;
1998 case spv::OpCapability:
1999 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2000 seen_coopmat_capability = true;
2001
2002 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
2003 skip |=
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002004 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002005 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2006 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2007 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
2008 }
2009 }
2010 break;
2011 case spv::OpMemoryModel:
2012 // If the capability isn't enabled, don't bother with the rest of this function.
2013 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2014 if (!seen_coopmat_capability) {
2015 return skip;
2016 }
2017 break;
2018 case spv::OpTypeCooperativeMatrixNV: {
2019 CoopMatType M;
2020 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2021
2022 if (M.all_constant) {
2023 // Validate that the type parameters are all supported for one of the
2024 // operands of a cooperative matrix property.
2025 bool valid = false;
2026 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2027 if (cooperative_matrix_properties[i].AType == M.component_type &&
2028 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2029 cooperative_matrix_properties[i].scope == M.scope) {
2030 valid = true;
2031 break;
2032 }
2033 if (cooperative_matrix_properties[i].BType == M.component_type &&
2034 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2035 cooperative_matrix_properties[i].scope == M.scope) {
2036 valid = true;
2037 break;
2038 }
2039 if (cooperative_matrix_properties[i].CType == M.component_type &&
2040 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2041 cooperative_matrix_properties[i].scope == M.scope) {
2042 valid = true;
2043 break;
2044 }
2045 if (cooperative_matrix_properties[i].DType == M.component_type &&
2046 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2047 cooperative_matrix_properties[i].scope == M.scope) {
2048 valid = true;
2049 break;
2050 }
2051 }
2052 if (!valid) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002053 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002054 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixType,
2055 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2056 insn.word(1));
2057 }
2058 }
2059 break;
2060 }
2061 case spv::OpCooperativeMatrixMulAddNV: {
2062 CoopMatType A, B, C, D;
2063 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2064 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2065 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2066 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
2067 assert(!"Couldn't find type of matrix");
2068 break;
2069 }
2070 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2071 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2072 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2073 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2074
2075 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2076 // Validate that the type parameters are all supported for the same
2077 // cooperative matrix property.
2078 bool valid = false;
2079 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2080 if (cooperative_matrix_properties[i].AType == A.component_type &&
2081 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2082 cooperative_matrix_properties[i].scope == A.scope &&
2083
2084 cooperative_matrix_properties[i].BType == B.component_type &&
2085 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2086 cooperative_matrix_properties[i].scope == B.scope &&
2087
2088 cooperative_matrix_properties[i].CType == C.component_type &&
2089 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2090 cooperative_matrix_properties[i].scope == C.scope &&
2091
2092 cooperative_matrix_properties[i].DType == D.component_type &&
2093 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2094 cooperative_matrix_properties[i].scope == D.scope) {
2095 valid = true;
2096 break;
2097 }
2098 }
2099 if (!valid) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002100 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002101 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixMulAdd,
2102 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2103 "VkCooperativeMatrixPropertiesNV",
2104 insn.word(2));
2105 }
2106 }
2107 break;
2108 }
2109 default:
2110 break;
2111 }
2112 }
2113
2114 return skip;
2115}
2116
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002117bool CoreChecks::ValidateExecutionModes(shader_module const *src, spirv_inst_iter entrypoint) {
2118 auto entrypoint_id = entrypoint.word(2);
2119
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002120 // The first denorm execution mode encountered, along with its bit width.
2121 // Used to check if SeparateDenormSettings is respected.
2122 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002123
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002124 // The first rounding mode encountered, along with its bit width.
2125 // Used to check if SeparateRoundingModeSettings is respected.
2126 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002127
2128 bool skip = false;
2129
2130 for (auto insn : *src) {
2131 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2132 auto mode = insn.word(2);
2133 switch (mode) {
2134 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2135 auto bit_width = insn.word(3);
2136 if ((bit_width == 16 && !GetEnabledFeatures()->float_controls.shaderSignedZeroInfNanPreserveFloat16) ||
2137 (bit_width == 32 && !GetEnabledFeatures()->float_controls.shaderSignedZeroInfNanPreserveFloat32) ||
2138 (bit_width == 64 && !GetEnabledFeatures()->float_controls.shaderSignedZeroInfNanPreserveFloat64)) {
2139 skip |=
2140 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2141 kVUID_Core_Shader_FeatureNotEnabled,
2142 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2143 bit_width);
2144 }
2145 break;
2146 }
2147
2148 case spv::ExecutionModeDenormPreserve: {
2149 auto bit_width = insn.word(3);
2150 if ((bit_width == 16 && !GetEnabledFeatures()->float_controls.shaderDenormPreserveFloat16) ||
2151 (bit_width == 32 && !GetEnabledFeatures()->float_controls.shaderDenormPreserveFloat32) ||
2152 (bit_width == 64 && !GetEnabledFeatures()->float_controls.shaderDenormPreserveFloat64)) {
2153 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2154 kVUID_Core_Shader_FeatureNotEnabled,
2155 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2156 bit_width);
2157 }
2158
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002159 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2160 // Register the first denorm execution mode found
2161 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
2162 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width &&
2163 !GetEnabledFeatures()->float_controls.separateDenormSettings) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002164 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2165 kVUID_Core_Shader_FeatureNotEnabled,
2166 "Shader uses separate denorm execution modes for different bit widths but "
2167 "SeparateDenormSettings is not enabled on the device");
2168 }
2169 break;
2170 }
2171
2172 case spv::ExecutionModeDenormFlushToZero: {
2173 auto bit_width = insn.word(3);
2174 if ((bit_width == 16 && !GetEnabledFeatures()->float_controls.shaderDenormFlushToZeroFloat16) ||
2175 (bit_width == 32 && !GetEnabledFeatures()->float_controls.shaderDenormFlushToZeroFloat32) ||
2176 (bit_width == 64 && !GetEnabledFeatures()->float_controls.shaderDenormFlushToZeroFloat64)) {
2177 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2178 kVUID_Core_Shader_FeatureNotEnabled,
2179 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2180 bit_width);
2181 }
2182
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002183 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2184 // Register the first denorm execution mode found
2185 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
2186 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width &&
2187 !GetEnabledFeatures()->float_controls.separateDenormSettings) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002188 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2189 kVUID_Core_Shader_FeatureNotEnabled,
2190 "Shader uses separate denorm execution modes for different bit widths but "
2191 "SeparateDenormSettings is not enabled on the device");
2192 }
2193 break;
2194 }
2195
2196 case spv::ExecutionModeRoundingModeRTE: {
2197 auto bit_width = insn.word(3);
2198 if ((bit_width == 16 && !GetEnabledFeatures()->float_controls.shaderRoundingModeRTEFloat16) ||
2199 (bit_width == 32 && !GetEnabledFeatures()->float_controls.shaderRoundingModeRTEFloat32) ||
2200 (bit_width == 64 && !GetEnabledFeatures()->float_controls.shaderRoundingModeRTEFloat64)) {
2201 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2202 kVUID_Core_Shader_FeatureNotEnabled,
2203 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2204 bit_width);
2205 }
2206
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002207 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2208 // Register the first rounding mode found
2209 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
2210 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width &&
2211 !GetEnabledFeatures()->float_controls.separateRoundingModeSettings) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002212 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2213 kVUID_Core_Shader_FeatureNotEnabled,
2214 "Shader uses separate rounding modes for different bit widths but "
2215 "SeparateRoundingModeSettings is not enabled on the device");
2216 }
2217 break;
2218 }
2219
2220 case spv::ExecutionModeRoundingModeRTZ: {
2221 auto bit_width = insn.word(3);
2222 if ((bit_width == 16 && !GetEnabledFeatures()->float_controls.shaderRoundingModeRTZFloat16) ||
2223 (bit_width == 32 && !GetEnabledFeatures()->float_controls.shaderRoundingModeRTZFloat32) ||
2224 (bit_width == 64 && !GetEnabledFeatures()->float_controls.shaderRoundingModeRTZFloat64)) {
2225 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2226 kVUID_Core_Shader_FeatureNotEnabled,
2227 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
2228 bit_width);
2229 }
2230
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002231 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2232 // Register the first rounding mode found
2233 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
2234 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width &&
2235 !GetEnabledFeatures()->float_controls.separateRoundingModeSettings) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002236 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2237 kVUID_Core_Shader_FeatureNotEnabled,
2238 "Shader uses separate rounding modes for different bit widths but "
2239 "SeparateRoundingModeSettings is not enabled on the device");
2240 }
2241 break;
2242 }
2243 }
2244 }
2245 }
2246
2247 return skip;
2248}
2249
Jeff Bolze4356752019-03-07 11:23:46 -06002250static uint32_t DescriptorTypeToReqs(shader_module const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07002251 auto type = module->get_def(type_id);
2252
2253 while (true) {
2254 switch (type.opcode()) {
2255 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07002256 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07002257 case spv::OpTypeSampledImage:
2258 type = module->get_def(type.word(2));
2259 break;
2260 case spv::OpTypePointer:
2261 type = module->get_def(type.word(3));
2262 break;
2263 case spv::OpTypeImage: {
2264 auto dim = type.word(3);
2265 auto arrayed = type.word(5);
2266 auto msaa = type.word(6);
2267
Chris Forbes74ba2232018-08-27 15:19:27 -07002268 uint32_t bits = 0;
2269 switch (GetFundamentalType(module, type.word(2))) {
2270 case FORMAT_TYPE_FLOAT:
2271 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
2272 break;
2273 case FORMAT_TYPE_UINT:
2274 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
2275 break;
2276 case FORMAT_TYPE_SINT:
2277 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
2278 break;
2279 default:
2280 break;
2281 }
2282
Chris Forbes47567b72017-06-09 12:09:45 -07002283 switch (dim) {
2284 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002285 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
2286 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002287 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002288 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2289 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
2290 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002291 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002292 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
2293 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002294 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07002295 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
2296 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002297 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07002298 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2299 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002300 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07002301 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002302 }
2303 }
2304 default:
2305 return 0;
2306 }
2307 }
2308}
2309
2310// For given pipelineLayout verify that the set_layout_node at slot.first
2311// has the requested binding at slot.second and return ptr to that binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002312static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_NODE const *pipelineLayout,
2313 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07002314 if (!pipelineLayout) return nullptr;
2315
2316 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
2317
2318 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
2319}
2320
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002321static void ProcessExecutionModes(shader_module const *src, spirv_inst_iter entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05002322 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07002323 bool is_point_mode = false;
2324
2325 for (auto insn : *src) {
2326 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2327 switch (insn.word(2)) {
2328 case spv::ExecutionModePointMode:
2329 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
2330 is_point_mode = true;
2331 break;
2332
2333 case spv::ExecutionModeOutputPoints:
2334 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2335 break;
2336
2337 case spv::ExecutionModeIsolines:
2338 case spv::ExecutionModeOutputLineStrip:
2339 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
2340 break;
2341
2342 case spv::ExecutionModeTriangles:
2343 case spv::ExecutionModeQuads:
2344 case spv::ExecutionModeOutputTriangleStrip:
2345 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
2346 break;
2347 }
2348 }
2349 }
2350
2351 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2352}
2353
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002354// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
2355// o If there is only a vertex shader : gl_PointSize must be written when using points
2356// o If there is a geometry or tessellation shader:
2357// - If shaderTessellationAndGeometryPointSize feature is enabled:
2358// * gl_PointSize must be written in the final geometry stage
2359// - If shaderTessellationAndGeometryPointSize feature is disabled:
2360// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002361bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, shader_module const *src, spirv_inst_iter entrypoint,
2362 VkShaderStageFlagBits stage) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002363 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2364 return false;
2365 }
2366
2367 bool pointsize_written = false;
2368 bool skip = false;
2369
2370 // Search for PointSize built-in decorations
2371 std::vector<uint32_t> pointsize_builtin_offsets;
2372 spirv_inst_iter insn = entrypoint;
2373 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
2374 if (insn.opcode() == spv::OpMemberDecorate) {
2375 if (insn.word(3) == spv::DecorationBuiltIn) {
2376 if (insn.word(4) == spv::BuiltInPointSize) {
2377 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2378 }
2379 }
2380 } else if (insn.opcode() == spv::OpDecorate) {
2381 if (insn.word(2) == spv::DecorationBuiltIn) {
2382 if (insn.word(3) == spv::BuiltInPointSize) {
2383 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2384 }
2385 }
2386 }
2387
2388 insn++;
2389 }
2390
2391 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinski60e79032019-03-07 10:22:31 -07002392 !GetEnabledFeatures()->core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002393 if (pointsize_written) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002394 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002395 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
2396 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
2397 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
2398 }
2399 } else if (!pointsize_written) {
2400 skip |=
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002401 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002402 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
2403 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
2404 string_VkShaderStageFlagBits(stage));
2405 }
2406 return skip;
2407}
2408
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002409bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
2410 shader_module const **out_module, spirv_inst_iter *out_entrypoint,
2411 bool check_point_size) {
Chris Forbes47567b72017-06-09 12:09:45 -07002412 bool skip = false;
Mark Lobodzinski9e9da292019-03-06 16:19:55 -07002413 auto module = *out_module = GetShaderModuleState(pStage->module);
Chris Forbes47567b72017-06-09 12:09:45 -07002414
2415 if (!module->has_valid_spirv) return false;
2416
2417 // Find the entrypoint
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002418 auto entrypoint = *out_entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
Chris Forbes47567b72017-06-09 12:09:45 -07002419 if (entrypoint == module->end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002420 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 -06002421 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
2422 pStage->pName, string_VkShaderStageFlagBits(pStage->stage))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002423 return true; // no point continuing beyond here, any analysis is just going to be garbage.
2424 }
2425 }
2426
Chris Forbes47567b72017-06-09 12:09:45 -07002427 // Mark accessible ids
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002428 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
2429 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002430
2431 // Validate descriptor set layout against what the entrypoint actually uses
Chris Forbes8af24522018-03-07 11:37:45 -08002432 bool has_writable_descriptor = false;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002433 auto descriptor_uses = CollectInterfaceByDescriptorSlot(report_data, module, accessible_ids, &has_writable_descriptor);
Chris Forbes47567b72017-06-09 12:09:45 -07002434
Chris Forbes349b3132018-03-07 11:38:08 -08002435 // Validate shader capabilities against enabled device features
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002436 skip |= ValidateShaderCapabilities(module, pStage->stage, has_writable_descriptor);
2437 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002438 skip |= ValidateExecutionModes(module, entrypoint);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002439 skip |= ValidateSpecializationOffsets(report_data, pStage);
2440 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
2441 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05002442 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002443 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002444 }
Jeff Bolze4356752019-03-07 11:23:46 -06002445 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002446
2447 // Validate descriptor use
2448 for (auto use : descriptor_uses) {
2449 // While validating shaders capture which slots are used by the pipeline
2450 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002451 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
Chris Forbes47567b72017-06-09 12:09:45 -07002452
2453 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002454 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07002455 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05002456 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07002457
2458 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002459 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 -06002460 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002461 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05002462 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002463 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002464 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 -06002465 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002466 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
2467 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05002468 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002469 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 -06002470 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002471 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05002472 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07002473 string_VkDescriptorType(binding->descriptorType));
2474 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002475 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 -06002476 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002477 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
2478 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07002479 }
2480 }
2481
2482 // Validate use of input attachments against subpass structure
2483 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002484 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07002485
Petr Krause91f7a12017-12-14 20:57:36 +01002486 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002487 auto subpass = pipeline->graphicsPipelineCI.subpass;
2488
2489 for (auto use : input_attachment_uses) {
2490 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
2491 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07002492 ? input_attachments[use.first].attachment
2493 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07002494
2495 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002496 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 -06002497 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07002498 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002499 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002500 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002501 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 -06002502 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002503 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002504 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002505 }
2506 }
2507 }
2508
2509 return skip;
2510}
2511
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002512static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, shader_module const *producer,
2513 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
2514 shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
2515 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07002516 bool skip = false;
2517
2518 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002519 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
2520 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07002521
2522 auto a_it = outputs.begin();
2523 auto b_it = inputs.begin();
2524
2525 // Maps sorted by key (location); walk them together to find mismatches
2526 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
2527 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
2528 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
2529 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
2530 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
2531
2532 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06002533 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 -06002534 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06002535 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
2536 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002537 a_it++;
2538 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06002539 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 -06002540 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06002541 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
2542 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002543 b_it++;
2544 } else {
2545 // subtleties of arrayed interfaces:
2546 // - if is_patch, then the member is not arrayed, even though the interface may be.
2547 // - if is_block_member, then the extra array level of an arrayed interface is not
2548 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002549 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
2550 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
2551 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06002552 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 -06002553 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06002554 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002555 DescribeType(producer, a_it->second.type_id).c_str(),
2556 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002557 }
2558 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06002559 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 -06002560 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002561 "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 -07002562 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
2563 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
2564 }
2565 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06002566 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 -06002567 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002568 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
2569 a_first.second, producer_stage->name, consumer_stage->name);
2570 }
2571 a_it++;
2572 b_it++;
2573 }
2574 }
2575
2576 return skip;
2577}
2578
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002579static inline uint32_t DetermineFinalGeomStage(PIPELINE_STATE *pipeline, VkGraphicsPipelineCreateInfo *pCreateInfo) {
2580 uint32_t stage_mask = 0;
2581 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2582 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2583 stage_mask |= pCreateInfo->pStages[i].stage;
2584 }
2585 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05002586 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
2587 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
2588 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002589 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
2590 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
2591 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
2592 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
2593 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002594 }
2595 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002596 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002597}
2598
Chris Forbes47567b72017-06-09 12:09:45 -07002599// Validate that the shaders used by the given pipeline and store the active_slots
2600// that are actually used by the pipeline into pPipeline->active_slots
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002601bool CoreChecks::ValidateAndCapturePipelineShaderState(PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002602 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002603 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2604 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002605
Jeff Bolz7e35c392018-09-04 15:30:41 -05002606 shader_module const *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002607 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05002608 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002609 memset(entrypoints, 0, sizeof(entrypoints));
2610 bool skip = false;
2611
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002612 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
2613
Chris Forbes47567b72017-06-09 12:09:45 -07002614 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2615 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002616 auto stage_id = GetShaderStageId(pStage->stage);
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002617 skip |= ValidatePipelineShaderStage(pStage, pipeline, &shaders[stage_id], &entrypoints[stage_id],
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002618 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07002619 }
2620
2621 // if the shader stages are no good individually, cross-stage validation is pointless.
2622 if (skip) return true;
2623
2624 auto vi = pCreateInfo->pVertexInputState;
2625
2626 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002627 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07002628 }
2629
2630 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002631 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07002632 }
2633
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002634 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2635 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002636
2637 while (!shaders[producer] && producer != fragment_stage) {
2638 producer++;
2639 consumer++;
2640 }
2641
2642 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
2643 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002644 if (shaders[consumer]) {
2645 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002646 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
2647 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
2648 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002649 }
Chris Forbes47567b72017-06-09 12:09:45 -07002650
2651 producer = consumer;
2652 }
2653 }
2654
2655 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002656 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
2657 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07002658 }
2659
2660 return skip;
2661}
2662
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002663bool CoreChecks::ValidateComputePipeline(PIPELINE_STATE *pipeline) {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002664 auto pCreateInfo = pipeline->computePipelineCI.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002665
2666 shader_module const *module;
2667 spirv_inst_iter entrypoint;
2668
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002669 return ValidatePipelineShaderStage(&pCreateInfo->stage, pipeline, &module, &entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07002670}
Chris Forbes4ae55b32017-06-09 14:42:56 -07002671
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002672bool CoreChecks::ValidateRayTracingPipelineNV(PIPELINE_STATE *pipeline) {
Jeff Bolzfbe51582018-09-13 10:01:35 -05002673 auto pCreateInfo = pipeline->raytracingPipelineCI.ptr();
2674
2675 shader_module const *module;
2676 spirv_inst_iter entrypoint;
2677
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002678 return ValidatePipelineShaderStage(pCreateInfo->pStages, pipeline, &module, &entrypoint, false);
Jeff Bolzfbe51582018-09-13 10:01:35 -05002679}
2680
Dave Houltona9df0ce2018-02-07 10:51:23 -07002681uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07002682
Dave Houltona9df0ce2018-02-07 10:51:23 -07002683static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06002684 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
2685 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06002686 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07002687 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002688 return nullptr;
2689}
2690
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002691bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2692 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002693 bool skip = false;
2694 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002695
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06002696 if (disabled.shader_validation) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002697 return false;
2698 }
2699
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06002700 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002701
2702 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07002703 skip |= 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 -06002704 "VUID-VkShaderModuleCreateInfo-pCode-01376",
2705 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
2706 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002707 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07002708 auto cache = GetValidationCacheInfo(pCreateInfo);
2709 uint32_t hash = 0;
2710 if (cache) {
2711 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002712 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07002713 }
2714
Chris Forbes4ae55b32017-06-09 14:42:56 -07002715 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06002716 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
Mark Lobodzinski96d5c6e2019-03-07 11:28:21 -07002717 if (GetApiVersion() >= VK_API_VERSION_1_1) {
Dave Houlton0ea2d012018-06-21 14:00:26 -06002718 spirv_environment = SPV_ENV_VULKAN_1_1;
2719 }
2720 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002721 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07002722 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06002723 spv_validator_options options = spvValidatorOptionsCreate();
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06002724 if (device_extensions.vk_khr_relaxed_block_layout) {
Karl Schultzfda1b382018-08-08 18:56:11 -06002725 spvValidatorOptionsSetRelaxBlockLayout(options, true);
2726 }
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06002727 if (device_extensions.vk_ext_scalar_block_layout &&
Mark Lobodzinski60e79032019-03-07 10:22:31 -07002728 GetEnabledFeatures()->scalar_block_layout_features.scalarBlockLayout == VK_TRUE) {
Tobias Hector6a0ece72018-12-10 12:24:05 +00002729 spvValidatorOptionsSetScalarBlockLayout(options, true);
2730 }
Karl Schultzfda1b382018-08-08 18:56:11 -06002731 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002732 if (spv_valid != SPV_SUCCESS) {
2733 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07002734 skip |=
2735 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
2736 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
2737 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07002738 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002739 } else {
2740 if (cache) {
2741 cache->Insert(hash);
2742 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002743 }
2744
Karl Schultzfda1b382018-08-08 18:56:11 -06002745 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002746 spvDiagnosticDestroy(diag);
2747 spvContextDestroy(ctx);
2748 }
2749
Chris Forbes4ae55b32017-06-09 14:42:56 -07002750 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07002751}
2752
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002753void CoreChecks::PreCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2754 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
2755 void *csm_state_data) {
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07002756 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06002757 if (enabled.gpu_validation) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -07002758 GpuPreCallCreateShaderModule(pCreateInfo, pAllocator, pShaderModule, &csm_state->unique_shader_id,
Mark Lobodzinski01734072019-02-13 17:39:15 -07002759 &csm_state->instrumented_create_info, &csm_state->instrumented_pgm);
2760 }
2761}
2762
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002763void CoreChecks::PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
2764 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
2765 VkResult result, void *csm_state_data) {
Mark Lobodzinski01734072019-02-13 17:39:15 -07002766 if (VK_SUCCESS != result) return;
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07002767 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinski01734072019-02-13 17:39:15 -07002768
Mark Lobodzinski96d5c6e2019-03-07 11:28:21 -07002769 spv_target_env spirv_environment = ((GetApiVersion() >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0);
Mark Lobodzinski01734072019-02-13 17:39:15 -07002770 bool is_spirv = (pCreateInfo->pCode[0] == spv::MagicNumber);
2771 std::unique_ptr<shader_module> new_shader_module(
2772 is_spirv ? new shader_module(pCreateInfo, *pShaderModule, spirv_environment, csm_state->unique_shader_id)
2773 : new shader_module());
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07002774 shaderModuleMap[*pShaderModule] = std::move(new_shader_module);
Mark Lobodzinski01734072019-02-13 17:39:15 -07002775}