blob: 236d19b100cc74291398eee5a0354c3770a96403 [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
Petr Kraus25810d02019-08-27 17:41:15 +020022#include "shader_validation.h"
23
Chris Forbes47567b72017-06-09 12:09:45 -070024#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020025#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020026#include <cinttypes>
27#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070028#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020029#include <string>
30#include <unordered_map>
31#include <vector>
32
Chris Forbes47567b72017-06-09 12:09:45 -070033#include <SPIRV/spirv.hpp>
34#include "vk_loader_platform.h"
35#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070036#include "vk_layer_data.h"
37#include "vk_layer_extension_utils.h"
38#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070039#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070040#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020041
Chris Forbes4ae55b32017-06-09 14:42:56 -070042#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070043#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070044
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080045void decoration_set::add(uint32_t decoration, uint32_t value) {
46 switch (decoration) {
47 case spv::DecorationLocation:
48 flags |= location_bit;
49 location = value;
50 break;
51 case spv::DecorationPatch:
52 flags |= patch_bit;
53 break;
54 case spv::DecorationRelaxedPrecision:
55 flags |= relaxed_precision_bit;
56 break;
57 case spv::DecorationBlock:
58 flags |= block_bit;
59 break;
60 case spv::DecorationBufferBlock:
61 flags |= buffer_block_bit;
62 break;
63 case spv::DecorationComponent:
64 flags |= component_bit;
65 component = value;
66 break;
67 case spv::DecorationInputAttachmentIndex:
68 flags |= input_attachment_index_bit;
69 input_attachment_index = value;
70 break;
71 case spv::DecorationDescriptorSet:
72 flags |= descriptor_set_bit;
73 descriptor_set = value;
74 break;
75 case spv::DecorationBinding:
76 flags |= binding_bit;
77 binding = value;
78 break;
79 case spv::DecorationNonWritable:
80 flags |= nonwritable_bit;
81 break;
82 case spv::DecorationBuiltIn:
83 flags |= builtin_bit;
84 builtin = value;
85 break;
86 }
87}
88
Chris Forbes47567b72017-06-09 12:09:45 -070089enum FORMAT_TYPE {
90 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
91 FORMAT_TYPE_SINT = 2,
92 FORMAT_TYPE_UINT = 4,
93};
94
95typedef std::pair<unsigned, unsigned> location_t;
96
Chris Forbes47567b72017-06-09 12:09:45 -070097struct shader_stage_attributes {
98 char const *const name;
99 bool arrayed_input;
100 bool arrayed_output;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200101 VkShaderStageFlags stage;
Chris Forbes47567b72017-06-09 12:09:45 -0700102};
103
104static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200105 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
106 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
107 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
108 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
109 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700110};
111
John Zulauf14c355b2019-06-27 16:09:37 -0600112unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
113
Chris Forbes47567b72017-06-09 12:09:45 -0700114// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600115void SHADER_MODULE_STATE::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -0700116 for (auto insn : *this) {
117 switch (insn.opcode()) {
118 // Types
119 case spv::OpTypeVoid:
120 case spv::OpTypeBool:
121 case spv::OpTypeInt:
122 case spv::OpTypeFloat:
123 case spv::OpTypeVector:
124 case spv::OpTypeMatrix:
125 case spv::OpTypeImage:
126 case spv::OpTypeSampler:
127 case spv::OpTypeSampledImage:
128 case spv::OpTypeArray:
129 case spv::OpTypeRuntimeArray:
130 case spv::OpTypeStruct:
131 case spv::OpTypeOpaque:
132 case spv::OpTypePointer:
133 case spv::OpTypeFunction:
134 case spv::OpTypeEvent:
135 case spv::OpTypeDeviceEvent:
136 case spv::OpTypeReserveId:
137 case spv::OpTypeQueue:
138 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600139 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600140 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700141 def_index[insn.word(1)] = insn.offset();
142 break;
143
144 // Fixed constants
145 case spv::OpConstantTrue:
146 case spv::OpConstantFalse:
147 case spv::OpConstant:
148 case spv::OpConstantComposite:
149 case spv::OpConstantSampler:
150 case spv::OpConstantNull:
151 def_index[insn.word(2)] = insn.offset();
152 break;
153
154 // Specialization constants
155 case spv::OpSpecConstantTrue:
156 case spv::OpSpecConstantFalse:
157 case spv::OpSpecConstant:
158 case spv::OpSpecConstantComposite:
159 case spv::OpSpecConstantOp:
160 def_index[insn.word(2)] = insn.offset();
161 break;
162
163 // Variables
164 case spv::OpVariable:
165 def_index[insn.word(2)] = insn.offset();
166 break;
167
168 // Functions
169 case spv::OpFunction:
170 def_index[insn.word(2)] = insn.offset();
171 break;
172
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800173 // Decorations
174 case spv::OpDecorate: {
175 auto targetId = insn.word(1);
176 decorations[targetId].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
177 } break;
178 case spv::OpGroupDecorate: {
179 auto const &src = decorations[insn.word(1)];
180 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
181 } break;
182
John Zulauf14c355b2019-06-27 16:09:37 -0600183 // Entry points ... add to the entrypoint table
184 case spv::OpEntryPoint: {
185 // Entry points do not have an id (the id is the function id) and thus need their own table
186 auto entrypoint_name = (char const *)&insn.word(3);
187 auto execution_model = insn.word(1);
188 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
189 entry_points.emplace(entrypoint_name, EntryPoint{insn.offset(), entrypoint_stage});
190 break;
191 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800192
Chris Forbes47567b72017-06-09 12:09:45 -0700193 default:
194 // We don't care about any other defs for now.
195 break;
196 }
197 }
198}
199
Jeff Bolz105d6492018-09-29 15:46:44 -0500200unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
201 switch (mode) {
202 case spv::ExecutionModelVertex:
203 return VK_SHADER_STAGE_VERTEX_BIT;
204 case spv::ExecutionModelTessellationControl:
205 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
206 case spv::ExecutionModelTessellationEvaluation:
207 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
208 case spv::ExecutionModelGeometry:
209 return VK_SHADER_STAGE_GEOMETRY_BIT;
210 case spv::ExecutionModelFragment:
211 return VK_SHADER_STAGE_FRAGMENT_BIT;
212 case spv::ExecutionModelGLCompute:
213 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600214 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700215 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600216 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700217 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600218 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700219 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600220 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700221 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600222 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700223 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600224 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700225 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500226 case spv::ExecutionModelTaskNV:
227 return VK_SHADER_STAGE_TASK_BIT_NV;
228 case spv::ExecutionModelMeshNV:
229 return VK_SHADER_STAGE_MESH_BIT_NV;
230 default:
231 return 0;
232 }
233}
234
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600235static spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600236 auto range = src->entry_points.equal_range(name);
237 for (auto it = range.first; it != range.second; ++it) {
238 if (it->second.stage == stageBits) {
239 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700240 }
241 }
Chris Forbes47567b72017-06-09 12:09:45 -0700242 return src->end();
243}
244
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600245static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700246 switch (sc) {
247 case spv::StorageClassInput:
248 return "input";
249 case spv::StorageClassOutput:
250 return "output";
251 case spv::StorageClassUniformConstant:
252 return "const uniform";
253 case spv::StorageClassUniform:
254 return "uniform";
255 case spv::StorageClassWorkgroup:
256 return "workgroup local";
257 case spv::StorageClassCrossWorkgroup:
258 return "workgroup global";
259 case spv::StorageClassPrivate:
260 return "private global";
261 case spv::StorageClassFunction:
262 return "function";
263 case spv::StorageClassGeneric:
264 return "generic";
265 case spv::StorageClassAtomicCounter:
266 return "atomic counter";
267 case spv::StorageClassImage:
268 return "image";
269 case spv::StorageClassPushConstant:
270 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800271 case spv::StorageClassStorageBuffer:
272 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700273 default:
274 return "unknown";
275 }
276}
277
278// Get the value of an integral constant
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600279unsigned GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700280 auto value = src->get_def(id);
281 assert(value != src->end());
282
283 if (value.opcode() != spv::OpConstant) {
284 // TODO: Either ensure that the specialization transform is already performed on a module we're
285 // considering here, OR -- specialize on the fly now.
286 return 1;
287 }
288
289 return value.word(3);
290}
291
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600292static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700293 auto insn = src->get_def(type);
294 assert(insn != src->end());
295
296 switch (insn.opcode()) {
297 case spv::OpTypeBool:
298 ss << "bool";
299 break;
300 case spv::OpTypeInt:
301 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
302 break;
303 case spv::OpTypeFloat:
304 ss << "float" << insn.word(2);
305 break;
306 case spv::OpTypeVector:
307 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600308 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700309 break;
310 case spv::OpTypeMatrix:
311 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600312 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700313 break;
314 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600315 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
316 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700317 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700318 case spv::OpTypeRuntimeArray:
319 ss << "runtime arr[] of ";
320 DescribeTypeInner(ss, src, insn.word(2));
321 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700322 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600323 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
324 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700325 break;
326 case spv::OpTypeStruct: {
327 ss << "struct of (";
328 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600329 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700330 if (i == insn.len() - 1) {
331 ss << ")";
332 } else {
333 ss << ", ";
334 }
335 }
336 break;
337 }
338 case spv::OpTypeSampler:
339 ss << "sampler";
340 break;
341 case spv::OpTypeSampledImage:
342 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600343 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700344 break;
345 case spv::OpTypeImage:
346 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
347 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600348 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500349 ss << "accelerationStruture";
350 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700351 default:
352 ss << "oddtype";
353 break;
354 }
355}
356
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600357static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700358 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600359 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700360 return ss.str();
361}
362
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600363static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700364 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
365 return type.word(2) < 64;
366}
367
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600368static bool TypesMatch(SHADER_MODULE_STATE const *a, SHADER_MODULE_STATE const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600369 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700370 // Walk two type trees together, and complain about differences
371 auto a_insn = a->get_def(a_type);
372 auto b_insn = b->get_def(b_type);
373 assert(a_insn != a->end());
374 assert(b_insn != b->end());
375
Chris Forbes062f1222018-08-21 15:34:15 -0700376 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
377
Chris Forbes47567b72017-06-09 12:09:45 -0700378 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600379 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700380 }
381
382 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
383 // 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 -0600384 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700385 }
386
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600387 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
388 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700389 }
390
391 if (a_insn.opcode() != b_insn.opcode()) {
392 return false;
393 }
394
395 if (a_insn.opcode() == spv::OpTypePointer) {
396 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600397 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700398 }
399
400 if (a_arrayed || b_arrayed) {
401 // If we havent resolved array-of-verts by here, we're not going to.
402 return false;
403 }
404
405 switch (a_insn.opcode()) {
406 case spv::OpTypeBool:
407 return true;
408 case spv::OpTypeInt:
409 // Match on width, signedness
410 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
411 case spv::OpTypeFloat:
412 // Match on width
413 return a_insn.word(2) == b_insn.word(2);
414 case spv::OpTypeVector:
415 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600416 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
417 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700418 return a_insn.word(3) >= b_insn.word(3);
419 } else {
420 return a_insn.word(3) == b_insn.word(3);
421 }
422 case spv::OpTypeMatrix:
423 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600424 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700425 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700426 case spv::OpTypeArray:
427 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
428 // 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 -0600429 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
430 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700431 case spv::OpTypeStruct:
432 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700433 {
434 if (a_insn.len() != b_insn.len()) {
435 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700436 }
Chris Forbes47567b72017-06-09 12:09:45 -0700437
Dave Houltona9df0ce2018-02-07 10:51:23 -0700438 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600439 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700440 return false;
441 }
442 }
443
444 return true;
445 }
Chris Forbes47567b72017-06-09 12:09:45 -0700446 default:
447 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
448 return false;
449 }
450}
451
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600452static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
Chris Forbes47567b72017-06-09 12:09:45 -0700453 auto it = map.find(id);
454 if (it == map.end())
455 return def;
456 else
457 return it->second;
458}
459
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600460static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700461 auto insn = src->get_def(type);
462 assert(insn != src->end());
463
464 switch (insn.opcode()) {
465 case spv::OpTypePointer:
466 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
467 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600468 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700469 case spv::OpTypeArray:
470 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600471 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700472 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600473 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700474 }
475 case spv::OpTypeMatrix:
476 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600477 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700478 case spv::OpTypeVector: {
479 auto scalar_type = src->get_def(insn.word(2));
480 auto bit_width =
481 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
482
483 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
484 return (bit_width * insn.word(3) + 127) / 128;
485 }
486 default:
487 // Everything else is just 1.
488 return 1;
489
490 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
491 }
492}
493
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600494static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200495 auto insn = src->get_def(type);
496 assert(insn != src->end());
497
498 switch (insn.opcode()) {
499 case spv::OpTypePointer:
500 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
501 // pointers around.
502 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
503 case spv::OpTypeStruct: {
504 uint32_t sum = 0;
505 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
506 sum += GetComponentsConsumedByType(src, insn.word(i), false);
507 }
508 return sum;
509 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500510 case spv::OpTypeArray:
511 if (strip_array_level) {
512 return GetComponentsConsumedByType(src, insn.word(2), false);
513 } else {
514 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200515 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200516 case spv::OpTypeMatrix:
517 // Num locations is the dimension * element size
518 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
519 case spv::OpTypeVector: {
520 auto scalar_type = src->get_def(insn.word(2));
521 auto bit_width =
522 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
523 // One component is 32-bit
524 return (bit_width * insn.word(3) + 31) / 32;
525 }
526 case spv::OpTypeFloat: {
527 auto bit_width = insn.word(2);
528 return (bit_width + 31) / 32;
529 }
530 case spv::OpTypeInt: {
531 auto bit_width = insn.word(2);
532 return (bit_width + 31) / 32;
533 }
534 case spv::OpConstant:
535 return GetComponentsConsumedByType(src, insn.word(1), false);
536 default:
537 return 0;
538 }
539}
540
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600541static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700542 switch (format) {
543 case VK_FORMAT_R64G64B64A64_SFLOAT:
544 case VK_FORMAT_R64G64B64A64_SINT:
545 case VK_FORMAT_R64G64B64A64_UINT:
546 case VK_FORMAT_R64G64B64_SFLOAT:
547 case VK_FORMAT_R64G64B64_SINT:
548 case VK_FORMAT_R64G64B64_UINT:
549 return 2;
550 default:
551 return 1;
552 }
553}
554
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600555static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700556 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
557 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
558 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
559 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700560 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
561 return FORMAT_TYPE_FLOAT;
562}
563
564// 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 -0700565// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600566static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700567 auto insn = src->get_def(type);
568 assert(insn != src->end());
569
570 switch (insn.opcode()) {
571 case spv::OpTypeInt:
572 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
573 case spv::OpTypeFloat:
574 return FORMAT_TYPE_FLOAT;
575 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700576 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700577 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700578 case spv::OpTypeRuntimeArray:
579 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600580 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700581 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600582 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700583
584 default:
585 return 0;
586 }
587}
588
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600589static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700590 uint32_t bit_pos = uint32_t(u_ffs(stage));
591 return bit_pos - 1;
592}
593
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600594static spirv_inst_iter GetStructType(SHADER_MODULE_STATE const *src, spirv_inst_iter def, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700595 while (true) {
596 if (def.opcode() == spv::OpTypePointer) {
597 def = src->get_def(def.word(3));
598 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
599 def = src->get_def(def.word(2));
600 is_array_of_verts = false;
601 } else if (def.opcode() == spv::OpTypeStruct) {
602 return def;
603 } else {
604 return src->end();
605 }
606 }
607}
608
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600609static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800610 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
611 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700612 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600613 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800614 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700615 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700616 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700617 }
618
619 std::unordered_map<unsigned, unsigned> member_components;
620 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700621 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700622
623 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
624 for (auto insn : *src) {
625 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
626 unsigned member_index = insn.word(2);
627
628 if (insn.word(3) == spv::DecorationComponent) {
629 unsigned component = insn.word(4);
630 member_components[member_index] = component;
631 }
632
633 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
634 member_relaxed_precision[member_index] = 1;
635 }
Chris Forbesa313d772017-06-13 13:59:41 -0700636
637 if (insn.word(3) == spv::DecorationPatch) {
638 member_patch[member_index] = 1;
639 }
Chris Forbes47567b72017-06-09 12:09:45 -0700640 }
641 }
642
Chris Forbesa313d772017-06-13 13:59:41 -0700643 // TODO: correctly handle location assignment from outside
644
Chris Forbes47567b72017-06-09 12:09:45 -0700645 // Second pass -- produce the output, from Location decorations
646 for (auto insn : *src) {
647 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
648 unsigned member_index = insn.word(2);
649 unsigned member_type_id = type.word(2 + member_index);
650
651 if (insn.word(3) == spv::DecorationLocation) {
652 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600653 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700654 auto component_it = member_components.find(member_index);
655 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
656 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700657 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700658
659 for (unsigned int offset = 0; offset < num_locations; offset++) {
660 interface_var v = {};
661 v.id = id;
662 // TODO: member index in interface_var too?
663 v.type_id = member_type_id;
664 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700665 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700666 v.is_block_member = true;
667 v.is_relaxed_precision = is_relaxed_precision;
668 (*out)[std::make_pair(location + offset, component)] = v;
669 }
670 }
671 }
672 }
Chris Forbesa313d772017-06-13 13:59:41 -0700673
674 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700675}
676
Ari Suonpaa696b3432019-03-11 14:02:57 +0200677static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800678 assert(entrypoint.opcode() == spv::OpEntryPoint);
679
Ari Suonpaa696b3432019-03-11 14:02:57 +0200680 std::vector<uint32_t> interfaces;
681 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
682 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
683 uint32_t word = 3;
684 while (entrypoint.word(word) & 0xff000000u) {
685 ++word;
686 }
687 ++word;
688
689 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
690
691 return interfaces;
692}
693
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600694static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600695 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700696 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
697
Chris Forbes47567b72017-06-09 12:09:45 -0700698 std::map<location_t, interface_var> out;
699
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800700 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
701 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700702 assert(insn != src->end());
703 assert(insn.opcode() == spv::OpVariable);
704
705 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800706 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700707 unsigned id = insn.word(2);
708 unsigned type = insn.word(1);
709
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800710 int location = d.location;
711 int builtin = d.builtin;
712 unsigned component = d.component;
713 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
714 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700715
Dave Houltona9df0ce2018-02-07 10:51:23 -0700716 if (builtin != -1)
717 continue;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800718 else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700719 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
720 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600721 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700722 for (unsigned int offset = 0; offset < num_locations; offset++) {
723 interface_var v = {};
724 v.id = id;
725 v.type_id = type;
726 v.offset = offset;
727 v.is_patch = is_patch;
728 v.is_relaxed_precision = is_relaxed_precision;
729 out[std::make_pair(location + offset, component)] = v;
730 }
Chris Forbes47567b72017-06-09 12:09:45 -0700731 }
732 }
733 }
734
735 return out;
736}
737
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600738static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200739 uint32_t storageClass) {
740 std::vector<uint32_t> variables;
741 std::vector<uint32_t> builtinStructMembers;
742 std::vector<uint32_t> builtinDecorations;
743
744 for (auto insn : *src) {
745 switch (insn.opcode()) {
746 // Find all built-in member decorations
747 case spv::OpMemberDecorate:
748 if (insn.word(3) == spv::DecorationBuiltIn) {
749 builtinStructMembers.push_back(insn.word(1));
750 }
751 break;
752 // Find all built-in decorations
753 case spv::OpDecorate:
754 switch (insn.word(2)) {
755 case spv::DecorationBlock: {
756 uint32_t blockID = insn.word(1);
757 for (auto builtInBlockID : builtinStructMembers) {
758 // Check if one of the members of the block are built-in -> the block is built-in
759 if (blockID == builtInBlockID) {
760 builtinDecorations.push_back(blockID);
761 break;
762 }
763 }
764 break;
765 }
766 case spv::DecorationBuiltIn:
767 builtinDecorations.push_back(insn.word(1));
768 break;
769 default:
770 break;
771 }
772 break;
773 default:
774 break;
775 }
776 }
777
778 // Find all interface variables belonging to the entrypoint and matching the storage class
779 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
780 auto def = src->get_def(id);
781 assert(def != src->end());
782 assert(def.opcode() == spv::OpVariable);
783
784 if (def.word(3) == storageClass) variables.push_back(def.word(1));
785 }
786
787 // Find all members belonging to the builtin block selected
788 std::vector<uint32_t> builtinBlockMembers;
789 for (auto &var : variables) {
790 auto def = src->get_def(src->get_def(var).word(3));
791
792 // It could be an array of IO blocks. The element type should be the struct defining the block contents
793 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
794
795 // Now find all members belonging to the struct defining the IO block
796 if (def.opcode() == spv::OpTypeStruct) {
797 for (auto builtInID : builtinDecorations) {
798 if (builtInID == def.word(1)) {
799 for (int i = 2; i < (int)def.len(); i++)
800 builtinBlockMembers.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
801 // These shouldn't be left after replacing.
802 for (auto insn : *src) {
803 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == builtInID &&
804 insn.word(3) == spv::DecorationBuiltIn) {
805 auto structIndex = insn.word(2);
806 assert(structIndex < builtinBlockMembers.size());
807 builtinBlockMembers[structIndex] = insn.word(4);
808 }
809 }
810 }
811 }
812 }
813 }
814
815 return builtinBlockMembers;
816}
817
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600818static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600819 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700820 std::vector<std::pair<uint32_t, interface_var>> out;
821
822 for (auto insn : *src) {
823 if (insn.opcode() == spv::OpDecorate) {
824 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
825 auto attachment_index = insn.word(3);
826 auto id = insn.word(1);
827
828 if (accessible_ids.count(id)) {
829 auto def = src->get_def(id);
830 assert(def != src->end());
831
832 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600833 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700834 for (unsigned int offset = 0; offset < num_locations; offset++) {
835 interface_var v = {};
836 v.id = id;
837 v.type_id = def.word(1);
838 v.offset = offset;
839 out.emplace_back(attachment_index + offset, v);
840 }
841 }
842 }
843 }
844 }
845 }
846
847 return out;
848}
849
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600850static bool IsWritableDescriptorType(SHADER_MODULE_STATE const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800851 auto type = module->get_def(type_id);
852
853 // 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 -0700854 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
855 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700856 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800857 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700858 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800859 }
860 }
861
862 switch (type.opcode()) {
863 case spv::OpTypeImage: {
864 auto dim = type.word(3);
865 auto sampled = type.word(7);
866 return sampled == 2 && dim != spv::DimSubpassData;
867 }
868
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700869 case spv::OpTypeStruct: {
870 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800871 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800872 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800873 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
874 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700875 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800876 }
877 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700878
879 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
880 // as nonwritable.
881 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
882 }
Chris Forbes8af24522018-03-07 11:37:45 -0800883 }
884
885 return false;
886}
887
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600888static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600889 debug_report_data const *report_data, SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids,
Chris Forbes8af24522018-03-07 11:37:45 -0800890 bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700891 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
892
893 for (auto id : accessible_ids) {
894 auto insn = src->get_def(id);
895 assert(insn != src->end());
896
897 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800898 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
899 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800900 auto d = src->get_decorations(insn.word(2));
901 unsigned set = d.descriptor_set;
902 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -0700903
904 interface_var v = {};
905 v.id = insn.word(2);
906 v.type_id = insn.word(1);
907 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800908
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800909 if (!(d.flags & decoration_set::nonwritable_bit) &&
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700910 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800911 *has_writable_descriptor = true;
912 }
Chris Forbes47567b72017-06-09 12:09:45 -0700913 }
914 }
915
916 return out;
917}
918
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600919static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
Chris Forbes47567b72017-06-09 12:09:45 -0700920 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
921 // be specified only once.
922 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
923 bool skip = false;
924
925 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
926 auto desc = &vi->pVertexBindingDescriptions[i];
927 auto &binding = bindings[desc->binding];
928 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600929 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600930 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 -0600931 kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
Chris Forbes47567b72017-06-09 12:09:45 -0700932 desc->binding);
933 } else {
934 binding = desc;
935 }
936 }
937
938 return skip;
939}
940
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600941static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600942 SHADER_MODULE_STATE const *vs, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -0700943 bool skip = false;
944
Petr Kraus25810d02019-08-27 17:41:15 +0200945 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700946
947 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +0200948 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -0700949 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +0200950 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
951 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
952 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -0700953 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
954 }
955 }
956 }
957
Petr Kraus25810d02019-08-27 17:41:15 +0200958 struct AttribInputPair {
959 const VkVertexInputAttributeDescription *attrib = nullptr;
960 const interface_var *input = nullptr;
961 };
962 std::map<uint32_t, AttribInputPair> location_map;
963 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
964 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -0700965
Petr Kraus25810d02019-08-27 17:41:15 +0200966 for (const auto location_it : location_map) {
967 const auto location = location_it.first;
968 const auto attrib = location_it.second.attrib;
969 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600970
Petr Kraus25810d02019-08-27 17:41:15 +0200971 if (attrib && !input) {
972 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
973 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
974 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
975 } else if (!attrib && input) {
Mark Young4e919b22018-05-21 15:53:59 -0600976 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 -0600977 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Petr Kraus25810d02019-08-27 17:41:15 +0200978 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
979 } else if (attrib && input) {
980 const auto attrib_type = GetFormatType(attrib->format);
981 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700982
983 // Type checking
984 if (!(attrib_type & input_type)) {
Mark Young4e919b22018-05-21 15:53:59 -0600985 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 -0600986 HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Petr Kraus25810d02019-08-27 17:41:15 +0200987 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
988 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700989 }
Petr Kraus25810d02019-08-27 17:41:15 +0200990 } else { // !attrib && !input
991 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -0700992 }
993 }
994
995 return skip;
996}
997
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600998static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, SHADER_MODULE_STATE const *fs,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600999 spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
Petr Kraus25810d02019-08-27 17:41:15 +02001000 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001001
Petr Kraus25810d02019-08-27 17:41:15 +02001002 const auto rpci = pipeline->rp_state->createInfo.ptr();
1003
1004 std::map<uint32_t, const VkAttachmentDescription2KHR *> color_attachments;
1005 const auto subpass = rpci->pSubpasses[subpass_index];
1006 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
1007 const uint32_t attachment = subpass.pColorAttachments[i].attachment;
1008 if (attachment != VK_ATTACHMENT_UNUSED && rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
1009 color_attachments[i] = &rpci->pAttachments[attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001010 }
1011 }
1012
Chris Forbes47567b72017-06-09 12:09:45 -07001013 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1014
Petr Kraus25810d02019-08-27 17:41:15 +02001015 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001016
Petr Kraus25810d02019-08-27 17:41:15 +02001017 struct AttachmentOutputPair {
1018 const VkAttachmentDescription2KHR *attachment = nullptr;
1019 const interface_var *output = nullptr;
1020 };
1021 std::map<uint32_t, AttachmentOutputPair> location_map;
1022 for (const auto &attachment_it : color_attachments) location_map[attachment_it.first].attachment = attachment_it.second;
1023 for (const auto &output_it : outputs) location_map[output_it.first.first].output = &output_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001024
Petr Kraus25810d02019-08-27 17:41:15 +02001025 const bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1026 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001027
Petr Kraus25810d02019-08-27 17:41:15 +02001028 for (const auto location_it : location_map) {
1029 const auto location = location_it.first;
1030 const auto attachment = location_it.second.attachment;
1031 const auto output = location_it.second.output;
Chris Forbes47567b72017-06-09 12:09:45 -07001032
Petr Kraus25810d02019-08-27 17:41:15 +02001033 if (attachment && !output) {
1034 if (pipeline->attachments[location].colorWriteMask != 0) {
1035 skip |=
1036 log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1037 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
1038 "Attachment %" PRIu32 " not written by fragment shader; undefined values will be written to attachment",
1039 location);
1040 }
1041 } else if (!attachment && output) {
1042 if (!(alphaToCoverageEnabled && location == 0)) {
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001043 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1044 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Petr Kraus25810d02019-08-27 17:41:15 +02001045 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001046 }
Petr Kraus25810d02019-08-27 17:41:15 +02001047 } else if (attachment && output) {
1048 const auto attachment_type = GetFormatType(attachment->format);
1049 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001050
1051 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001052 if (!(output_type & attachment_type)) {
1053 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1054 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
1055 "Attachment %" PRIu32
1056 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1057 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001058 }
Petr Kraus25810d02019-08-27 17:41:15 +02001059 } else { // !attachment && !output
1060 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001061 }
1062 }
1063
Petr Kraus25810d02019-08-27 17:41:15 +02001064 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
1065 bool locationZeroHasAlpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1066 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001067 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
1068 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
1069 HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1070 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
1071 }
1072
Chris Forbes47567b72017-06-09 12:09:45 -07001073 return skip;
1074}
1075
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001076// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1077// This function examines instructions in the static call tree for a write to this variable.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001078static bool IsPointSizeWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001079 auto type = builtin_instr.opcode();
1080 uint32_t target_id = builtin_instr.word(1);
1081 bool init_complete = false;
1082
1083 if (type == spv::OpMemberDecorate) {
1084 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1085 auto insn = entrypoint;
1086 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1087 switch (insn.opcode()) {
1088 case spv::OpTypePointer:
1089 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1090 target_id = insn.word(1);
1091 }
1092 break;
1093 case spv::OpVariable:
1094 if (insn.word(1) == target_id) {
1095 target_id = insn.word(2);
1096 init_complete = true;
1097 }
1098 break;
1099 }
1100 insn++;
1101 }
1102 }
1103
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001104 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1105
1106 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001107 std::unordered_set<uint32_t> worklist;
1108 worklist.insert(entrypoint.word(2));
1109
1110 // Follow instructions in call graph looking for writes to target
1111 while (!worklist.empty() && !found_write) {
1112 auto id_iter = worklist.begin();
1113 auto id = *id_iter;
1114 worklist.erase(id_iter);
1115
1116 auto insn = src->get_def(id);
1117 if (insn == src->end()) {
1118 continue;
1119 }
1120
1121 if (insn.opcode() == spv::OpFunction) {
1122 // Scan body of function looking for other function calls or items in our ID chain
1123 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1124 switch (insn.opcode()) {
1125 case spv::OpAccessChain:
1126 if (insn.word(3) == target_id) {
1127 if (type == spv::OpMemberDecorate) {
1128 auto value = GetConstantValue(src, insn.word(4));
1129 if (value == builtin_instr.word(2)) {
1130 target_id = insn.word(2);
1131 }
1132 } else {
1133 target_id = insn.word(2);
1134 }
1135 }
1136 break;
1137 case spv::OpStore:
1138 if (insn.word(1) == target_id) {
1139 found_write = true;
1140 }
1141 break;
1142 case spv::OpFunctionCall:
1143 worklist.insert(insn.word(3));
1144 break;
1145 }
1146 }
1147 }
1148 }
1149 return found_write;
1150}
1151
Chris Forbes47567b72017-06-09 12:09:45 -07001152// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1153// important for identifying the set of shader resources actually used by an entrypoint, for example.
1154// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1155// - NOT the shader input/output interfaces.
1156//
1157// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1158// converting parts of this to be generated from the machine-readable spec instead.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001159static std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001160 std::unordered_set<uint32_t> ids;
1161 std::unordered_set<uint32_t> worklist;
1162 worklist.insert(entrypoint.word(2));
1163
1164 while (!worklist.empty()) {
1165 auto id_iter = worklist.begin();
1166 auto id = *id_iter;
1167 worklist.erase(id_iter);
1168
1169 auto insn = src->get_def(id);
1170 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001171 // 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 -07001172 // that we may not care about.
1173 continue;
1174 }
1175
1176 // Try to add to the output set
1177 if (!ids.insert(id).second) {
1178 continue; // If we already saw this id, we don't want to walk it again.
1179 }
1180
1181 switch (insn.opcode()) {
1182 case spv::OpFunction:
1183 // Scan whole body of the function, enlisting anything interesting
1184 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1185 switch (insn.opcode()) {
1186 case spv::OpLoad:
1187 case spv::OpAtomicLoad:
1188 case spv::OpAtomicExchange:
1189 case spv::OpAtomicCompareExchange:
1190 case spv::OpAtomicCompareExchangeWeak:
1191 case spv::OpAtomicIIncrement:
1192 case spv::OpAtomicIDecrement:
1193 case spv::OpAtomicIAdd:
1194 case spv::OpAtomicISub:
1195 case spv::OpAtomicSMin:
1196 case spv::OpAtomicUMin:
1197 case spv::OpAtomicSMax:
1198 case spv::OpAtomicUMax:
1199 case spv::OpAtomicAnd:
1200 case spv::OpAtomicOr:
1201 case spv::OpAtomicXor:
1202 worklist.insert(insn.word(3)); // ptr
1203 break;
1204 case spv::OpStore:
1205 case spv::OpAtomicStore:
1206 worklist.insert(insn.word(1)); // ptr
1207 break;
1208 case spv::OpAccessChain:
1209 case spv::OpInBoundsAccessChain:
1210 worklist.insert(insn.word(3)); // base ptr
1211 break;
1212 case spv::OpSampledImage:
1213 case spv::OpImageSampleImplicitLod:
1214 case spv::OpImageSampleExplicitLod:
1215 case spv::OpImageSampleDrefImplicitLod:
1216 case spv::OpImageSampleDrefExplicitLod:
1217 case spv::OpImageSampleProjImplicitLod:
1218 case spv::OpImageSampleProjExplicitLod:
1219 case spv::OpImageSampleProjDrefImplicitLod:
1220 case spv::OpImageSampleProjDrefExplicitLod:
1221 case spv::OpImageFetch:
1222 case spv::OpImageGather:
1223 case spv::OpImageDrefGather:
1224 case spv::OpImageRead:
1225 case spv::OpImage:
1226 case spv::OpImageQueryFormat:
1227 case spv::OpImageQueryOrder:
1228 case spv::OpImageQuerySizeLod:
1229 case spv::OpImageQuerySize:
1230 case spv::OpImageQueryLod:
1231 case spv::OpImageQueryLevels:
1232 case spv::OpImageQuerySamples:
1233 case spv::OpImageSparseSampleImplicitLod:
1234 case spv::OpImageSparseSampleExplicitLod:
1235 case spv::OpImageSparseSampleDrefImplicitLod:
1236 case spv::OpImageSparseSampleDrefExplicitLod:
1237 case spv::OpImageSparseSampleProjImplicitLod:
1238 case spv::OpImageSparseSampleProjExplicitLod:
1239 case spv::OpImageSparseSampleProjDrefImplicitLod:
1240 case spv::OpImageSparseSampleProjDrefExplicitLod:
1241 case spv::OpImageSparseFetch:
1242 case spv::OpImageSparseGather:
1243 case spv::OpImageSparseDrefGather:
1244 case spv::OpImageTexelPointer:
1245 worklist.insert(insn.word(3)); // Image or sampled image
1246 break;
1247 case spv::OpImageWrite:
1248 worklist.insert(insn.word(1)); // Image -- different operand order to above
1249 break;
1250 case spv::OpFunctionCall:
1251 for (uint32_t i = 3; i < insn.len(); i++) {
1252 worklist.insert(insn.word(i)); // fn itself, and all args
1253 }
1254 break;
1255
1256 case spv::OpExtInst:
1257 for (uint32_t i = 5; i < insn.len(); i++) {
1258 worklist.insert(insn.word(i)); // Operands to ext inst
1259 }
1260 break;
1261 }
1262 }
1263 break;
1264 }
1265 }
1266
1267 return ids;
1268}
1269
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001270static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
1271 std::vector<VkPushConstantRange> const *push_constant_ranges,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001272 SHADER_MODULE_STATE const *src, spirv_inst_iter type,
1273 VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001274 bool skip = false;
1275
1276 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001277 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001278 assert(type != src->end());
1279
1280 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1281 // TODO: arrays, matrices, weird sizes
1282 for (auto insn : *src) {
1283 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1284 if (insn.word(3) == spv::DecorationOffset) {
1285 unsigned offset = insn.word(4);
1286 auto size = 4; // Bytes; TODO: calculate this based on the type
1287
1288 bool found_range = false;
1289 for (auto const &range : *push_constant_ranges) {
1290 if (range.offset <= offset && range.offset + range.size >= offset + size) {
1291 found_range = true;
1292
1293 if ((range.stageFlags & stage) == 0) {
Dave Houltona9df0ce2018-02-07 10:51:23 -07001294 skip |=
1295 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 -06001296 kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001297 "Push constant range covering variable starting at offset %u not accessible from stage %s",
1298 offset, string_VkShaderStageFlagBits(stage));
Chris Forbes47567b72017-06-09 12:09:45 -07001299 }
1300
1301 break;
1302 }
1303 }
1304
1305 if (!found_range) {
1306 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 -06001307 kVUID_Core_Shader_PushConstantOutOfRange,
Dave Houltona9df0ce2018-02-07 10:51:23 -07001308 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001309 }
1310 }
1311 }
1312 }
1313
1314 return skip;
1315}
1316
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001317static bool ValidatePushConstantUsage(debug_report_data const *report_data,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001318 std::vector<VkPushConstantRange> const *push_constant_ranges, SHADER_MODULE_STATE const *src,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001319 std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07001320 bool skip = false;
1321
1322 for (auto id : accessible_ids) {
1323 auto def_insn = src->get_def(id);
1324 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001325 skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
1326 stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001327 }
1328 }
1329
1330 return skip;
1331}
1332
1333// Validate that data for each specialization entry is fully contained within the buffer.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001334static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
Chris Forbes47567b72017-06-09 12:09:45 -07001335 bool skip = false;
1336
1337 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1338
1339 if (spec) {
1340 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Dave Houlton78d09922018-05-17 15:48:45 -06001341 // TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
Chris Forbes47567b72017-06-09 12:09:45 -07001342 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001343 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 -06001344 "VUID-VkSpecializationInfo-pMapEntries-00774",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001345 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001346 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
Dave Houltona9df0ce2018-02-07 10:51:23 -07001347 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
Mark Lobodzinski487a0d12018-03-30 10:09:03 -06001348 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001349 }
1350 }
1351 }
1352
1353 return skip;
1354}
1355
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001356// TODO (jbolz): Can this return a const reference?
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001357static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001358 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001359 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001360 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001361 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001362
1363 // 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 -05001364 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1365 if (type.opcode() == spv::OpTypeRuntimeArray) {
1366 descriptor_count = 0;
1367 type = module->get_def(type.word(2));
1368 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001369 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001370 type = module->get_def(type.word(2));
1371 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001372 if (type.word(2) == spv::StorageClassStorageBuffer) {
1373 is_storage_buffer = true;
1374 }
Chris Forbes47567b72017-06-09 12:09:45 -07001375 type = module->get_def(type.word(3));
1376 }
1377 }
1378
1379 switch (type.opcode()) {
1380 case spv::OpTypeStruct: {
1381 for (auto insn : *module) {
1382 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1383 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001384 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001385 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1386 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1387 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001388 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001389 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1390 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1391 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1392 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001393 }
Chris Forbes47567b72017-06-09 12:09:45 -07001394 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001395 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1396 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1397 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001398 }
1399 }
1400 }
1401
1402 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001403 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001404 }
1405
1406 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001407 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1408 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1409 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001410
Chris Forbes73c00bf2018-06-22 16:28:06 -07001411 case spv::OpTypeSampledImage: {
1412 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1413 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1414 auto image_type = module->get_def(type.word(2));
1415 auto dim = image_type.word(3);
1416 auto sampled = image_type.word(7);
1417 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001418 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1419 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001420 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001421 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001422 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1423 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001424
1425 case spv::OpTypeImage: {
1426 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1427 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1428 auto dim = type.word(3);
1429 auto sampled = type.word(7);
1430
1431 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001432 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1433 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001434 } else if (dim == spv::DimBuffer) {
1435 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001436 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1437 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001438 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001439 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1440 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001441 }
1442 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001443 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1444 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1445 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001446 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001447 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1448 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001449 }
1450 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001451 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001452 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001453 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001454
1455 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1456 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001457 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001458 }
1459}
1460
Jeff Bolze54ae892018-09-08 12:16:29 -05001461static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001462 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001463 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1464 if (ss.tellp()) ss << ", ";
1465 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001466 }
1467 return ss.str();
1468}
1469
Jeff Bolzee743412019-06-20 22:24:32 -05001470static bool RequirePropertyFlag(debug_report_data const *report_data, VkBool32 check, char const *flag, char const *structure) {
1471 if (!check) {
1472 if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1473 kVUID_Core_Shader_ExceedDeviceLimit, "Shader requires flag %s set in %s but it is not set on the device", flag,
1474 structure)) {
1475 return true;
1476 }
1477 }
1478
1479 return false;
1480}
1481
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001482static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001483 if (!feature) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001484 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 -06001485 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001486 return true;
1487 }
1488 }
1489
1490 return false;
1491}
1492
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001493static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
Chris Forbes47567b72017-06-09 12:09:45 -07001494 if (!extension) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06001495 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 -06001496 kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
Chris Forbes47567b72017-06-09 12:09:45 -07001497 extension_name)) {
1498 return true;
1499 }
1500 }
1501
1502 return false;
1503}
1504
John Zulaufac4c6e12019-07-01 16:05:58 -06001505bool CoreChecks::ValidateShaderCapabilities(SHADER_MODULE_STATE const *src, VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001506 bool skip = false;
1507
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001508 struct FeaturePointer {
1509 // Callable object to test if this feature is enabled in the given aggregate feature struct
1510 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1511
1512 // Test if feature pointer is populated
1513 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1514
1515 // Default and nullptr constructor to create an empty FeaturePointer
1516 FeaturePointer() : IsEnabled(nullptr) {}
1517 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1518
1519 // Constructors to populate FeaturePointer based on given pointer to member
1520 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1521 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
1522 FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
1523 : IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
1524 FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
1525 : IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001526 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1527 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001528 FeaturePointer(VkBool32 VkPhysicalDeviceFloat16Int8FeaturesKHR::*ptr)
1529 : IsEnabled([=](const DeviceFeatures &features) { return features.float16_int8.*ptr; }) {}
Tobias Hector6a0ece72018-12-10 12:24:05 +00001530 FeaturePointer(VkBool32 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT::*ptr)
1531 : IsEnabled([=](const DeviceFeatures &features) { return features.scalar_block_layout_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06001532 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
1533 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001534 FeaturePointer(VkBool32 VkPhysicalDeviceFloatControlsPropertiesKHR::*ptr)
1535 : IsEnabled([=](const DeviceFeatures &features) { return features.float_controls.*ptr; }) {}
Graeme Leese9b6a1522019-06-07 20:49:45 +01001536 FeaturePointer(VkBool32 VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR::*ptr)
1537 : IsEnabled([=](const DeviceFeatures &features) { return features.uniform_buffer_standard_layout.*ptr; }) {}
Jason Macnakc5a621d2019-06-10 12:42:50 -07001538 FeaturePointer(VkBool32 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::*ptr)
1539 : IsEnabled([=](const DeviceFeatures &features) { return features.compute_shader_derivatives_features.*ptr; }) {}
Jason Macnak325e8b52019-06-10 13:33:10 -07001540 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::*ptr)
1541 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_barycentric_features.*ptr; }) {}
Jason Macnakd7fddf82019-06-13 09:52:49 -07001542 FeaturePointer(VkBool32 VkPhysicalDeviceShaderImageFootprintFeaturesNV::*ptr)
1543 : IsEnabled([=](const DeviceFeatures &features) { return features.shader_image_footprint_features.*ptr; }) {}
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001544 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::*ptr)
1545 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_interlock_features.*ptr; }) {}
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001546 FeaturePointer(VkBool32 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::*ptr)
1547 : IsEnabled([=](const DeviceFeatures &features) { return features.demote_to_helper_invocation_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001548 };
1549
Chris Forbes47567b72017-06-09 12:09:45 -07001550 struct CapabilityInfo {
1551 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001552 FeaturePointer feature;
1553 bool DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001554 };
1555
Chris Forbes47567b72017-06-09 12:09:45 -07001556 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001557 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001558 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1559 // feature bits.
1560 {spv::CapabilityMatrix, {nullptr}},
1561 {spv::CapabilityShader, {nullptr}},
1562 {spv::CapabilityInputAttachment, {nullptr}},
1563 {spv::CapabilitySampled1D, {nullptr}},
1564 {spv::CapabilityImage1D, {nullptr}},
1565 {spv::CapabilitySampledBuffer, {nullptr}},
Toni Merilehtib13a4a22019-05-21 12:58:44 +03001566 {spv::CapabilityStorageImageExtendedFormats, {nullptr}},
Chris Forbes47567b72017-06-09 12:09:45 -07001567 {spv::CapabilityImageQuery, {nullptr}},
1568 {spv::CapabilityDerivativeControl, {nullptr}},
1569
1570 // Capabilities that are optionally supported, but require a feature to
1571 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001572 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1573 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1574 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1575 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1576 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1577 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1578 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1579 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1580 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1581 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1582 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1583 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1584 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1585 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1586 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1587 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1588 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1589 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1590 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1591 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001592 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1593 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1594 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1595 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001596
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001597 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
1598 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
1599 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
1600 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
1601 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
1602 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
1603 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
1604 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
1605 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
1606 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
1607 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
Jason Macnakf7019582019-06-13 10:07:26 -07001608 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001609
1610 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001611 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1612 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1613 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1614 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1615 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1616 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1617 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1618 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Jason Macnakb7d091c2019-06-10 11:13:11 -07001619 {spv::CapabilityGroupNonUniformPartitionedNV, {VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_shader_subgroup_partitioned}},
aqnuep7033c702018-09-11 18:03:29 +02001620 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001621
Jason Macnakc5a621d2019-06-10 12:42:50 -07001622 {spv::CapabilityComputeDerivativeGroupQuadsNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
1623 {spv::CapabilityComputeDerivativeGroupLinearNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
Jason Macnakf7019582019-06-13 10:07:26 -07001624 {spv::CapabilityFragmentBarycentricNV, {"VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric", &VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric, &DeviceExtensions::vk_nv_fragment_shader_barycentric}},
Jason Macnakc5a621d2019-06-10 12:42:50 -07001625
Jason Macnakf7019582019-06-13 10:07:26 -07001626 {spv::CapabilityStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1627 {spv::CapabilityUniformAndStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1628 {spv::CapabilityStoragePushConstant8, {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001629
Jason Macnakf7019582019-06-13 10:07:26 -07001630 {spv::CapabilityTransformFeedback, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
1631 {spv::CapabilityGeometryStreams, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001632
Jason Macnakf7019582019-06-13 10:07:26 -07001633 {spv::CapabilityFloat16, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1634 {spv::CapabilityInt8, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06001635
Jason Macnakd7fddf82019-06-13 09:52:49 -07001636 {spv::CapabilityImageFootprintNV, {"VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint", &VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint, &DeviceExtensions::vk_nv_shader_image_footprint}},
1637
Jeff Bolze4356752019-03-07 11:23:46 -06001638 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001639
1640 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1641 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1642 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1643 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1644 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1645 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1646 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1647 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1648 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1649 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1650 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1651 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
1652 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
1653 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
1654 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001655
1656 {spv::CapabilityFragmentShaderSampleInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1657 {spv::CapabilityFragmentShaderPixelInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1658 {spv::CapabilityFragmentShaderShadingRateInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001659 {spv::CapabilityDemoteToHelperInvocationEXT, {"VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation", &VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation, &DeviceExtensions::vk_ext_shader_demote_to_helper_invocation}},
Chris Forbes47567b72017-06-09 12:09:45 -07001660 };
1661 // clang-format on
1662
1663 for (auto insn : *src) {
1664 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001665 size_t n = capabilities.count(insn.word(1));
1666 if (1 == n) { // key occurs exactly once
1667 auto it = capabilities.find(insn.word(1));
1668 if (it != capabilities.end()) {
1669 if (it->second.feature) {
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001670 skip |= RequireFeature(report_data, it->second.feature.IsEnabled(enabled_features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001671 }
1672 if (it->second.extension) {
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001673 skip |= RequireExtension(report_data, device_extensions.*(it->second.extension), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001674 }
Chris Forbes47567b72017-06-09 12:09:45 -07001675 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001676 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1677 bool needs_feature = false, has_feature = false;
1678 bool needs_ext = false, has_ext = false;
1679 std::string feature_names = "(one of) [ ";
1680 std::string extension_names = feature_names;
1681 auto caps = capabilities.equal_range(insn.word(1));
1682 for (auto it = caps.first; it != caps.second; ++it) {
1683 if (it->second.feature) {
1684 needs_feature = true;
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001685 has_feature = has_feature || it->second.feature.IsEnabled(enabled_features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001686 feature_names += it->second.name;
1687 feature_names += " ";
1688 }
1689 if (it->second.extension) {
1690 needs_ext = true;
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001691 has_ext = has_ext || device_extensions.*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001692 extension_names += it->second.name;
1693 extension_names += " ";
1694 }
1695 }
1696 if (needs_feature) {
1697 feature_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001698 skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001699 }
1700 if (needs_ext) {
1701 extension_names += "]";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001702 skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001703 }
Jeff Bolzee743412019-06-20 22:24:32 -05001704 } else { // Do group non-uniform checks
1705 const VkSubgroupFeatureFlags supportedOperations = phys_dev_ext_props.subgroup_props.supportedOperations;
1706 const VkSubgroupFeatureFlags supportedStages = phys_dev_ext_props.subgroup_props.supportedStages;
1707
1708 switch (insn.word(1)) {
1709 default:
1710 break;
1711 case spv::CapabilityGroupNonUniform:
1712 case spv::CapabilityGroupNonUniformVote:
1713 case spv::CapabilityGroupNonUniformArithmetic:
1714 case spv::CapabilityGroupNonUniformBallot:
1715 case spv::CapabilityGroupNonUniformShuffle:
1716 case spv::CapabilityGroupNonUniformShuffleRelative:
1717 case spv::CapabilityGroupNonUniformClustered:
1718 case spv::CapabilityGroupNonUniformQuad:
1719 case spv::CapabilityGroupNonUniformPartitionedNV:
1720 RequirePropertyFlag(report_data, supportedStages & stage, string_VkShaderStageFlagBits(stage),
1721 "VkPhysicalDeviceSubgroupProperties::supportedStages");
1722 break;
1723 }
1724
1725 switch (insn.word(1)) {
1726 default:
1727 break;
1728 case spv::CapabilityGroupNonUniform:
1729 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT,
1730 "VK_SUBGROUP_FEATURE_BASIC_BIT",
1731 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1732 break;
1733 case spv::CapabilityGroupNonUniformVote:
1734 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT,
1735 "VK_SUBGROUP_FEATURE_VOTE_BIT",
1736 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1737 break;
1738 case spv::CapabilityGroupNonUniformArithmetic:
1739 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,
1740 "VK_SUBGROUP_FEATURE_ARITHMETIC_BIT",
1741 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1742 break;
1743 case spv::CapabilityGroupNonUniformBallot:
1744 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT,
1745 "VK_SUBGROUP_FEATURE_BALLOT_BIT",
1746 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1747 break;
1748 case spv::CapabilityGroupNonUniformShuffle:
1749 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT,
1750 "VK_SUBGROUP_FEATURE_SHUFFLE_BIT",
1751 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1752 break;
1753 case spv::CapabilityGroupNonUniformShuffleRelative:
1754 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,
1755 "VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT",
1756 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1757 break;
1758 case spv::CapabilityGroupNonUniformClustered:
1759 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT,
1760 "VK_SUBGROUP_FEATURE_CLUSTERED_BIT",
1761 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1762 break;
1763 case spv::CapabilityGroupNonUniformQuad:
1764 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT,
1765 "VK_SUBGROUP_FEATURE_QUAD_BIT",
1766 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1767 break;
1768 case spv::CapabilityGroupNonUniformPartitionedNV:
1769 RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV,
1770 "VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV",
1771 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1772 break;
1773 }
Chris Forbes47567b72017-06-09 12:09:45 -07001774 }
1775 }
1776 }
1777
Jeff Bolzee743412019-06-20 22:24:32 -05001778 return skip;
1779}
1780
John Zulaufac4c6e12019-07-01 16:05:58 -06001781bool CoreChecks::ValidateShaderStageWritableDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001782 bool skip = false;
1783
Chris Forbes349b3132018-03-07 11:38:08 -08001784 if (has_writable_descriptor) {
1785 switch (stage) {
1786 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06001787 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1788 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1789 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1790 case VK_SHADER_STAGE_MISS_BIT_NV:
1791 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1792 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1793 case VK_SHADER_STAGE_TASK_BIT_NV:
1794 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08001795 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06001796 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08001797 break;
1798 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001799 skip |= RequireFeature(report_data, enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001800 break;
1801 default:
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001802 skip |= RequireFeature(report_data, enabled_features.core.vertexPipelineStoresAndAtomics,
1803 "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001804 break;
1805 }
1806 }
1807
Chris Forbes47567b72017-06-09 12:09:45 -07001808 return skip;
1809}
1810
Jeff Bolzee743412019-06-20 22:24:32 -05001811bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
John Zulaufac4c6e12019-07-01 16:05:58 -06001812 std::unordered_set<uint32_t> const &accessible_ids) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001813 bool skip = false;
1814
1815 auto const subgroup_props = phys_dev_ext_props.subgroup_props;
1816
1817 for (uint32_t id : accessible_ids) {
1818 auto inst = module->get_def(id);
1819
1820 // Check the quad operations.
1821 switch (inst.opcode()) {
1822 default:
1823 break;
1824 case spv::OpGroupNonUniformQuadBroadcast:
1825 case spv::OpGroupNonUniformQuadSwap:
1826 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
1827 skip |= RequireFeature(report_data, subgroup_props.quadOperationsInAllStages,
1828 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages");
1829 }
1830 break;
1831 }
1832 }
1833
1834 return skip;
1835}
1836
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001837bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06001838 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001839 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
1840 pStage->stage == VK_SHADER_STAGE_ALL) {
1841 return false;
1842 }
1843
1844 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001845 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001846
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001847 std::set<uint32_t> patchIDs;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001848 struct Variable {
1849 uint32_t baseTypePtrID;
1850 uint32_t ID;
1851 uint32_t storageClass;
1852 };
1853 std::vector<Variable> variables;
1854
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001855 uint32_t numVertices = 0;
1856
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001857 for (auto insn : *src) {
1858 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001859 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001860 case spv::OpDecorate:
1861 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001862 case spv::DecorationPatch: {
1863 patchIDs.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001864 break;
1865 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001866 default:
1867 break;
1868 }
1869 break;
1870 // Find all input and output variables
1871 case spv::OpVariable: {
1872 Variable var = {};
1873 var.storageClass = insn.word(3);
1874 if (var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) {
1875 var.baseTypePtrID = insn.word(1);
1876 var.ID = insn.word(2);
1877 variables.push_back(var);
1878 }
1879 break;
1880 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001881 case spv::OpExecutionMode:
1882 if (insn.word(1) == entrypoint.word(2)) {
1883 switch (insn.word(2)) {
1884 default:
1885 break;
1886 case spv::ExecutionModeOutputVertices:
1887 numVertices = insn.word(3);
1888 break;
1889 }
1890 }
1891 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001892 default:
1893 break;
1894 }
1895 }
1896
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001897 bool strip_output_array_level =
1898 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
1899 bool strip_input_array_level =
1900 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
1901 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
1902
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001903 uint32_t numCompIn = 0, numCompOut = 0;
1904 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001905 // Check if the variable is a patch. Patches can also be members of blocks,
1906 // but if they are then the top-level arrayness has already been stripped
1907 // by the time GetComponentsConsumedByType gets to it.
1908 bool isPatch = patchIDs.find(var.ID) != patchIDs.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001909
1910 if (var.storageClass == spv::StorageClassInput) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001911 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001912 } else { // var.storageClass == spv::StorageClassOutput
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001913 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001914 }
1915 }
1916
1917 switch (pStage->stage) {
1918 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001919 if (numCompOut > limits.maxVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001920 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1921 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1922 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
1923 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
1924 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001925 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001926 }
1927 break;
1928
1929 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001930 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001931 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1932 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1933 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1934 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
1935 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001936 limits.maxTessellationControlPerVertexInputComponents,
1937 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001938 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001939 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001940 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1941 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1942 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
1943 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
1944 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001945 limits.maxTessellationControlPerVertexOutputComponents,
1946 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001947 }
1948 break;
1949
1950 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001951 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001952 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1953 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1954 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1955 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
1956 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001957 limits.maxTessellationEvaluationInputComponents,
1958 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001959 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001960 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001961 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1962 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1963 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
1964 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
1965 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001966 limits.maxTessellationEvaluationOutputComponents,
1967 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001968 }
1969 break;
1970
1971 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001972 if (numCompIn > limits.maxGeometryInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001973 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1974 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1975 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1976 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
1977 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001978 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001979 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001980 if (numCompOut > limits.maxGeometryOutputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001981 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1982 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1983 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1984 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
1985 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001986 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001987 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001988 if (numCompOut * numVertices > limits.maxGeometryTotalOutputComponents) {
1989 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
1990 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
1991 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
1992 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
1993 "components by %u components",
1994 limits.maxGeometryTotalOutputComponents,
1995 numCompOut * numVertices - limits.maxGeometryTotalOutputComponents);
1996 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001997 break;
1998
1999 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002000 if (numCompIn > limits.maxFragmentInputComponents) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002001 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
2002 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
2003 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2004 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2005 "components by %u components",
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002006 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002007 }
2008 break;
2009
Jeff Bolz148d94e2018-12-13 21:25:56 -06002010 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2011 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2012 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2013 case VK_SHADER_STAGE_MISS_BIT_NV:
2014 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2015 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2016 case VK_SHADER_STAGE_TASK_BIT_NV:
2017 case VK_SHADER_STAGE_MESH_BIT_NV:
2018 break;
2019
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002020 default:
2021 assert(false); // This should never happen
2022 }
2023 return skip;
2024}
2025
Jeff Bolze4356752019-03-07 11:23:46 -06002026// copy the specialization constant value into buf, if it is present
2027void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2028 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2029
2030 if (spec && spec_id < spec->mapEntryCount) {
2031 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2032 }
2033}
2034
2035// Fill in value with the constant or specialization constant value, if available.
2036// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002037static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002038 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2039 auto type_id = src->get_def(insn.word(1));
2040 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2041 return false;
2042 }
2043 switch (insn.opcode()) {
2044 case spv::OpSpecConstant:
2045 *value = insn.word(3);
2046 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2047 return true;
2048 case spv::OpConstant:
2049 *value = insn.word(3);
2050 return true;
2051 default:
2052 return false;
2053 }
2054}
2055
2056// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002057VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002058 switch (insn.opcode()) {
2059 case spv::OpTypeInt:
2060 switch (insn.word(2)) {
2061 case 8:
2062 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2063 case 16:
2064 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2065 case 32:
2066 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2067 case 64:
2068 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2069 default:
2070 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2071 }
2072 case spv::OpTypeFloat:
2073 switch (insn.word(2)) {
2074 case 16:
2075 return VK_COMPONENT_TYPE_FLOAT16_NV;
2076 case 32:
2077 return VK_COMPONENT_TYPE_FLOAT32_NV;
2078 case 64:
2079 return VK_COMPONENT_TYPE_FLOAT64_NV;
2080 default:
2081 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2082 }
2083 default:
2084 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2085 }
2086}
2087
2088// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2089// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002090bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002091 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002092 bool skip = false;
2093
2094 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2095 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2096 // Map SPIR-V result ID to the ID of its type.
2097 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2098
2099 struct CoopMatType {
2100 uint32_t scope, rows, cols;
2101 VkComponentTypeNV component_type;
2102 bool all_constant;
2103
2104 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2105
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002106 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002107 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2108 spirv_inst_iter insn = src->get_def(id);
2109 uint32_t component_type_id = insn.word(2);
2110 uint32_t scope_id = insn.word(3);
2111 uint32_t rows_id = insn.word(4);
2112 uint32_t cols_id = insn.word(5);
2113 auto component_type_iter = src->get_def(component_type_id);
2114 auto scope_iter = src->get_def(scope_id);
2115 auto rows_iter = src->get_def(rows_id);
2116 auto cols_iter = src->get_def(cols_id);
2117
2118 all_constant = true;
2119 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2120 all_constant = false;
2121 }
2122 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2123 all_constant = false;
2124 }
2125 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2126 all_constant = false;
2127 }
2128 component_type = GetComponentType(component_type_iter, src);
2129 }
2130 };
2131
2132 bool seen_coopmat_capability = false;
2133
2134 for (auto insn : *src) {
2135 // Whitelist instructions whose result can be a cooperative matrix type, and
2136 // keep track of their types. It would be nice if SPIRV-Headers generated code
2137 // to identify which instructions have a result type and result id. Lacking that,
2138 // this whitelist is based on the set of instructions that
2139 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2140 switch (insn.opcode()) {
2141 case spv::OpLoad:
2142 case spv::OpCooperativeMatrixLoadNV:
2143 case spv::OpCooperativeMatrixMulAddNV:
2144 case spv::OpSNegate:
2145 case spv::OpFNegate:
2146 case spv::OpIAdd:
2147 case spv::OpFAdd:
2148 case spv::OpISub:
2149 case spv::OpFSub:
2150 case spv::OpFDiv:
2151 case spv::OpSDiv:
2152 case spv::OpUDiv:
2153 case spv::OpMatrixTimesScalar:
2154 case spv::OpConstantComposite:
2155 case spv::OpCompositeConstruct:
2156 case spv::OpConvertFToU:
2157 case spv::OpConvertFToS:
2158 case spv::OpConvertSToF:
2159 case spv::OpConvertUToF:
2160 case spv::OpUConvert:
2161 case spv::OpSConvert:
2162 case spv::OpFConvert:
2163 id_to_type_id[insn.word(2)] = insn.word(1);
2164 break;
2165 default:
2166 break;
2167 }
2168
2169 switch (insn.opcode()) {
2170 case spv::OpDecorate:
2171 if (insn.word(2) == spv::DecorationSpecId) {
2172 id_to_spec_id[insn.word(1)] = insn.word(3);
2173 }
2174 break;
2175 case spv::OpCapability:
2176 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2177 seen_coopmat_capability = true;
2178
2179 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
2180 skip |=
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002181 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Jeff Bolze4356752019-03-07 11:23:46 -06002182 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2183 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2184 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
2185 }
2186 }
2187 break;
2188 case spv::OpMemoryModel:
2189 // If the capability isn't enabled, don't bother with the rest of this function.
2190 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2191 if (!seen_coopmat_capability) {
2192 return skip;
2193 }
2194 break;
2195 case spv::OpTypeCooperativeMatrixNV: {
2196 CoopMatType M;
2197 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2198
2199 if (M.all_constant) {
2200 // Validate that the type parameters are all supported for one of the
2201 // operands of a cooperative matrix property.
2202 bool valid = false;
2203 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2204 if (cooperative_matrix_properties[i].AType == M.component_type &&
2205 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2206 cooperative_matrix_properties[i].scope == M.scope) {
2207 valid = true;
2208 break;
2209 }
2210 if (cooperative_matrix_properties[i].BType == M.component_type &&
2211 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2212 cooperative_matrix_properties[i].scope == M.scope) {
2213 valid = true;
2214 break;
2215 }
2216 if (cooperative_matrix_properties[i].CType == M.component_type &&
2217 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2218 cooperative_matrix_properties[i].scope == M.scope) {
2219 valid = true;
2220 break;
2221 }
2222 if (cooperative_matrix_properties[i].DType == M.component_type &&
2223 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2224 cooperative_matrix_properties[i].scope == M.scope) {
2225 valid = true;
2226 break;
2227 }
2228 }
2229 if (!valid) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002230 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 -06002231 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixType,
2232 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2233 insn.word(1));
2234 }
2235 }
2236 break;
2237 }
2238 case spv::OpCooperativeMatrixMulAddNV: {
2239 CoopMatType A, B, C, D;
2240 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2241 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2242 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2243 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002244 // Couldn't find type of matrix
2245 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002246 break;
2247 }
2248 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2249 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2250 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2251 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2252
2253 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2254 // Validate that the type parameters are all supported for the same
2255 // cooperative matrix property.
2256 bool valid = false;
2257 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2258 if (cooperative_matrix_properties[i].AType == A.component_type &&
2259 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2260 cooperative_matrix_properties[i].scope == A.scope &&
2261
2262 cooperative_matrix_properties[i].BType == B.component_type &&
2263 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2264 cooperative_matrix_properties[i].scope == B.scope &&
2265
2266 cooperative_matrix_properties[i].CType == C.component_type &&
2267 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2268 cooperative_matrix_properties[i].scope == C.scope &&
2269
2270 cooperative_matrix_properties[i].DType == D.component_type &&
2271 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2272 cooperative_matrix_properties[i].scope == D.scope) {
2273 valid = true;
2274 break;
2275 }
2276 }
2277 if (!valid) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002278 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 -06002279 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixMulAdd,
2280 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2281 "VkCooperativeMatrixPropertiesNV",
2282 insn.word(2));
2283 }
2284 }
2285 break;
2286 }
2287 default:
2288 break;
2289 }
2290 }
2291
2292 return skip;
2293}
2294
John Zulaufac4c6e12019-07-01 16:05:58 -06002295bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002296 auto entrypoint_id = entrypoint.word(2);
2297
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002298 // The first denorm execution mode encountered, along with its bit width.
2299 // Used to check if SeparateDenormSettings is respected.
2300 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002301
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002302 // The first rounding mode encountered, along with its bit width.
2303 // Used to check if SeparateRoundingModeSettings is respected.
2304 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002305
2306 bool skip = false;
2307
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002308 uint32_t verticesOut = 0;
2309 uint32_t invocations = 0;
2310
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002311 for (auto insn : *src) {
2312 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2313 auto mode = insn.word(2);
2314 switch (mode) {
2315 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2316 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002317 if ((bit_width == 16 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat16) ||
2318 (bit_width == 32 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat32) ||
2319 (bit_width == 64 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002320 skip |=
2321 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2322 kVUID_Core_Shader_FeatureNotEnabled,
2323 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2324 bit_width);
2325 }
2326 break;
2327 }
2328
2329 case spv::ExecutionModeDenormPreserve: {
2330 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002331 if ((bit_width == 16 && !enabled_features.float_controls.shaderDenormPreserveFloat16) ||
2332 (bit_width == 32 && !enabled_features.float_controls.shaderDenormPreserveFloat32) ||
2333 (bit_width == 64 && !enabled_features.float_controls.shaderDenormPreserveFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002334 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2335 kVUID_Core_Shader_FeatureNotEnabled,
2336 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2337 bit_width);
2338 }
2339
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002340 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2341 // Register the first denorm execution mode found
2342 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002343 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
2344 switch (enabled_features.float_controls.denormBehaviorIndependence) {
2345 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2346 if (first_rounding_mode.second != 32 && bit_width != 32) {
2347 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2348 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2349 "Shader uses different denorm execution modes for 16 and 64-bit but "
2350 "denormBehaviorIndependence is "
2351 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2352 }
2353 break;
2354
2355 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2356 break;
2357
2358 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2359 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2360 0, kVUID_Core_Shader_FeatureNotEnabled,
2361 "Shader uses different denorm execution modes for different bit widths but "
2362 "denormBehaviorIndependence is "
2363 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2364 break;
2365
2366 default:
2367 break;
2368 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002369 }
2370 break;
2371 }
2372
2373 case spv::ExecutionModeDenormFlushToZero: {
2374 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002375 if ((bit_width == 16 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat16) ||
2376 (bit_width == 32 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat32) ||
2377 (bit_width == 64 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002378 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2379 kVUID_Core_Shader_FeatureNotEnabled,
2380 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2381 bit_width);
2382 }
2383
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002384 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2385 // Register the first denorm execution mode found
2386 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002387 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
2388 switch (enabled_features.float_controls.denormBehaviorIndependence) {
2389 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2390 if (first_rounding_mode.second != 32 && bit_width != 32) {
2391 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2392 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2393 "Shader uses different denorm execution modes for 16 and 64-bit but "
2394 "denormBehaviorIndependence is "
2395 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2396 }
2397 break;
2398
2399 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2400 break;
2401
2402 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2403 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2404 0, kVUID_Core_Shader_FeatureNotEnabled,
2405 "Shader uses different denorm execution modes for different bit widths but "
2406 "denormBehaviorIndependence is "
2407 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2408 break;
2409
2410 default:
2411 break;
2412 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002413 }
2414 break;
2415 }
2416
2417 case spv::ExecutionModeRoundingModeRTE: {
2418 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002419 if ((bit_width == 16 && !enabled_features.float_controls.shaderRoundingModeRTEFloat16) ||
2420 (bit_width == 32 && !enabled_features.float_controls.shaderRoundingModeRTEFloat32) ||
2421 (bit_width == 64 && !enabled_features.float_controls.shaderRoundingModeRTEFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002422 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2423 kVUID_Core_Shader_FeatureNotEnabled,
2424 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2425 bit_width);
2426 }
2427
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002428 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2429 // Register the first rounding mode found
2430 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002431 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
2432 switch (enabled_features.float_controls.roundingModeIndependence) {
2433 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2434 if (first_rounding_mode.second != 32 && bit_width != 32) {
2435 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2436 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2437 "Shader uses different rounding modes for 16 and 64-bit but "
2438 "roundingModeIndependence is "
2439 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2440 }
2441 break;
2442
2443 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2444 break;
2445
2446 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2447 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2448 0, kVUID_Core_Shader_FeatureNotEnabled,
2449 "Shader uses different rounding modes for different bit widths but "
2450 "roundingModeIndependence is "
2451 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2452 break;
2453
2454 default:
2455 break;
2456 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002457 }
2458 break;
2459 }
2460
2461 case spv::ExecutionModeRoundingModeRTZ: {
2462 auto bit_width = insn.word(3);
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002463 if ((bit_width == 16 && !enabled_features.float_controls.shaderRoundingModeRTZFloat16) ||
2464 (bit_width == 32 && !enabled_features.float_controls.shaderRoundingModeRTZFloat32) ||
2465 (bit_width == 64 && !enabled_features.float_controls.shaderRoundingModeRTZFloat64)) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002466 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2467 kVUID_Core_Shader_FeatureNotEnabled,
2468 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
2469 bit_width);
2470 }
2471
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002472 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2473 // Register the first rounding mode found
2474 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002475 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
2476 switch (enabled_features.float_controls.roundingModeIndependence) {
2477 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2478 if (first_rounding_mode.second != 32 && bit_width != 32) {
2479 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2480 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_FeatureNotEnabled,
2481 "Shader uses different rounding modes for 16 and 64-bit but "
2482 "roundingModeIndependence is "
2483 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
2484 }
2485 break;
2486
2487 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2488 break;
2489
2490 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
2491 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
2492 0, kVUID_Core_Shader_FeatureNotEnabled,
2493 "Shader uses different rounding modes for different bit widths but "
2494 "roundingModeIndependence is "
2495 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
2496 break;
2497
2498 default:
2499 break;
2500 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002501 }
2502 break;
2503 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002504
2505 case spv::ExecutionModeOutputVertices: {
2506 verticesOut = insn.word(3);
2507 break;
2508 }
2509
2510 case spv::ExecutionModeInvocations: {
2511 invocations = insn.word(3);
2512 break;
2513 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002514 }
2515 }
2516 }
2517
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002518 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
2519 if (verticesOut == 0 || verticesOut > phys_dev_props.limits.maxGeometryOutputVertices) {
2520 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2521 "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
2522 "Geometry shader entry point must have an OpExecutionMode instruction that "
2523 "specifies a maximum output vertex count that is greater than 0 and less "
2524 "than or equal to maxGeometryOutputVertices. "
2525 "OutputVertices=%d, maxGeometryOutputVertices=%d",
2526 verticesOut, phys_dev_props.limits.maxGeometryOutputVertices);
2527 }
2528
2529 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
2530 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2531 "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
2532 "Geometry shader entry point must have an OpExecutionMode instruction that "
2533 "specifies an invocation count that is greater than 0 and less "
2534 "than or equal to maxGeometryShaderInvocations. "
2535 "Invocations=%d, maxGeometryShaderInvocations=%d",
2536 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
2537 }
2538 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002539 return skip;
2540}
2541
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002542static uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07002543 auto type = module->get_def(type_id);
2544
2545 while (true) {
2546 switch (type.opcode()) {
2547 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07002548 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07002549 case spv::OpTypeSampledImage:
2550 type = module->get_def(type.word(2));
2551 break;
2552 case spv::OpTypePointer:
2553 type = module->get_def(type.word(3));
2554 break;
2555 case spv::OpTypeImage: {
2556 auto dim = type.word(3);
2557 auto arrayed = type.word(5);
2558 auto msaa = type.word(6);
2559
Chris Forbes74ba2232018-08-27 15:19:27 -07002560 uint32_t bits = 0;
2561 switch (GetFundamentalType(module, type.word(2))) {
2562 case FORMAT_TYPE_FLOAT:
2563 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
2564 break;
2565 case FORMAT_TYPE_UINT:
2566 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
2567 break;
2568 case FORMAT_TYPE_SINT:
2569 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
2570 break;
2571 default:
2572 break;
2573 }
2574
Chris Forbes47567b72017-06-09 12:09:45 -07002575 switch (dim) {
2576 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002577 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
2578 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002579 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002580 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2581 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
2582 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002583 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002584 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
2585 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002586 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07002587 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
2588 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002589 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07002590 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2591 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002592 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07002593 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002594 }
2595 }
2596 default:
2597 return 0;
2598 }
2599 }
2600}
2601
2602// For given pipelineLayout verify that the set_layout_node at slot.first
2603// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06002604static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002605 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07002606 if (!pipelineLayout) return nullptr;
2607
2608 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
2609
2610 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
2611}
2612
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002613static bool FindLocalSize(SHADER_MODULE_STATE const *src, uint32_t &local_size_x, uint32_t &local_size_y, uint32_t &local_size_z) {
Locke1ec6d952019-04-02 11:57:21 -06002614 for (auto insn : *src) {
2615 if (insn.opcode() == spv::OpEntryPoint) {
2616 auto executionModel = insn.word(1);
2617 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
2618 if (entrypointStageBits == VK_SHADER_STAGE_COMPUTE_BIT) {
2619 auto entrypoint_id = insn.word(2);
2620 for (auto insn1 : *src) {
2621 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
2622 insn1.word(2) == spv::ExecutionModeLocalSize) {
2623 local_size_x = insn1.word(3);
2624 local_size_y = insn1.word(4);
2625 local_size_z = insn1.word(5);
2626 return true;
2627 }
2628 }
2629 }
2630 }
2631 }
2632 return false;
2633}
2634
John Zulauf14c355b2019-06-27 16:09:37 -06002635static void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05002636 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07002637 bool is_point_mode = false;
2638
2639 for (auto insn : *src) {
2640 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2641 switch (insn.word(2)) {
2642 case spv::ExecutionModePointMode:
2643 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
2644 is_point_mode = true;
2645 break;
2646
2647 case spv::ExecutionModeOutputPoints:
2648 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2649 break;
2650
2651 case spv::ExecutionModeIsolines:
2652 case spv::ExecutionModeOutputLineStrip:
2653 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
2654 break;
2655
2656 case spv::ExecutionModeTriangles:
2657 case spv::ExecutionModeQuads:
2658 case spv::ExecutionModeOutputTriangleStrip:
2659 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
2660 break;
2661 }
2662 }
2663 }
2664
2665 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2666}
2667
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002668// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
2669// o If there is only a vertex shader : gl_PointSize must be written when using points
2670// o If there is a geometry or tessellation shader:
2671// - If shaderTessellationAndGeometryPointSize feature is enabled:
2672// * gl_PointSize must be written in the final geometry stage
2673// - If shaderTessellationAndGeometryPointSize feature is disabled:
2674// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002675bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06002676 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002677 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2678 return false;
2679 }
2680
2681 bool pointsize_written = false;
2682 bool skip = false;
2683
2684 // Search for PointSize built-in decorations
2685 std::vector<uint32_t> pointsize_builtin_offsets;
2686 spirv_inst_iter insn = entrypoint;
2687 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
2688 if (insn.opcode() == spv::OpMemberDecorate) {
2689 if (insn.word(3) == spv::DecorationBuiltIn) {
2690 if (insn.word(4) == spv::BuiltInPointSize) {
2691 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2692 }
2693 }
2694 } else if (insn.opcode() == spv::OpDecorate) {
2695 if (insn.word(2) == spv::DecorationBuiltIn) {
2696 if (insn.word(3) == spv::BuiltInPointSize) {
2697 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2698 }
2699 }
2700 }
2701
2702 insn++;
2703 }
2704
2705 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002706 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002707 if (pointsize_written) {
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002708 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 -06002709 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
2710 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
2711 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
2712 }
2713 } else if (!pointsize_written) {
2714 skip |=
Mark Lobodzinski93a1fa72019-04-19 12:12:25 -06002715 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002716 HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
2717 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
2718 string_VkShaderStageFlagBits(stage));
2719 }
2720 return skip;
2721}
John Zulauf14c355b2019-06-27 16:09:37 -06002722void ValidationStateTracker::RecordPipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
2723 PIPELINE_STATE::StageState *stage_state) {
2724 // Validation shouldn't rely on anything in stage state being valid if the spirv isn't
2725 auto module = GetShaderModuleState(pStage->module);
2726 if (!module->has_valid_spirv) return;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002727
John Zulauf14c355b2019-06-27 16:09:37 -06002728 // Validation shouldn't rely on anything in stage state being valid if the entrypoint isn't present
2729 auto entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
2730 if (entrypoint == module->end()) return;
Chris Forbes47567b72017-06-09 12:09:45 -07002731
Chris Forbes47567b72017-06-09 12:09:45 -07002732 // Mark accessible ids
John Zulauf14c355b2019-06-27 16:09:37 -06002733 stage_state->accessible_ids = MarkAccessibleIds(module, entrypoint);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002734 ProcessExecutionModes(module, entrypoint, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002735
John Zulauf14c355b2019-06-27 16:09:37 -06002736 stage_state->descriptor_uses =
2737 CollectInterfaceByDescriptorSlot(report_data, module, stage_state->accessible_ids, &stage_state->has_writable_descriptor);
2738 // Capture descriptor uses for the pipeline
2739 for (auto use : stage_state->descriptor_uses) {
2740 // While validating shaders capture which slots are used by the pipeline
2741 auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
2742 reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
2743 }
2744}
2745
2746bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
2747 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06002748 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06002749 bool skip = false;
2750
2751 // Check the module
2752 if (!module->has_valid_spirv) {
2753 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2754 "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s.",
2755 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
2756 }
2757
2758 // Check the entrypoint
2759 if (entrypoint == module->end()) {
2760 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
2761 "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
2762 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
2763 }
2764 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
2765
2766 // Mark accessible ids
2767 auto &accessible_ids = stage_state.accessible_ids;
2768
Chris Forbes47567b72017-06-09 12:09:45 -07002769 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06002770 bool has_writable_descriptor = stage_state.has_writable_descriptor;
2771 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07002772
Chris Forbes349b3132018-03-07 11:38:08 -08002773 // Validate shader capabilities against enabled device features
Jeff Bolzee743412019-06-20 22:24:32 -05002774 skip |= ValidateShaderCapabilities(module, pStage->stage);
2775 skip |= ValidateShaderStageWritableDescriptor(pStage->stage, has_writable_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002776 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
Jeff Bolzee743412019-06-20 22:24:32 -05002777 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, accessible_ids);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002778 skip |= ValidateExecutionModes(module, entrypoint);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002779 skip |= ValidateSpecializationOffsets(report_data, pStage);
2780 skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
2781 pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05002782 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002783 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002784 }
Jeff Bolze4356752019-03-07 11:23:46 -06002785 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002786
2787 // Validate descriptor use
2788 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07002789 // Verify given pipelineLayout has requested setLayout with requested binding
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002790 const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07002791 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05002792 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07002793
2794 if (!binding) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002795 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 -06002796 kVUID_Core_Shader_MissingDescriptor,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002797 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
Jeff Bolze54ae892018-09-08 12:16:29 -05002798 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002799 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002800 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 -06002801 kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002802 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
2803 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05002804 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002805 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 -06002806 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002807 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
Jeff Bolze54ae892018-09-08 12:16:29 -05002808 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
Chris Forbes47567b72017-06-09 12:09:45 -07002809 string_VkDescriptorType(binding->descriptorType));
2810 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002811 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 -06002812 kVUID_Core_Shader_DescriptorTypeMismatch,
Chris Forbes73c00bf2018-06-22 16:28:06 -07002813 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
2814 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07002815 }
2816 }
2817
2818 // Validate use of input attachments against subpass structure
2819 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002820 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07002821
Petr Krause91f7a12017-12-14 20:57:36 +01002822 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002823 auto subpass = pipeline->graphicsPipelineCI.subpass;
2824
2825 for (auto use : input_attachment_uses) {
2826 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
2827 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07002828 ? input_attachments[use.first].attachment
2829 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07002830
2831 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002832 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 -06002833 kVUID_Core_Shader_MissingInputAttachment,
Chris Forbes47567b72017-06-09 12:09:45 -07002834 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002835 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07002836 skip |=
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -06002837 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 -06002838 kVUID_Core_Shader_InputAttachmentTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002839 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002840 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002841 }
2842 }
2843 }
Lockeaa8fdc02019-04-02 11:59:20 -06002844 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
2845 skip |= ValidateComputeWorkGroupSizes(module);
2846 }
Chris Forbes47567b72017-06-09 12:09:45 -07002847 return skip;
2848}
2849
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002850static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, SHADER_MODULE_STATE const *producer,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002851 spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002852 SHADER_MODULE_STATE const *consumer, spirv_inst_iter consumer_entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002853 shader_stage_attributes const *consumer_stage) {
Chris Forbes47567b72017-06-09 12:09:45 -07002854 bool skip = false;
2855
2856 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002857 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
2858 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07002859
2860 auto a_it = outputs.begin();
2861 auto b_it = inputs.begin();
2862
2863 // Maps sorted by key (location); walk them together to find mismatches
2864 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
2865 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
2866 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
2867 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
2868 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
2869
2870 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Young4e919b22018-05-21 15:53:59 -06002871 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 -06002872 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
Mark Young4e919b22018-05-21 15:53:59 -06002873 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
2874 a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002875 a_it++;
2876 } else if (a_at_end || a_first > b_first) {
Mark Young4e919b22018-05-21 15:53:59 -06002877 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 -06002878 HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
Mark Young4e919b22018-05-21 15:53:59 -06002879 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
2880 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07002881 b_it++;
2882 } else {
2883 // subtleties of arrayed interfaces:
2884 // - if is_patch, then the member is not arrayed, even though the interface may be.
2885 // - if is_block_member, then the extra array level of an arrayed interface is not
2886 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002887 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
2888 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
2889 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Young4e919b22018-05-21 15:53:59 -06002890 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 -06002891 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Mark Young4e919b22018-05-21 15:53:59 -06002892 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002893 DescribeType(producer, a_it->second.type_id).c_str(),
2894 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002895 }
2896 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Young4e919b22018-05-21 15:53:59 -06002897 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 -06002898 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Dave Houltona9df0ce2018-02-07 10:51:23 -07002899 "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 -07002900 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
2901 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
2902 }
2903 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Young4e919b22018-05-21 15:53:59 -06002904 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 -06002905 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
Chris Forbes47567b72017-06-09 12:09:45 -07002906 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
2907 a_first.second, producer_stage->name, consumer_stage->name);
2908 }
2909 a_it++;
2910 b_it++;
2911 }
2912 }
2913
Ari Suonpaa696b3432019-03-11 14:02:57 +02002914 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
2915 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
2916 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
2917
2918 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
2919 if (builtins_producer.size() != builtins_consumer.size()) {
2920 skip |=
2921 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
2922 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
2923 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).", producer_stage->name,
2924 (int)builtins_producer.size(), consumer_stage->name, (int)builtins_consumer.size());
2925 } else {
2926 auto it_producer = builtins_producer.begin();
2927 auto it_consumer = builtins_consumer.begin();
2928 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
2929 if (*it_producer != *it_consumer) {
2930 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
2931 HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
2932 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
2933 consumer_stage->name);
2934 break;
2935 }
2936 it_producer++;
2937 it_consumer++;
2938 }
2939 }
2940 }
2941 }
2942
Chris Forbes47567b72017-06-09 12:09:45 -07002943 return skip;
2944}
2945
John Zulauf14c355b2019-06-27 16:09:37 -06002946static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002947 uint32_t stage_mask = 0;
2948 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2949 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2950 stage_mask |= pCreateInfo->pStages[i].stage;
2951 }
2952 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05002953 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
2954 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
2955 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002956 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
2957 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
2958 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
2959 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
2960 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002961 }
2962 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002963 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06002964}
2965
Chris Forbes47567b72017-06-09 12:09:45 -07002966// Validate that the shaders used by the given pipeline and store the active_slots
2967// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06002968bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Chris Forbesa400a8a2017-07-20 13:10:24 -07002969 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002970 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2971 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002972
John Zulauf14c355b2019-06-27 16:09:37 -06002973 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002974 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05002975 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002976 memset(entrypoints, 0, sizeof(entrypoints));
2977 bool skip = false;
2978
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002979 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
2980
Chris Forbes47567b72017-06-09 12:09:45 -07002981 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2982 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002983 auto stage_id = GetShaderStageId(pStage->stage);
John Zulauf14c355b2019-06-27 16:09:37 -06002984 shaders[stage_id] = GetShaderModuleState(pStage->module);
2985 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], pStage->pName, pStage->stage);
2986 skip |= ValidatePipelineShaderStage(pStage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
2987
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002988 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07002989 }
2990
2991 // if the shader stages are no good individually, cross-stage validation is pointless.
2992 if (skip) return true;
2993
2994 auto vi = pCreateInfo->pVertexInputState;
2995
2996 if (vi) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002997 skip |= ValidateViConsistency(report_data, vi);
Chris Forbes47567b72017-06-09 12:09:45 -07002998 }
2999
3000 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003001 skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003002 }
3003
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003004 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3005 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003006
3007 while (!shaders[producer] && producer != fragment_stage) {
3008 producer++;
3009 consumer++;
3010 }
3011
3012 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3013 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003014 if (shaders[consumer]) {
3015 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003016 skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
3017 &shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
3018 &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003019 }
Chris Forbes47567b72017-06-09 12:09:45 -07003020
3021 producer = consumer;
3022 }
3023 }
3024
3025 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003026 skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
3027 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003028 }
3029
3030 return skip;
3031}
3032
John Zulaufac4c6e12019-07-01 16:05:58 -06003033bool CoreChecks::ValidateComputePipeline(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003034 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003035
John Zulauf14c355b2019-06-27 16:09:37 -06003036 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3037 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003038
John Zulauf14c355b2019-06-27 16:09:37 -06003039 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003040}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003041
John Zulaufac4c6e12019-07-01 16:05:58 -06003042bool CoreChecks::ValidateRayTracingPipelineNV(PIPELINE_STATE *pipeline) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003043 bool skip = false;
3044 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3045 const auto &stage = pipeline->raytracingPipelineCI.ptr()->pStages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003046
John Zulaufe4474e72019-07-01 17:28:27 -06003047 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3048 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003049
John Zulaufe4474e72019-07-01 17:28:27 -06003050 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
3051 }
3052 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003053}
3054
Dave Houltona9df0ce2018-02-07 10:51:23 -07003055uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003056
Dave Houltona9df0ce2018-02-07 10:51:23 -07003057static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06003058 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
3059 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003060 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003061 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003062 return nullptr;
3063}
3064
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003065bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
3066 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003067 bool skip = false;
3068 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003069
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06003070 if (disabled.shader_validation) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003071 return false;
3072 }
3073
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003074 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003075
3076 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07003077 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 -06003078 "VUID-VkShaderModuleCreateInfo-pCode-01376",
3079 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3080 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003081 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003082 auto cache = GetValidationCacheInfo(pCreateInfo);
3083 uint32_t hash = 0;
3084 if (cache) {
3085 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003086 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003087 }
3088
Chris Forbes4ae55b32017-06-09 14:42:56 -07003089 // Use SPIRV-Tools validator to try and catch any issues with the module itself
Dave Houlton0ea2d012018-06-21 14:00:26 -06003090 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
Mark Lobodzinski544def72019-04-19 14:25:59 -06003091 if (api_version >= VK_API_VERSION_1_1) {
Dave Houlton0ea2d012018-06-21 14:00:26 -06003092 spirv_environment = SPV_ENV_VULKAN_1_1;
3093 }
3094 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003095 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003096 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06003097 spv_validator_options options = spvValidatorOptionsCreate();
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003098 if (device_extensions.vk_khr_relaxed_block_layout) {
Karl Schultzfda1b382018-08-08 18:56:11 -06003099 spvValidatorOptionsSetRelaxBlockLayout(options, true);
3100 }
Graeme Leese9b6a1522019-06-07 20:49:45 +01003101 if (device_extensions.vk_khr_uniform_buffer_standard_layout &&
3102 enabled_features.uniform_buffer_standard_layout.uniformBufferStandardLayout == VK_TRUE) {
3103 spvValidatorOptionsSetUniformBufferStandardLayout(options, true);
3104 }
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003105 if (device_extensions.vk_ext_scalar_block_layout &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003106 enabled_features.scalar_block_layout_features.scalarBlockLayout == VK_TRUE) {
Tobias Hector6a0ece72018-12-10 12:24:05 +00003107 spvValidatorOptionsSetScalarBlockLayout(options, true);
3108 }
Karl Schultzfda1b382018-08-08 18:56:11 -06003109 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003110 if (spv_valid != SPV_SUCCESS) {
3111 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07003112 skip |=
3113 log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
3114 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
3115 "SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
Chris Forbes4ae55b32017-06-09 14:42:56 -07003116 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003117 } else {
3118 if (cache) {
3119 cache->Insert(hash);
3120 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003121 }
3122
Karl Schultzfda1b382018-08-08 18:56:11 -06003123 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003124 spvDiagnosticDestroy(diag);
3125 spvContextDestroy(ctx);
3126 }
3127
Chris Forbes4ae55b32017-06-09 14:42:56 -07003128 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003129}
3130
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003131void CoreChecks::PreCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
3132 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
3133 void *csm_state_data) {
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07003134 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06003135 if (enabled.gpu_validation) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -07003136 GpuPreCallCreateShaderModule(pCreateInfo, pAllocator, pShaderModule, &csm_state->unique_shader_id,
Mark Lobodzinski01734072019-02-13 17:39:15 -07003137 &csm_state->instrumented_create_info, &csm_state->instrumented_pgm);
3138 }
3139}
3140
John Zulauf7eeb6f72019-06-17 11:56:36 -06003141void ValidationStateTracker::PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
3142 const VkAllocationCallbacks *pAllocator,
3143 VkShaderModule *pShaderModule, VkResult result,
3144 void *csm_state_data) {
Mark Lobodzinski01734072019-02-13 17:39:15 -07003145 if (VK_SUCCESS != result) return;
Mark Lobodzinski1db77e82019-03-01 10:02:54 -07003146 create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
Mark Lobodzinski01734072019-02-13 17:39:15 -07003147
Mark Lobodzinski544def72019-04-19 14:25:59 -06003148 spv_target_env spirv_environment = ((api_version >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0);
Mark Lobodzinski01734072019-02-13 17:39:15 -07003149 bool is_spirv = (pCreateInfo->pCode[0] == spv::MagicNumber);
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003150 std::unique_ptr<SHADER_MODULE_STATE> new_shader_module(
3151 is_spirv ? new SHADER_MODULE_STATE(pCreateInfo, *pShaderModule, spirv_environment, csm_state->unique_shader_id)
3152 : new SHADER_MODULE_STATE());
Mark Lobodzinski7767ad82019-03-09 13:35:25 -07003153 shaderModuleMap[*pShaderModule] = std::move(new_shader_module);
Mark Lobodzinski01734072019-02-13 17:39:15 -07003154}
Lockeaa8fdc02019-04-02 11:59:20 -06003155
John Zulaufac4c6e12019-07-01 16:05:58 -06003156bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003157 bool skip = false;
3158 uint32_t local_size_x = 0;
3159 uint32_t local_size_y = 0;
3160 uint32_t local_size_z = 0;
3161 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3162 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
locke-lunarg9edc2812019-06-17 23:18:52 -06003163 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3164 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3165 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
3166 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3167 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06003168 }
3169 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
locke-lunarg9edc2812019-06-17 23:18:52 -06003170 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3171 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3172 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
3173 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3174 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06003175 }
3176 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
locke-lunarg9edc2812019-06-17 23:18:52 -06003177 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3178 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3179 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
3180 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3181 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06003182 }
3183
3184 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
3185 uint64_t invocations = local_size_x * local_size_y;
3186 // Prevent overflow.
3187 bool fail = false;
3188 if (invocations > UINT32_MAX || invocations > limit) {
3189 fail = true;
3190 }
3191 if (!fail) {
3192 invocations *= local_size_z;
3193 if (invocations > UINT32_MAX || invocations > limit) {
3194 fail = true;
3195 }
3196 }
3197 if (fail) {
3198 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
3199 HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
locke-lunarg9edc2812019-06-17 23:18:52 -06003200 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
Lockeaa8fdc02019-04-02 11:59:20 -06003201 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
3202 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
3203 limit);
3204 }
3205 }
3206 return skip;
3207}