blob: 760440648742ccfeb9629fa294f465c9a3af9f75 [file] [log] [blame]
Tony-LunarG73719992020-01-15 10:20:28 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 LunarG, Inc.
4 * Copyright (C) 2015-2020 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>
Jeff Bolzf234bf82019-11-04 14:07:15 -060027#include <cmath>
Petr Kraus25810d02019-08-27 17:41:15 +020028#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070029#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <string>
31#include <unordered_map>
32#include <vector>
33
Mark Lobodzinski102687e2020-04-28 11:03:28 -060034#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070035#include "vk_loader_platform.h"
36#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_layer_data.h"
38#include "vk_layer_extension_utils.h"
39#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070040#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070041#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020042
Chris Forbes4ae55b32017-06-09 14:42:56 -070043#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070044#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070045
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080046void decoration_set::add(uint32_t decoration, uint32_t value) {
47 switch (decoration) {
48 case spv::DecorationLocation:
49 flags |= location_bit;
50 location = value;
51 break;
52 case spv::DecorationPatch:
53 flags |= patch_bit;
54 break;
55 case spv::DecorationRelaxedPrecision:
56 flags |= relaxed_precision_bit;
57 break;
58 case spv::DecorationBlock:
59 flags |= block_bit;
60 break;
61 case spv::DecorationBufferBlock:
62 flags |= buffer_block_bit;
63 break;
64 case spv::DecorationComponent:
65 flags |= component_bit;
66 component = value;
67 break;
68 case spv::DecorationInputAttachmentIndex:
69 flags |= input_attachment_index_bit;
70 input_attachment_index = value;
71 break;
72 case spv::DecorationDescriptorSet:
73 flags |= descriptor_set_bit;
74 descriptor_set = value;
75 break;
76 case spv::DecorationBinding:
77 flags |= binding_bit;
78 binding = value;
79 break;
80 case spv::DecorationNonWritable:
81 flags |= nonwritable_bit;
82 break;
83 case spv::DecorationBuiltIn:
84 flags |= builtin_bit;
85 builtin = value;
86 break;
87 }
88}
89
Chris Forbes47567b72017-06-09 12:09:45 -070090enum FORMAT_TYPE {
91 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
92 FORMAT_TYPE_SINT = 2,
93 FORMAT_TYPE_UINT = 4,
94};
95
96typedef std::pair<unsigned, unsigned> location_t;
97
Chris Forbes47567b72017-06-09 12:09:45 -070098static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +020099 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
100 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
101 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
102 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
103 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700104};
105
John Zulauf14c355b2019-06-27 16:09:37 -0600106unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
107
Chris Forbes47567b72017-06-09 12:09:45 -0700108// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600109void SHADER_MODULE_STATE::BuildDefIndex() {
Chris Forbes47567b72017-06-09 12:09:45 -0700110 for (auto insn : *this) {
111 switch (insn.opcode()) {
112 // Types
113 case spv::OpTypeVoid:
114 case spv::OpTypeBool:
115 case spv::OpTypeInt:
116 case spv::OpTypeFloat:
117 case spv::OpTypeVector:
118 case spv::OpTypeMatrix:
119 case spv::OpTypeImage:
120 case spv::OpTypeSampler:
121 case spv::OpTypeSampledImage:
122 case spv::OpTypeArray:
123 case spv::OpTypeRuntimeArray:
124 case spv::OpTypeStruct:
125 case spv::OpTypeOpaque:
126 case spv::OpTypePointer:
127 case spv::OpTypeFunction:
128 case spv::OpTypeEvent:
129 case spv::OpTypeDeviceEvent:
130 case spv::OpTypeReserveId:
131 case spv::OpTypeQueue:
132 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600133 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600134 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700135 def_index[insn.word(1)] = insn.offset();
136 break;
137
138 // Fixed constants
139 case spv::OpConstantTrue:
140 case spv::OpConstantFalse:
141 case spv::OpConstant:
142 case spv::OpConstantComposite:
143 case spv::OpConstantSampler:
144 case spv::OpConstantNull:
145 def_index[insn.word(2)] = insn.offset();
146 break;
147
148 // Specialization constants
149 case spv::OpSpecConstantTrue:
150 case spv::OpSpecConstantFalse:
151 case spv::OpSpecConstant:
152 case spv::OpSpecConstantComposite:
153 case spv::OpSpecConstantOp:
154 def_index[insn.word(2)] = insn.offset();
155 break;
156
157 // Variables
158 case spv::OpVariable:
159 def_index[insn.word(2)] = insn.offset();
160 break;
161
162 // Functions
163 case spv::OpFunction:
164 def_index[insn.word(2)] = insn.offset();
165 break;
166
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800167 // Decorations
168 case spv::OpDecorate: {
169 auto targetId = insn.word(1);
170 decorations[targetId].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
171 } break;
172 case spv::OpGroupDecorate: {
173 auto const &src = decorations[insn.word(1)];
174 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
175 } break;
176
John Zulauf14c355b2019-06-27 16:09:37 -0600177 // Entry points ... add to the entrypoint table
178 case spv::OpEntryPoint: {
179 // Entry points do not have an id (the id is the function id) and thus need their own table
180 auto entrypoint_name = (char const *)&insn.word(3);
181 auto execution_model = insn.word(1);
182 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
183 entry_points.emplace(entrypoint_name, EntryPoint{insn.offset(), entrypoint_stage});
184 break;
185 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800186
Chris Forbes47567b72017-06-09 12:09:45 -0700187 default:
188 // We don't care about any other defs for now.
189 break;
190 }
191 }
192}
193
Jeff Bolz105d6492018-09-29 15:46:44 -0500194unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
195 switch (mode) {
196 case spv::ExecutionModelVertex:
197 return VK_SHADER_STAGE_VERTEX_BIT;
198 case spv::ExecutionModelTessellationControl:
199 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
200 case spv::ExecutionModelTessellationEvaluation:
201 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
202 case spv::ExecutionModelGeometry:
203 return VK_SHADER_STAGE_GEOMETRY_BIT;
204 case spv::ExecutionModelFragment:
205 return VK_SHADER_STAGE_FRAGMENT_BIT;
206 case spv::ExecutionModelGLCompute:
207 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600208 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700209 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600210 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700211 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600212 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700213 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600214 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700215 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600216 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700217 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600218 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700219 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500220 case spv::ExecutionModelTaskNV:
221 return VK_SHADER_STAGE_TASK_BIT_NV;
222 case spv::ExecutionModelMeshNV:
223 return VK_SHADER_STAGE_MESH_BIT_NV;
224 default:
225 return 0;
226 }
227}
228
locke-lunargd9a069d2019-09-17 01:50:19 -0600229spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600230 auto range = src->entry_points.equal_range(name);
231 for (auto it = range.first; it != range.second; ++it) {
232 if (it->second.stage == stageBits) {
233 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700234 }
235 }
Chris Forbes47567b72017-06-09 12:09:45 -0700236 return src->end();
237}
238
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600239static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700240 switch (sc) {
241 case spv::StorageClassInput:
242 return "input";
243 case spv::StorageClassOutput:
244 return "output";
245 case spv::StorageClassUniformConstant:
246 return "const uniform";
247 case spv::StorageClassUniform:
248 return "uniform";
249 case spv::StorageClassWorkgroup:
250 return "workgroup local";
251 case spv::StorageClassCrossWorkgroup:
252 return "workgroup global";
253 case spv::StorageClassPrivate:
254 return "private global";
255 case spv::StorageClassFunction:
256 return "function";
257 case spv::StorageClassGeneric:
258 return "generic";
259 case spv::StorageClassAtomicCounter:
260 return "atomic counter";
261 case spv::StorageClassImage:
262 return "image";
263 case spv::StorageClassPushConstant:
264 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800265 case spv::StorageClassStorageBuffer:
266 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700267 default:
268 return "unknown";
269 }
270}
271
272// Get the value of an integral constant
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600273unsigned GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700274 auto value = src->get_def(id);
275 assert(value != src->end());
276
277 if (value.opcode() != spv::OpConstant) {
278 // TODO: Either ensure that the specialization transform is already performed on a module we're
279 // considering here, OR -- specialize on the fly now.
280 return 1;
281 }
282
283 return value.word(3);
284}
285
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600286static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700287 auto insn = src->get_def(type);
288 assert(insn != src->end());
289
290 switch (insn.opcode()) {
291 case spv::OpTypeBool:
292 ss << "bool";
293 break;
294 case spv::OpTypeInt:
295 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
296 break;
297 case spv::OpTypeFloat:
298 ss << "float" << insn.word(2);
299 break;
300 case spv::OpTypeVector:
301 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600302 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700303 break;
304 case spv::OpTypeMatrix:
305 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600306 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700307 break;
308 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600309 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
310 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700311 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700312 case spv::OpTypeRuntimeArray:
313 ss << "runtime arr[] of ";
314 DescribeTypeInner(ss, src, insn.word(2));
315 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700316 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600317 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
318 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700319 break;
320 case spv::OpTypeStruct: {
321 ss << "struct of (";
322 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600323 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700324 if (i == insn.len() - 1) {
325 ss << ")";
326 } else {
327 ss << ", ";
328 }
329 }
330 break;
331 }
332 case spv::OpTypeSampler:
333 ss << "sampler";
334 break;
335 case spv::OpTypeSampledImage:
336 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600337 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700338 break;
339 case spv::OpTypeImage:
340 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
341 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600342 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500343 ss << "accelerationStruture";
344 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700345 default:
346 ss << "oddtype";
347 break;
348 }
349}
350
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600351static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700352 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600353 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700354 return ss.str();
355}
356
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600357static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700358 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
359 return type.word(2) < 64;
360}
361
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600362static 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 -0600363 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700364 // Walk two type trees together, and complain about differences
365 auto a_insn = a->get_def(a_type);
366 auto b_insn = b->get_def(b_type);
367 assert(a_insn != a->end());
368 assert(b_insn != b->end());
369
Chris Forbes062f1222018-08-21 15:34:15 -0700370 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
371
Chris Forbes47567b72017-06-09 12:09:45 -0700372 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600373 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700374 }
375
376 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
377 // 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 -0600378 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700379 }
380
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600381 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
382 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700383 }
384
385 if (a_insn.opcode() != b_insn.opcode()) {
386 return false;
387 }
388
389 if (a_insn.opcode() == spv::OpTypePointer) {
390 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600391 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700392 }
393
394 if (a_arrayed || b_arrayed) {
395 // If we havent resolved array-of-verts by here, we're not going to.
396 return false;
397 }
398
399 switch (a_insn.opcode()) {
400 case spv::OpTypeBool:
401 return true;
402 case spv::OpTypeInt:
403 // Match on width, signedness
404 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
405 case spv::OpTypeFloat:
406 // Match on width
407 return a_insn.word(2) == b_insn.word(2);
408 case spv::OpTypeVector:
409 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600410 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
411 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700412 return a_insn.word(3) >= b_insn.word(3);
413 } else {
414 return a_insn.word(3) == b_insn.word(3);
415 }
416 case spv::OpTypeMatrix:
417 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600418 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700419 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700420 case spv::OpTypeArray:
421 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
422 // 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 -0600423 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
424 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700425 case spv::OpTypeStruct:
426 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700427 {
428 if (a_insn.len() != b_insn.len()) {
429 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700430 }
Chris Forbes47567b72017-06-09 12:09:45 -0700431
Dave Houltona9df0ce2018-02-07 10:51:23 -0700432 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600433 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700434 return false;
435 }
436 }
437
438 return true;
439 }
Chris Forbes47567b72017-06-09 12:09:45 -0700440 default:
441 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
442 return false;
443 }
444}
445
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600446static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700447 auto insn = src->get_def(type);
448 assert(insn != src->end());
449
450 switch (insn.opcode()) {
451 case spv::OpTypePointer:
452 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
453 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600454 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700455 case spv::OpTypeArray:
456 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600457 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700458 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600459 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700460 }
461 case spv::OpTypeMatrix:
462 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600463 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700464 case spv::OpTypeVector: {
465 auto scalar_type = src->get_def(insn.word(2));
466 auto bit_width =
467 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
468
469 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
470 return (bit_width * insn.word(3) + 127) / 128;
471 }
472 default:
473 // Everything else is just 1.
474 return 1;
475
476 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
477 }
478}
479
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600480static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200481 auto insn = src->get_def(type);
482 assert(insn != src->end());
483
484 switch (insn.opcode()) {
485 case spv::OpTypePointer:
486 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
487 // pointers around.
488 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
489 case spv::OpTypeStruct: {
490 uint32_t sum = 0;
491 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
492 sum += GetComponentsConsumedByType(src, insn.word(i), false);
493 }
494 return sum;
495 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500496 case spv::OpTypeArray:
497 if (strip_array_level) {
498 return GetComponentsConsumedByType(src, insn.word(2), false);
499 } else {
500 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200501 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200502 case spv::OpTypeMatrix:
503 // Num locations is the dimension * element size
504 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
505 case spv::OpTypeVector: {
506 auto scalar_type = src->get_def(insn.word(2));
507 auto bit_width =
508 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
509 // One component is 32-bit
510 return (bit_width * insn.word(3) + 31) / 32;
511 }
512 case spv::OpTypeFloat: {
513 auto bit_width = insn.word(2);
514 return (bit_width + 31) / 32;
515 }
516 case spv::OpTypeInt: {
517 auto bit_width = insn.word(2);
518 return (bit_width + 31) / 32;
519 }
520 case spv::OpConstant:
521 return GetComponentsConsumedByType(src, insn.word(1), false);
522 default:
523 return 0;
524 }
525}
526
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600527static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700528 switch (format) {
529 case VK_FORMAT_R64G64B64A64_SFLOAT:
530 case VK_FORMAT_R64G64B64A64_SINT:
531 case VK_FORMAT_R64G64B64A64_UINT:
532 case VK_FORMAT_R64G64B64_SFLOAT:
533 case VK_FORMAT_R64G64B64_SINT:
534 case VK_FORMAT_R64G64B64_UINT:
535 return 2;
536 default:
537 return 1;
538 }
539}
540
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600541static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700542 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
543 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
544 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
545 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700546 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
547 return FORMAT_TYPE_FLOAT;
548}
549
550// 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 -0700551// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600552static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700553 auto insn = src->get_def(type);
554 assert(insn != src->end());
555
556 switch (insn.opcode()) {
557 case spv::OpTypeInt:
558 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
559 case spv::OpTypeFloat:
560 return FORMAT_TYPE_FLOAT;
561 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700562 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700563 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700564 case spv::OpTypeRuntimeArray:
565 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600566 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700567 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600568 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700569
570 default:
571 return 0;
572 }
573}
574
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600575static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700576 uint32_t bit_pos = uint32_t(u_ffs(stage));
577 return bit_pos - 1;
578}
579
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600580static 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 -0700581 while (true) {
582 if (def.opcode() == spv::OpTypePointer) {
583 def = src->get_def(def.word(3));
584 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
585 def = src->get_def(def.word(2));
586 is_array_of_verts = false;
587 } else if (def.opcode() == spv::OpTypeStruct) {
588 return def;
589 } else {
590 return src->end();
591 }
592 }
593}
594
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600595static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800596 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
597 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700598 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600599 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800600 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700601 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700602 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700603 }
604
605 std::unordered_map<unsigned, unsigned> member_components;
606 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700607 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700608
609 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
610 for (auto insn : *src) {
611 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
612 unsigned member_index = insn.word(2);
613
614 if (insn.word(3) == spv::DecorationComponent) {
615 unsigned component = insn.word(4);
616 member_components[member_index] = component;
617 }
618
619 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
620 member_relaxed_precision[member_index] = 1;
621 }
Chris Forbesa313d772017-06-13 13:59:41 -0700622
623 if (insn.word(3) == spv::DecorationPatch) {
624 member_patch[member_index] = 1;
625 }
Chris Forbes47567b72017-06-09 12:09:45 -0700626 }
627 }
628
Chris Forbesa313d772017-06-13 13:59:41 -0700629 // TODO: correctly handle location assignment from outside
630
Chris Forbes47567b72017-06-09 12:09:45 -0700631 // Second pass -- produce the output, from Location decorations
632 for (auto insn : *src) {
633 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
634 unsigned member_index = insn.word(2);
635 unsigned member_type_id = type.word(2 + member_index);
636
637 if (insn.word(3) == spv::DecorationLocation) {
638 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600639 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700640 auto component_it = member_components.find(member_index);
641 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
642 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700643 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700644
645 for (unsigned int offset = 0; offset < num_locations; offset++) {
646 interface_var v = {};
647 v.id = id;
648 // TODO: member index in interface_var too?
649 v.type_id = member_type_id;
650 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700651 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700652 v.is_block_member = true;
653 v.is_relaxed_precision = is_relaxed_precision;
654 (*out)[std::make_pair(location + offset, component)] = v;
655 }
656 }
657 }
658 }
Chris Forbesa313d772017-06-13 13:59:41 -0700659
660 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700661}
662
Ari Suonpaa696b3432019-03-11 14:02:57 +0200663static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800664 assert(entrypoint.opcode() == spv::OpEntryPoint);
665
Ari Suonpaa696b3432019-03-11 14:02:57 +0200666 std::vector<uint32_t> interfaces;
667 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
668 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
669 uint32_t word = 3;
670 while (entrypoint.word(word) & 0xff000000u) {
671 ++word;
672 }
673 ++word;
674
675 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
676
677 return interfaces;
678}
679
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600680static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600681 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700682 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
683
Chris Forbes47567b72017-06-09 12:09:45 -0700684 std::map<location_t, interface_var> out;
685
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800686 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
687 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700688 assert(insn != src->end());
689 assert(insn.opcode() == spv::OpVariable);
690
691 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800692 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700693 unsigned id = insn.word(2);
694 unsigned type = insn.word(1);
695
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800696 int location = d.location;
697 int builtin = d.builtin;
698 unsigned component = d.component;
699 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
700 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700701
Dave Houltona9df0ce2018-02-07 10:51:23 -0700702 if (builtin != -1)
703 continue;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800704 else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700705 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
706 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600707 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700708 for (unsigned int offset = 0; offset < num_locations; offset++) {
709 interface_var v = {};
710 v.id = id;
711 v.type_id = type;
712 v.offset = offset;
713 v.is_patch = is_patch;
714 v.is_relaxed_precision = is_relaxed_precision;
715 out[std::make_pair(location + offset, component)] = v;
716 }
Chris Forbes47567b72017-06-09 12:09:45 -0700717 }
718 }
719 }
720
721 return out;
722}
723
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600724static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200725 uint32_t storageClass) {
726 std::vector<uint32_t> variables;
727 std::vector<uint32_t> builtinStructMembers;
728 std::vector<uint32_t> builtinDecorations;
729
730 for (auto insn : *src) {
731 switch (insn.opcode()) {
732 // Find all built-in member decorations
733 case spv::OpMemberDecorate:
734 if (insn.word(3) == spv::DecorationBuiltIn) {
735 builtinStructMembers.push_back(insn.word(1));
736 }
737 break;
738 // Find all built-in decorations
739 case spv::OpDecorate:
740 switch (insn.word(2)) {
741 case spv::DecorationBlock: {
742 uint32_t blockID = insn.word(1);
743 for (auto builtInBlockID : builtinStructMembers) {
744 // Check if one of the members of the block are built-in -> the block is built-in
745 if (blockID == builtInBlockID) {
746 builtinDecorations.push_back(blockID);
747 break;
748 }
749 }
750 break;
751 }
752 case spv::DecorationBuiltIn:
753 builtinDecorations.push_back(insn.word(1));
754 break;
755 default:
756 break;
757 }
758 break;
759 default:
760 break;
761 }
762 }
763
764 // Find all interface variables belonging to the entrypoint and matching the storage class
765 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
766 auto def = src->get_def(id);
767 assert(def != src->end());
768 assert(def.opcode() == spv::OpVariable);
769
770 if (def.word(3) == storageClass) variables.push_back(def.word(1));
771 }
772
773 // Find all members belonging to the builtin block selected
774 std::vector<uint32_t> builtinBlockMembers;
775 for (auto &var : variables) {
776 auto def = src->get_def(src->get_def(var).word(3));
777
778 // It could be an array of IO blocks. The element type should be the struct defining the block contents
779 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
780
781 // Now find all members belonging to the struct defining the IO block
782 if (def.opcode() == spv::OpTypeStruct) {
783 for (auto builtInID : builtinDecorations) {
784 if (builtInID == def.word(1)) {
785 for (int i = 2; i < (int)def.len(); i++)
786 builtinBlockMembers.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
787 // These shouldn't be left after replacing.
788 for (auto insn : *src) {
789 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == builtInID &&
790 insn.word(3) == spv::DecorationBuiltIn) {
791 auto structIndex = insn.word(2);
792 assert(structIndex < builtinBlockMembers.size());
793 builtinBlockMembers[structIndex] = insn.word(4);
794 }
795 }
796 }
797 }
798 }
799 }
800
801 return builtinBlockMembers;
802}
803
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600804static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600805 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700806 std::vector<std::pair<uint32_t, interface_var>> out;
807
808 for (auto insn : *src) {
809 if (insn.opcode() == spv::OpDecorate) {
810 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
811 auto attachment_index = insn.word(3);
812 auto id = insn.word(1);
813
814 if (accessible_ids.count(id)) {
815 auto def = src->get_def(id);
816 assert(def != src->end());
locke-lunarg9a16ebb2020-07-30 16:56:33 -0600817 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600818 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700819 for (unsigned int offset = 0; offset < num_locations; offset++) {
820 interface_var v = {};
821 v.id = id;
822 v.type_id = def.word(1);
823 v.offset = offset;
824 out.emplace_back(attachment_index + offset, v);
825 }
826 }
827 }
828 }
829 }
830 }
831
832 return out;
833}
834
locke-lunarg25b6c352020-08-06 17:44:18 -0600835static bool AtomicOperation(uint32_t opcode) {
836 switch (opcode) {
837 case spv::OpAtomicLoad:
838 case spv::OpAtomicStore:
839 case spv::OpAtomicExchange:
840 case spv::OpAtomicCompareExchange:
841 case spv::OpAtomicCompareExchangeWeak:
842 case spv::OpAtomicIIncrement:
843 case spv::OpAtomicIDecrement:
844 case spv::OpAtomicIAdd:
845 case spv::OpAtomicISub:
846 case spv::OpAtomicSMin:
847 case spv::OpAtomicUMin:
848 case spv::OpAtomicSMax:
849 case spv::OpAtomicUMax:
850 case spv::OpAtomicAnd:
851 case spv::OpAtomicOr:
852 case spv::OpAtomicXor:
853 case spv::OpAtomicFAddEXT:
854 return true;
855 default:
856 return false;
857 }
858 return false;
859}
860
locke-lunarg12d20992020-09-21 12:46:49 -0600861bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
862 const std::unordered_map<unsigned, unsigned> &load_members,
863 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
864 for (auto load_id : operator_members) {
865 auto load_it = load_members.find(load_id);
866 if (load_it == load_members.end()) {
867 continue;
868 }
869 if (load_it->second == object_id) {
870 return true;
871 }
872
873 auto accesschain_it = accesschain_members.find(load_it->second);
874 if (accesschain_it == accesschain_members.end()) {
875 continue;
876 }
877 if (accesschain_it->second.first == object_id) {
878 return true;
879 }
880 }
881 return false;
882}
883
locke-lunarg25b6c352020-08-06 17:44:18 -0600884// Check writable, image atomic operation
885static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
886 bool is_check_writable, interface_var &out_interface_var) {
locke-lunarg6f760f12020-06-05 16:19:37 -0600887 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -0600888 unsigned int id = id_it.word(2);
889
Chris Forbes8af24522018-03-07 11:37:45 -0800890 auto type = module->get_def(type_id);
891
892 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
locke-lunarg12d20992020-09-21 12:46:49 -0600893 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
894 type.opcode() == spv::OpTypeSampledImage) {
895 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
896 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700897 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800898 } else {
locke-lunarg36045992020-08-20 16:54:37 -0600899 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -0800900 }
901 }
Chris Forbes8af24522018-03-07 11:37:45 -0800902 switch (type.opcode()) {
903 case spv::OpTypeImage: {
904 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -0600905 if (dim != spv::DimSubpassData) {
locke-lunarg6f760f12020-06-05 16:19:37 -0600906 std::vector<unsigned> imagwrite_members;
locke-lunarg25b6c352020-08-06 17:44:18 -0600907 std::vector<unsigned> atomic_members;
locke-lunarg12d20992020-09-21 12:46:49 -0600908 std::vector<unsigned> sampler_implicitLod_members; // sampler Load id
locke-lunarg36045992020-08-20 16:54:37 -0600909 std::vector<std::pair<unsigned, unsigned>> sampledImage_members;
locke-lunarg6f760f12020-06-05 16:19:37 -0600910 std::unordered_map<unsigned, unsigned> load_members;
locke-lunarg36045992020-08-20 16:54:37 -0600911 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
locke-lunarg25b6c352020-08-06 17:44:18 -0600912 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
913
locke-lunarg6f760f12020-06-05 16:19:37 -0600914 for (auto insn : *module) {
915 switch (insn.opcode()) {
locke-lunarg12d20992020-09-21 12:46:49 -0600916 case spv::OpImageSampleImplicitLod:
917 case spv::OpImageSampleDrefImplicitLod:
918 case spv::OpImageSampleProjImplicitLod:
919 case spv::OpImageSampleProjDrefImplicitLod:
920 case spv::OpImageSparseSampleImplicitLod:
921 case spv::OpImageSparseSampleDrefImplicitLod:
922 case spv::OpImageSparseSampleProjImplicitLod:
923 case spv::OpImageSparseSampleProjDrefImplicitLod: {
924 sampler_implicitLod_members.emplace_back(insn.word(3)); // Load id
925 break;
926 }
locke-lunarg6f760f12020-06-05 16:19:37 -0600927 case spv::OpImageWrite: {
locke-lunarg25b6c352020-08-06 17:44:18 -0600928 if (is_check_writable) imagwrite_members.emplace_back(insn.word(1)); // Load id
locke-lunarg6f760f12020-06-05 16:19:37 -0600929 break;
930 }
locke-lunarg36045992020-08-20 16:54:37 -0600931 case spv::OpSampledImage: {
932 // 3: image load id, 4: sampler load id
933 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
934 break;
935 }
locke-lunarg6f760f12020-06-05 16:19:37 -0600936 case spv::OpLoad: {
937 // 2: Load id, 3: object id or AccessChain id
938 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
939 break;
940 }
941 case spv::OpAccessChain: {
locke-lunarg36045992020-08-20 16:54:37 -0600942 // 2: AccessChain id, 3: object id, 4: object id of array index
943 accesschain_members.insert(
944 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
locke-lunarg6f760f12020-06-05 16:19:37 -0600945 break;
946 }
locke-lunarg25b6c352020-08-06 17:44:18 -0600947 case spv::OpImageTexelPointer: {
948 // 2: ImageTexelPointer id, 3: object id
949 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
locke-lunarg6f760f12020-06-05 16:19:37 -0600950 break;
locke-lunarg25b6c352020-08-06 17:44:18 -0600951 }
952 default: {
953 if (AtomicOperation(insn.opcode())) {
954 if (insn.opcode() == spv::OpAtomicStore) {
955 atomic_members.emplace_back(insn.word(1)); // ImageTexelPointer id
956 } else {
957 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
958 }
959 }
960 break;
961 }
locke-lunarg6f760f12020-06-05 16:19:37 -0600962 }
963 }
locke-lunarg25b6c352020-08-06 17:44:18 -0600964 out_interface_var.is_writable = false;
965 out_interface_var.is_atomic_operation = false;
locke-lunarg12d20992020-09-21 12:46:49 -0600966 out_interface_var.is_sampler_implicitLod = false;
locke-lunarg25b6c352020-08-06 17:44:18 -0600967
locke-lunarg12d20992020-09-21 12:46:49 -0600968 if (CheckObjectIDFromOpLoad(id, imagwrite_members, load_members, accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -0600969 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -0600970 }
971 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
972 used_operators.accesschain_members)) {
973 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -0600974 }
975
locke-lunarg36045992020-08-20 16:54:37 -0600976 for (auto &itp_id : sampledImage_members) {
977 // Find if image id match.
978 uint32_t image_index = 0;
979 auto load_it = load_members.find(itp_id.first);
980 if (load_it == load_members.end()) {
981 continue;
982 } else {
983 if (load_it->second != id) {
984 auto accesschain_it = accesschain_members.find(load_it->second);
985 if (accesschain_it == accesschain_members.end()) {
986 continue;
987 } else {
988 if (accesschain_it->second.first != id) {
989 continue;
990 }
991 image_index = GetConstantValue(module, accesschain_it->second.second);
992 }
993 }
994 }
995 // Find sampler's set binding.
996 load_it = load_members.find(itp_id.second);
997 if (load_it == load_members.end()) {
998 continue;
999 } else {
1000 uint32_t sampler_id = load_it->second;
1001 uint32_t sampler_index = 0;
1002 auto accesschain_it = accesschain_members.find(load_it->second);
1003 if (accesschain_it != accesschain_members.end()) {
1004 sampler_id = accesschain_it->second.first;
1005 sampler_index = GetConstantValue(module, accesschain_it->second.second);
1006 }
1007 auto sampler_dec = module->get_decorations(sampler_id);
1008 out_interface_var.samplers_used_by_image.emplace_back(SamplerUsedByImage{
1009 image_index, descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
1010 }
1011 }
1012
1013 for (auto &itp_id : atomic_members) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001014 auto ltp_it = image_texel_pointer_members.find(itp_id);
1015 if (ltp_it == image_texel_pointer_members.end()) {
1016 continue;
1017 }
1018 if (ltp_it->second == id) {
1019 out_interface_var.is_atomic_operation = true;
1020 break;
1021 }
1022
1023 auto accesschain_it = accesschain_members.find(ltp_it->second);
1024 if (accesschain_it == accesschain_members.end()) {
1025 continue;
1026 }
1027 out_interface_var.is_atomic_operation = true;
1028 break;
locke-lunarg6f760f12020-06-05 16:19:37 -06001029 }
1030 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001031 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001032 }
1033
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001034 case spv::OpTypeStruct: {
1035 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001036 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -08001037 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001038 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
1039 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001040 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001041 }
1042 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001043
1044 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1045 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001046 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
1047 std::vector<unsigned> store_members;
1048 std::unordered_map<unsigned, unsigned> accesschain_members;
locke-lunarg25b6c352020-08-06 17:44:18 -06001049 std::vector<unsigned> atomic_store_members;
1050 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
locke-lunarg36045992020-08-20 16:54:37 -06001051 // unsigned int id = id_it.word(2);
locke-lunarg6f760f12020-06-05 16:19:37 -06001052
1053 for (auto insn : *module) {
1054 switch (insn.opcode()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001055 case spv::OpStore: {
locke-lunarg6f760f12020-06-05 16:19:37 -06001056 if (insn.word(1) == id) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001057 out_interface_var.is_writable = true;
1058 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001059 }
1060 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1061 break;
1062 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001063 case spv::OpAtomicStore: {
1064 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1065 break;
1066 }
1067 case spv::OpImageTexelPointer: {
1068 // 2: ImageTexelPointer id, 3: object id
1069 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1070 break;
1071 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001072 case spv::OpAccessChain: {
1073 // 2: AccessChain id, 3: object id
1074 if (insn.word(3) == id) {
1075 accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1076 }
1077 break;
1078 }
1079 default:
1080 break;
1081 }
1082 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001083 out_interface_var.is_writable = false;
1084
locke-lunarg6f760f12020-06-05 16:19:37 -06001085 for (auto oid : store_members) {
1086 auto accesschain_it = accesschain_members.find(oid);
1087 if (accesschain_it == accesschain_members.end()) {
1088 continue;
1089 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001090 out_interface_var.is_writable = true;
1091 return;
1092 }
1093
1094 for (auto itp_id : atomic_store_members) {
1095 auto ltp_it = image_texel_pointer_members.find(itp_id);
1096 if (ltp_it == image_texel_pointer_members.end()) {
1097 continue;
1098 }
1099 if (ltp_it->second == id) {
1100 out_interface_var.is_writable = true;
1101 return;
1102 }
1103
1104 auto accesschain_it = accesschain_members.find(ltp_it->second);
1105 if (accesschain_it == accesschain_members.end()) {
1106 continue;
1107 }
1108 out_interface_var.is_writable = true;
1109 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001110 }
1111 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001112 }
Chris Forbes8af24522018-03-07 11:37:45 -08001113 }
Chris Forbes8af24522018-03-07 11:37:45 -08001114}
1115
locke-lunargd9a069d2019-09-17 01:50:19 -06001116std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001117 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1118 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001119 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
1120
1121 for (auto id : accessible_ids) {
1122 auto insn = src->get_def(id);
1123 assert(insn != src->end());
1124
1125 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001126 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1127 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001128 auto d = src->get_decorations(insn.word(2));
1129 unsigned set = d.descriptor_set;
1130 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001131
1132 interface_var v = {};
1133 v.id = insn.word(2);
1134 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001135
locke-lunarg25b6c352020-08-06 17:44:18 -06001136 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
1137 !(d.flags & decoration_set::nonwritable_bit), v);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001138 if (v.is_writable) *has_writable_descriptor = true;
1139 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001140 if (d.flags & decoration_set::input_attachment_index_bit) {
1141 v.input_index = d.input_attachment_index;
1142 }
locke-lunarg654e3692020-06-04 17:19:15 -06001143 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001144 }
1145 }
1146
1147 return out;
1148}
1149
locke-lunarg96dc9632020-06-10 17:22:18 -06001150std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1151 const VkPipelineShaderStageCreateInfo &stage_info) {
1152 std::unordered_set<uint32_t> location_list;
1153 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1154 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1155 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1156 std::unordered_set<unsigned> store_members;
1157 std::unordered_map<unsigned, unsigned> accesschain_members;
1158
1159 for (auto insn : module) {
1160 switch (insn.opcode()) {
1161 case spv::OpStore:
1162 case spv::OpAtomicStore: {
1163 store_members.insert(insn.word(1)); // object id or AccessChain id
1164 break;
1165 }
1166 case spv::OpAccessChain: {
1167 // 2: AccessChain id, 3: object id
1168 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1169 break;
1170 }
1171 default:
1172 break;
1173 }
1174 }
1175 if (store_members.empty()) {
1176 return location_list;
1177 }
1178 for (auto output : outputs) {
1179 auto store_it = store_members.find(output.second.id);
1180 if (store_it != store_members.end()) {
1181 location_list.insert(output.first.first);
1182 store_members.erase(store_it);
1183 continue;
1184 }
1185 store_it = store_members.begin();
1186 while (store_it != store_members.end()) {
1187 auto accesschain_it = accesschain_members.find(*store_it);
1188 if (accesschain_it == accesschain_members.end()) {
1189 ++store_it;
1190 continue;
1191 }
1192 if (accesschain_it->second == output.second.id) {
1193 location_list.insert(output.first.first);
1194 store_members.erase(store_it);
1195 accesschain_members.erase(accesschain_it);
1196 break;
1197 }
1198 ++store_it;
1199 }
1200 }
1201 return location_list;
1202}
1203
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001204bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001205 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1206 // be specified only once.
1207 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1208 bool skip = false;
1209
1210 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1211 auto desc = &vi->pVertexBindingDescriptions[i];
1212 auto &binding = bindings[desc->binding];
1213 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001214 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001215 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1216 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001217 } else {
1218 binding = desc;
1219 }
1220 }
1221
1222 return skip;
1223}
1224
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001225bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1226 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001227 bool skip = false;
1228
Petr Kraus25810d02019-08-27 17:41:15 +02001229 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001230
1231 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001232 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001233 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001234 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1235 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1236 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001237 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1238 }
1239 }
1240 }
1241
Petr Kraus25810d02019-08-27 17:41:15 +02001242 struct AttribInputPair {
1243 const VkVertexInputAttributeDescription *attrib = nullptr;
1244 const interface_var *input = nullptr;
1245 };
1246 std::map<uint32_t, AttribInputPair> location_map;
1247 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1248 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001249
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001250 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001251 const auto location = location_it.first;
1252 const auto attrib = location_it.second.attrib;
1253 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001254
Petr Kraus25810d02019-08-27 17:41:15 +02001255 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001256 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1257 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001258 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001259 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1260 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001261 } else if (attrib && input) {
1262 const auto attrib_type = GetFormatType(attrib->format);
1263 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001264
1265 // Type checking
1266 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001267 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1268 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1269 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001270 }
Petr Kraus25810d02019-08-27 17:41:15 +02001271 } else { // !attrib && !input
1272 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001273 }
1274 }
1275
1276 return skip;
1277}
1278
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001279bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1280 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001281 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001282
Petr Kraus25810d02019-08-27 17:41:15 +02001283 const auto rpci = pipeline->rp_state->createInfo.ptr();
1284
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001285 struct Attachment {
1286 const VkAttachmentReference2KHR *reference = nullptr;
1287 const VkAttachmentDescription2KHR *attachment = nullptr;
1288 const interface_var *output = nullptr;
1289 };
1290 std::map<uint32_t, Attachment> location_map;
1291
Petr Kraus25810d02019-08-27 17:41:15 +02001292 const auto subpass = rpci->pSubpasses[subpass_index];
1293 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001294 auto const &reference = subpass.pColorAttachments[i];
1295 location_map[i].reference = &reference;
1296 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1297 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1298 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001299 }
1300 }
1301
Chris Forbes47567b72017-06-09 12:09:45 -07001302 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1303
Petr Kraus25810d02019-08-27 17:41:15 +02001304 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001305 for (const auto &output_it : outputs) {
1306 auto const location = output_it.first.first;
1307 location_map[location].output = &output_it.second;
1308 }
Chris Forbes47567b72017-06-09 12:09:45 -07001309
Petr Kraus25810d02019-08-27 17:41:15 +02001310 const bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1311 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001312
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001313 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001314 const auto reference = location_it.second.reference;
1315 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1316 continue;
1317 }
1318
Petr Kraus25810d02019-08-27 17:41:15 +02001319 const auto location = location_it.first;
1320 const auto attachment = location_it.second.attachment;
1321 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001322 if (attachment && !output) {
1323 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001324 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1325 "Attachment %" PRIu32
1326 " not written by fragment shader; undefined values will be written to attachment",
1327 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001328 }
1329 } else if (!attachment && output) {
1330 if (!(alphaToCoverageEnabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001331 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1332 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001333 }
Petr Kraus25810d02019-08-27 17:41:15 +02001334 } else if (attachment && output) {
1335 const auto attachment_type = GetFormatType(attachment->format);
1336 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001337
1338 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001339 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001340 skip |=
1341 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1342 "Attachment %" PRIu32
1343 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1344 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001345 }
Petr Kraus25810d02019-08-27 17:41:15 +02001346 } else { // !attachment && !output
1347 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001348 }
1349 }
1350
Petr Kraus25810d02019-08-27 17:41:15 +02001351 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
1352 bool locationZeroHasAlpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1353 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001354 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001355 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1356 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001357 }
1358
Chris Forbes47567b72017-06-09 12:09:45 -07001359 return skip;
1360}
1361
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001362// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1363// This function examines instructions in the static call tree for a write to this variable.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001364static bool IsPointSizeWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001365 auto type = builtin_instr.opcode();
1366 uint32_t target_id = builtin_instr.word(1);
1367 bool init_complete = false;
1368
1369 if (type == spv::OpMemberDecorate) {
1370 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1371 auto insn = entrypoint;
1372 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1373 switch (insn.opcode()) {
1374 case spv::OpTypePointer:
1375 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1376 target_id = insn.word(1);
1377 }
1378 break;
1379 case spv::OpVariable:
1380 if (insn.word(1) == target_id) {
1381 target_id = insn.word(2);
1382 init_complete = true;
1383 }
1384 break;
1385 }
1386 insn++;
1387 }
1388 }
1389
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001390 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1391
1392 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001393 std::unordered_set<uint32_t> worklist;
1394 worklist.insert(entrypoint.word(2));
1395
1396 // Follow instructions in call graph looking for writes to target
1397 while (!worklist.empty() && !found_write) {
1398 auto id_iter = worklist.begin();
1399 auto id = *id_iter;
1400 worklist.erase(id_iter);
1401
1402 auto insn = src->get_def(id);
1403 if (insn == src->end()) {
1404 continue;
1405 }
1406
1407 if (insn.opcode() == spv::OpFunction) {
1408 // Scan body of function looking for other function calls or items in our ID chain
1409 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1410 switch (insn.opcode()) {
1411 case spv::OpAccessChain:
1412 if (insn.word(3) == target_id) {
1413 if (type == spv::OpMemberDecorate) {
1414 auto value = GetConstantValue(src, insn.word(4));
1415 if (value == builtin_instr.word(2)) {
1416 target_id = insn.word(2);
1417 }
1418 } else {
1419 target_id = insn.word(2);
1420 }
1421 }
1422 break;
1423 case spv::OpStore:
1424 if (insn.word(1) == target_id) {
1425 found_write = true;
1426 }
1427 break;
1428 case spv::OpFunctionCall:
1429 worklist.insert(insn.word(3));
1430 break;
1431 }
1432 }
1433 }
1434 }
1435 return found_write;
1436}
1437
Chris Forbes47567b72017-06-09 12:09:45 -07001438// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1439// important for identifying the set of shader resources actually used by an entrypoint, for example.
1440// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1441// - NOT the shader input/output interfaces.
1442//
1443// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1444// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001445std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001446 std::unordered_set<uint32_t> ids;
1447 std::unordered_set<uint32_t> worklist;
1448 worklist.insert(entrypoint.word(2));
1449
1450 while (!worklist.empty()) {
1451 auto id_iter = worklist.begin();
1452 auto id = *id_iter;
1453 worklist.erase(id_iter);
1454
1455 auto insn = src->get_def(id);
1456 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001457 // 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 -07001458 // that we may not care about.
1459 continue;
1460 }
1461
1462 // Try to add to the output set
1463 if (!ids.insert(id).second) {
1464 continue; // If we already saw this id, we don't want to walk it again.
1465 }
1466
1467 switch (insn.opcode()) {
1468 case spv::OpFunction:
1469 // Scan whole body of the function, enlisting anything interesting
1470 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1471 switch (insn.opcode()) {
1472 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001473 worklist.insert(insn.word(3)); // ptr
1474 break;
1475 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001476 worklist.insert(insn.word(1)); // ptr
1477 break;
1478 case spv::OpAccessChain:
1479 case spv::OpInBoundsAccessChain:
1480 worklist.insert(insn.word(3)); // base ptr
1481 break;
1482 case spv::OpSampledImage:
1483 case spv::OpImageSampleImplicitLod:
1484 case spv::OpImageSampleExplicitLod:
1485 case spv::OpImageSampleDrefImplicitLod:
1486 case spv::OpImageSampleDrefExplicitLod:
1487 case spv::OpImageSampleProjImplicitLod:
1488 case spv::OpImageSampleProjExplicitLod:
1489 case spv::OpImageSampleProjDrefImplicitLod:
1490 case spv::OpImageSampleProjDrefExplicitLod:
1491 case spv::OpImageFetch:
1492 case spv::OpImageGather:
1493 case spv::OpImageDrefGather:
1494 case spv::OpImageRead:
1495 case spv::OpImage:
1496 case spv::OpImageQueryFormat:
1497 case spv::OpImageQueryOrder:
1498 case spv::OpImageQuerySizeLod:
1499 case spv::OpImageQuerySize:
1500 case spv::OpImageQueryLod:
1501 case spv::OpImageQueryLevels:
1502 case spv::OpImageQuerySamples:
1503 case spv::OpImageSparseSampleImplicitLod:
1504 case spv::OpImageSparseSampleExplicitLod:
1505 case spv::OpImageSparseSampleDrefImplicitLod:
1506 case spv::OpImageSparseSampleDrefExplicitLod:
1507 case spv::OpImageSparseSampleProjImplicitLod:
1508 case spv::OpImageSparseSampleProjExplicitLod:
1509 case spv::OpImageSparseSampleProjDrefImplicitLod:
1510 case spv::OpImageSparseSampleProjDrefExplicitLod:
1511 case spv::OpImageSparseFetch:
1512 case spv::OpImageSparseGather:
1513 case spv::OpImageSparseDrefGather:
1514 case spv::OpImageTexelPointer:
1515 worklist.insert(insn.word(3)); // Image or sampled image
1516 break;
1517 case spv::OpImageWrite:
1518 worklist.insert(insn.word(1)); // Image -- different operand order to above
1519 break;
1520 case spv::OpFunctionCall:
1521 for (uint32_t i = 3; i < insn.len(); i++) {
1522 worklist.insert(insn.word(i)); // fn itself, and all args
1523 }
1524 break;
1525
1526 case spv::OpExtInst:
1527 for (uint32_t i = 5; i < insn.len(); i++) {
1528 worklist.insert(insn.word(i)); // Operands to ext inst
1529 }
1530 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001531
1532 default: {
1533 if (AtomicOperation(insn.opcode())) {
1534 if (insn.opcode() == spv::OpAtomicStore) {
1535 worklist.insert(insn.word(1)); // ptr
1536 } else {
1537 worklist.insert(insn.word(3)); // ptr
1538 }
1539 }
1540 break;
1541 }
Chris Forbes47567b72017-06-09 12:09:45 -07001542 }
1543 }
1544 break;
1545 }
1546 }
1547
1548 return ids;
1549}
1550
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001551bool CoreChecks::ValidatePushConstantBlockAgainstPipeline(std::vector<VkPushConstantRange> const *push_constant_ranges,
1552 SHADER_MODULE_STATE const *src, spirv_inst_iter type,
1553 VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001554 bool skip = false;
1555
1556 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001557 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001558 assert(type != src->end());
1559
1560 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
locke-lunarg78486832020-09-09 19:39:42 -06001561 // TODO: arrays, matrices, weird sizes
Chris Forbes47567b72017-06-09 12:09:45 -07001562 for (auto insn : *src) {
1563 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1564 if (insn.word(3) == spv::DecorationOffset) {
Jeremy Hayesadf93862020-07-22 14:29:30 -06001565 auto const member = insn.word(2);
1566 auto const offset = insn.word(4);
locke-lunarg78486832020-09-09 19:39:42 -06001567 auto const size = 4; // Bytes; TODO: calculate this based on the type
Chris Forbes47567b72017-06-09 12:09:45 -07001568
1569 bool found_range = false;
1570 for (auto const &range : *push_constant_ranges) {
Jeremy Hayese883b362019-12-10 15:12:26 -07001571 if ((range.offset <= offset) && ((range.offset + range.size) >= (offset + size)) &&
1572 (range.stageFlags & stage)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001573 found_range = true;
1574
Chris Forbes47567b72017-06-09 12:09:45 -07001575 break;
1576 }
1577 }
1578
1579 if (!found_range) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001580 skip |= LogError(device, kVUID_Core_Shader_PushConstantOutOfRange,
Jeremy Hayesadf93862020-07-22 14:29:30 -06001581 "Shader push-constant buffer member %u at offset %u is not declared in pipeline layout",
1582 member, offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001583 }
1584 }
1585 }
1586 }
1587
1588 return skip;
1589}
1590
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001591bool CoreChecks::ValidatePushConstantUsage(std::vector<VkPushConstantRange> const *push_constant_ranges,
1592 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> accessible_ids,
1593 VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001594 bool skip = false;
1595
1596 for (auto id : accessible_ids) {
1597 auto def_insn = src->get_def(id);
1598 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001599 skip |= ValidatePushConstantBlockAgainstPipeline(push_constant_ranges, src, src->get_def(def_insn.word(1)), stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001600 }
1601 }
1602
1603 return skip;
1604}
1605
1606// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001607bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001608 bool skip = false;
1609
1610 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1611
1612 if (spec) {
1613 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001614 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001615 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
1616 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1617 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1618 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1619 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001620
1621 continue;
1622 }
Chris Forbes47567b72017-06-09 12:09:45 -07001623 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001624 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
1625 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1626 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1627 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1628 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001629 }
1630 }
1631 }
1632
1633 return skip;
1634}
1635
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001636// TODO (jbolz): Can this return a const reference?
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001637static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001638 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001639 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001640 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001641 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001642
1643 // 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 -05001644 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1645 if (type.opcode() == spv::OpTypeRuntimeArray) {
1646 descriptor_count = 0;
1647 type = module->get_def(type.word(2));
1648 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001649 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001650 type = module->get_def(type.word(2));
1651 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001652 if (type.word(2) == spv::StorageClassStorageBuffer) {
1653 is_storage_buffer = true;
1654 }
Chris Forbes47567b72017-06-09 12:09:45 -07001655 type = module->get_def(type.word(3));
1656 }
1657 }
1658
1659 switch (type.opcode()) {
1660 case spv::OpTypeStruct: {
1661 for (auto insn : *module) {
1662 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1663 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001664 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001665 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1666 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1667 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001668 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001669 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1670 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1671 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1672 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001673 }
Chris Forbes47567b72017-06-09 12:09:45 -07001674 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001675 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1676 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1677 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001678 }
1679 }
1680 }
1681
1682 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001683 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001684 }
1685
1686 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001687 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1688 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1689 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001690
Chris Forbes73c00bf2018-06-22 16:28:06 -07001691 case spv::OpTypeSampledImage: {
1692 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1693 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1694 auto image_type = module->get_def(type.word(2));
1695 auto dim = image_type.word(3);
1696 auto sampled = image_type.word(7);
1697 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001698 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1699 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001700 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001701 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001702 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1703 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001704
1705 case spv::OpTypeImage: {
1706 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1707 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1708 auto dim = type.word(3);
1709 auto sampled = type.word(7);
1710
1711 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001712 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1713 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001714 } else if (dim == spv::DimBuffer) {
1715 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001716 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1717 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001718 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001719 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1720 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001721 }
1722 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001723 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1724 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1725 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001726 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001727 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1728 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001729 }
1730 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001731 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001732 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001733 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001734
1735 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1736 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001737 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001738 }
1739}
1740
Jeff Bolze54ae892018-09-08 12:16:29 -05001741static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001742 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001743 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1744 if (ss.tellp()) ss << ", ";
1745 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001746 }
1747 return ss.str();
1748}
1749
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001750bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001751 if (!check) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001752 if (LogError(device, kVUID_Core_Shader_ExceedDeviceLimit,
1753 "Shader requires flag %s set in %s but it is not set on the device", flag, structure)) {
Jeff Bolzee743412019-06-20 22:24:32 -05001754 return true;
1755 }
1756 }
1757
1758 return false;
1759}
1760
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001761bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001762 if (!feature) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001763 if (LogError(device, kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device",
1764 feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001765 return true;
1766 }
1767 }
1768
1769 return false;
1770}
1771
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001772bool CoreChecks::RequireExtension(bool extension, char const *extension_name) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001773 if (!extension) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001774 if (LogError(device, kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
1775 extension_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001776 return true;
1777 }
1778 }
1779
1780 return false;
1781}
1782
John Zulaufac4c6e12019-07-01 16:05:58 -06001783bool CoreChecks::ValidateShaderCapabilities(SHADER_MODULE_STATE const *src, VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001784 bool skip = false;
1785
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001786 struct FeaturePointer {
1787 // Callable object to test if this feature is enabled in the given aggregate feature struct
1788 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1789
1790 // Test if feature pointer is populated
1791 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1792
1793 // Default and nullptr constructor to create an empty FeaturePointer
1794 FeaturePointer() : IsEnabled(nullptr) {}
1795 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1796
1797 // Constructors to populate FeaturePointer based on given pointer to member
1798 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1799 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001800 FeaturePointer(VkBool32 VkPhysicalDeviceVulkan11Features::*ptr)
1801 : IsEnabled([=](const DeviceFeatures &features) { return features.core11.*ptr; }) {}
1802 FeaturePointer(VkBool32 VkPhysicalDeviceVulkan12Features::*ptr)
1803 : IsEnabled([=](const DeviceFeatures &features) { return features.core12.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001804 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1805 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06001806 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
1807 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Jason Macnakc5a621d2019-06-10 12:42:50 -07001808 FeaturePointer(VkBool32 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::*ptr)
1809 : IsEnabled([=](const DeviceFeatures &features) { return features.compute_shader_derivatives_features.*ptr; }) {}
Jason Macnak325e8b52019-06-10 13:33:10 -07001810 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::*ptr)
1811 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_barycentric_features.*ptr; }) {}
Jason Macnakd7fddf82019-06-13 09:52:49 -07001812 FeaturePointer(VkBool32 VkPhysicalDeviceShaderImageFootprintFeaturesNV::*ptr)
1813 : IsEnabled([=](const DeviceFeatures &features) { return features.shader_image_footprint_features.*ptr; }) {}
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001814 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::*ptr)
1815 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_interlock_features.*ptr; }) {}
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001816 FeaturePointer(VkBool32 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::*ptr)
1817 : IsEnabled([=](const DeviceFeatures &features) { return features.demote_to_helper_invocation_features.*ptr; }) {}
Jeff Bolz443c2ca2020-03-19 12:11:51 -05001818 FeaturePointer(VkBool32 VkPhysicalDeviceRayTracingFeaturesKHR::*ptr)
1819 : IsEnabled([=](const DeviceFeatures &features) { return features.ray_tracing_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001820 };
1821
Chris Forbes47567b72017-06-09 12:09:45 -07001822 struct CapabilityInfo {
1823 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001824 FeaturePointer feature;
Tony-LunarG2ec96bb2019-11-26 13:43:02 -07001825 ExtEnabled DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001826 };
1827
Chris Forbes47567b72017-06-09 12:09:45 -07001828 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001829 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001830 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1831 // feature bits.
1832 {spv::CapabilityMatrix, {nullptr}},
1833 {spv::CapabilityShader, {nullptr}},
1834 {spv::CapabilityInputAttachment, {nullptr}},
1835 {spv::CapabilitySampled1D, {nullptr}},
1836 {spv::CapabilityImage1D, {nullptr}},
1837 {spv::CapabilitySampledBuffer, {nullptr}},
Toni Merilehtib13a4a22019-05-21 12:58:44 +03001838 {spv::CapabilityStorageImageExtendedFormats, {nullptr}},
Chris Forbes47567b72017-06-09 12:09:45 -07001839 {spv::CapabilityImageQuery, {nullptr}},
1840 {spv::CapabilityDerivativeControl, {nullptr}},
1841
1842 // Capabilities that are optionally supported, but require a feature to
1843 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001844 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1845 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1846 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1847 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1848 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1849 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1850 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1851 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1852 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1853 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1854 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1855 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1856 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1857 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1858 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1859 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1860 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1861 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1862 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1863 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001864 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1865 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1866 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1867 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001868
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001869 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001870 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::runtimeDescriptorArray", &VkPhysicalDeviceVulkan12Features::runtimeDescriptorArray}},
1871 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderInputAttachmentArrayDynamicIndexing}},
1872 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformTexelBufferArrayDynamicIndexing}},
1873 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageTexelBufferArrayDynamicIndexing}},
1874 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformBufferArrayNonUniformIndexing}},
1875 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderSampledImageArrayNonUniformIndexing}},
1876 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageBufferArrayNonUniformIndexing}},
1877 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageImageArrayNonUniformIndexing}},
1878 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderInputAttachmentArrayNonUniformIndexing}},
1879 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformTexelBufferArrayNonUniformIndexing}},
1880 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001881
1882 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001883 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1884 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1885 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1886 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1887 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1888 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1889 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1890 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Jason Macnakb7d091c2019-06-10 11:13:11 -07001891 {spv::CapabilityGroupNonUniformPartitionedNV, {VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_shader_subgroup_partitioned}},
aqnuep7033c702018-09-11 18:03:29 +02001892 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
amhaganfa0b34d2019-10-15 16:03:53 -04001893 {spv::CapabilityShaderClockKHR, {VK_KHR_SHADER_CLOCK_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_clock }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001894
Jason Macnakc5a621d2019-06-10 12:42:50 -07001895 {spv::CapabilityComputeDerivativeGroupQuadsNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
1896 {spv::CapabilityComputeDerivativeGroupLinearNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
Jason Macnakf7019582019-06-13 10:07:26 -07001897 {spv::CapabilityFragmentBarycentricNV, {"VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric", &VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric, &DeviceExtensions::vk_nv_fragment_shader_barycentric}},
Jason Macnakc5a621d2019-06-10 12:42:50 -07001898
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001899 {spv::CapabilityStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDeviceVulkan12Features::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1900 {spv::CapabilityUniformAndStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDeviceVulkan12Features::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1901 {spv::CapabilityStoragePushConstant8, {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDeviceVulkan12Features::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001902
Jason Macnakf7019582019-06-13 10:07:26 -07001903 {spv::CapabilityTransformFeedback, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
1904 {spv::CapabilityGeometryStreams, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001905
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001906 {spv::CapabilityFloat16, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceVulkan12Features::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1907 {spv::CapabilityInt8, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceVulkan12Features::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06001908
Jason Macnakd7fddf82019-06-13 09:52:49 -07001909 {spv::CapabilityImageFootprintNV, {"VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint", &VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint, &DeviceExtensions::vk_nv_shader_image_footprint}},
1910
Jeff Bolze4356752019-03-07 11:23:46 -06001911 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001912
Graeme Leese41e6b842019-08-02 10:49:14 +01001913 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserve", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1914 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserve", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1915 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZero", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1916 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTE", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1917 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZ", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001918
1919 {spv::CapabilityFragmentShaderSampleInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1920 {spv::CapabilityFragmentShaderPixelInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1921 {spv::CapabilityFragmentShaderShadingRateInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001922 {spv::CapabilityDemoteToHelperInvocationEXT, {"VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation", &VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation, &DeviceExtensions::vk_ext_shader_demote_to_helper_invocation}},
Jeff Bolz4563f2a2019-12-10 13:30:30 -06001923
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001924 {spv::CapabilityPhysicalStorageBufferAddresses, {"VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress", &VkPhysicalDeviceVulkan12Features::bufferDeviceAddress, &DeviceExtensions::vk_ext_buffer_device_address}},
Jeff Bolz4563f2a2019-12-10 13:30:30 -06001925 // Should be non-EXT token, but Android SPIRV-Headers are out of date, and the token value is the same anyway
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001926 {spv::CapabilityPhysicalStorageBufferAddressesEXT, {"VkPhysicalDeviceBufferDeviceAddressFeaturesEXT::bufferDeviceAddress", &VkPhysicalDeviceVulkan12Features::bufferDeviceAddress, &DeviceExtensions::vk_khr_buffer_device_address}},
Jeff Bolz443c2ca2020-03-19 12:11:51 -05001927
1928 {spv::CapabilityRayTracingProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayTracing", &VkPhysicalDeviceRayTracingFeaturesKHR::rayTracing, &DeviceExtensions::vk_khr_ray_tracing}},
1929 {spv::CapabilityRayQueryProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayQuery", &VkPhysicalDeviceRayTracingFeaturesKHR::rayQuery, &DeviceExtensions::vk_khr_ray_tracing}},
1930 {spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayTracingPrimitiveCulling", &VkPhysicalDeviceRayTracingFeaturesKHR::rayTracingPrimitiveCulling, &DeviceExtensions::vk_khr_ray_tracing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001931 };
1932 // clang-format on
1933
1934 for (auto insn : *src) {
1935 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001936 size_t n = capabilities.count(insn.word(1));
1937 if (1 == n) { // key occurs exactly once
1938 auto it = capabilities.find(insn.word(1));
1939 if (it != capabilities.end()) {
1940 if (it->second.feature) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001941 skip |= RequireFeature(it->second.feature.IsEnabled(enabled_features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001942 }
1943 if (it->second.extension) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001944 skip |= RequireExtension(IsExtEnabled((device_extensions.*(it->second.extension))), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001945 }
Chris Forbes47567b72017-06-09 12:09:45 -07001946 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001947 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1948 bool needs_feature = false, has_feature = false;
1949 bool needs_ext = false, has_ext = false;
1950 std::string feature_names = "(one of) [ ";
1951 std::string extension_names = feature_names;
1952 auto caps = capabilities.equal_range(insn.word(1));
1953 for (auto it = caps.first; it != caps.second; ++it) {
1954 if (it->second.feature) {
1955 needs_feature = true;
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001956 has_feature = has_feature || it->second.feature.IsEnabled(enabled_features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001957 feature_names += it->second.name;
1958 feature_names += " ";
1959 }
1960 if (it->second.extension) {
1961 needs_ext = true;
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001962 has_ext = has_ext || device_extensions.*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001963 extension_names += it->second.name;
1964 extension_names += " ";
1965 }
1966 }
1967 if (needs_feature) {
1968 feature_names += "]";
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001969 skip |= RequireFeature(has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001970 }
1971 if (needs_ext) {
1972 extension_names += "]";
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001973 skip |= RequireExtension(has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001974 }
Graeme Leesec82dbe02019-08-02 10:44:21 +01001975 }
1976
1977 { // Do group non-uniform checks
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001978 const VkSubgroupFeatureFlags supportedOperations = phys_dev_props_core11.subgroupSupportedOperations;
1979 const VkSubgroupFeatureFlags supportedStages = phys_dev_props_core11.subgroupSupportedStages;
Jeff Bolzee743412019-06-20 22:24:32 -05001980
1981 switch (insn.word(1)) {
1982 default:
1983 break;
1984 case spv::CapabilityGroupNonUniform:
1985 case spv::CapabilityGroupNonUniformVote:
1986 case spv::CapabilityGroupNonUniformArithmetic:
1987 case spv::CapabilityGroupNonUniformBallot:
1988 case spv::CapabilityGroupNonUniformShuffle:
1989 case spv::CapabilityGroupNonUniformShuffleRelative:
1990 case spv::CapabilityGroupNonUniformClustered:
1991 case spv::CapabilityGroupNonUniformQuad:
1992 case spv::CapabilityGroupNonUniformPartitionedNV:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001993 RequirePropertyFlag(supportedStages & stage, string_VkShaderStageFlagBits(stage),
Jeff Bolzee743412019-06-20 22:24:32 -05001994 "VkPhysicalDeviceSubgroupProperties::supportedStages");
1995 break;
1996 }
1997
1998 switch (insn.word(1)) {
1999 default:
2000 break;
2001 case spv::CapabilityGroupNonUniform:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002002 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT, "VK_SUBGROUP_FEATURE_BASIC_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002003 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2004 break;
2005 case spv::CapabilityGroupNonUniformVote:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002006 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT, "VK_SUBGROUP_FEATURE_VOTE_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002007 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2008 break;
2009 case spv::CapabilityGroupNonUniformArithmetic:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002010 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002011 "VK_SUBGROUP_FEATURE_ARITHMETIC_BIT",
2012 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2013 break;
2014 case spv::CapabilityGroupNonUniformBallot:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002015 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT, "VK_SUBGROUP_FEATURE_BALLOT_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002016 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2017 break;
2018 case spv::CapabilityGroupNonUniformShuffle:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002019 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002020 "VK_SUBGROUP_FEATURE_SHUFFLE_BIT",
2021 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2022 break;
2023 case spv::CapabilityGroupNonUniformShuffleRelative:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002024 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002025 "VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT",
2026 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2027 break;
2028 case spv::CapabilityGroupNonUniformClustered:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002029 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002030 "VK_SUBGROUP_FEATURE_CLUSTERED_BIT",
2031 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2032 break;
2033 case spv::CapabilityGroupNonUniformQuad:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002034 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT, "VK_SUBGROUP_FEATURE_QUAD_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002035 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2036 break;
2037 case spv::CapabilityGroupNonUniformPartitionedNV:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002038 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV,
Jeff Bolzee743412019-06-20 22:24:32 -05002039 "VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV",
2040 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2041 break;
2042 }
Chris Forbes47567b72017-06-09 12:09:45 -07002043 }
baldurk4095f932020-02-16 13:24:42 +00002044 } else if (insn.opcode() == spv::OpExtension) {
2045 std::string extension_name = (char const *)&insn.word(1);
2046
2047 if (extension_name == "SPV_KHR_non_semantic_info") {
2048 skip |= RequireExtension(IsExtEnabled(device_extensions.vk_khr_shader_non_semantic_info),
2049 VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME);
2050 }
Chris Forbes47567b72017-06-09 12:09:45 -07002051 }
2052 }
2053
Jeff Bolzee743412019-06-20 22:24:32 -05002054 return skip;
2055}
2056
locke-lunarg63e4daf2020-08-17 17:53:25 -06002057bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2058 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002059 bool skip = false;
2060
locke-lunarg63e4daf2020-08-17 17:53:25 -06002061 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002062 switch (stage) {
2063 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002064 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2065 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2066 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2067 case VK_SHADER_STAGE_MISS_BIT_NV:
2068 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2069 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2070 case VK_SHADER_STAGE_TASK_BIT_NV:
2071 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002072 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002073 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002074 break;
2075 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002076 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08002077 break;
2078 default:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002079 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08002080 break;
2081 }
2082 }
2083
Chris Forbes47567b72017-06-09 12:09:45 -07002084 return skip;
2085}
2086
Jeff Bolz526f2d52019-09-18 13:18:08 -05002087bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002088 bool skip = false;
2089
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002090 auto const subgroup_props = phys_dev_props_core11;
Jeff Bolzee743412019-06-20 22:24:32 -05002091
Jeff Bolz526f2d52019-09-18 13:18:08 -05002092 for (auto inst : *module) {
Jeff Bolzee743412019-06-20 22:24:32 -05002093 // Check the quad operations.
2094 switch (inst.opcode()) {
2095 default:
2096 break;
2097 case spv::OpGroupNonUniformQuadBroadcast:
2098 case spv::OpGroupNonUniformQuadSwap:
2099 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002100 skip |= RequireFeature(subgroup_props.subgroupQuadOperationsInAllStages,
Jeff Bolzee743412019-06-20 22:24:32 -05002101 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages");
2102 }
2103 break;
2104 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002105
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002106 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
Jeff Bolz526f2d52019-09-18 13:18:08 -05002107 switch (inst.opcode()) {
2108 default:
2109 break;
2110 case spv::OpGroupNonUniformAllEqual:
2111 case spv::OpGroupNonUniformBroadcast:
2112 case spv::OpGroupNonUniformBroadcastFirst:
2113 case spv::OpGroupNonUniformShuffle:
2114 case spv::OpGroupNonUniformShuffleXor:
2115 case spv::OpGroupNonUniformShuffleUp:
2116 case spv::OpGroupNonUniformShuffleDown:
2117 case spv::OpGroupNonUniformIAdd:
2118 case spv::OpGroupNonUniformFAdd:
2119 case spv::OpGroupNonUniformIMul:
2120 case spv::OpGroupNonUniformFMul:
2121 case spv::OpGroupNonUniformSMin:
2122 case spv::OpGroupNonUniformUMin:
2123 case spv::OpGroupNonUniformFMin:
2124 case spv::OpGroupNonUniformSMax:
2125 case spv::OpGroupNonUniformUMax:
2126 case spv::OpGroupNonUniformFMax:
2127 case spv::OpGroupNonUniformBitwiseAnd:
2128 case spv::OpGroupNonUniformBitwiseOr:
2129 case spv::OpGroupNonUniformBitwiseXor:
2130 case spv::OpGroupNonUniformLogicalAnd:
2131 case spv::OpGroupNonUniformLogicalOr:
2132 case spv::OpGroupNonUniformLogicalXor:
2133 case spv::OpGroupNonUniformQuadBroadcast:
2134 case spv::OpGroupNonUniformQuadSwap: {
2135 auto type = module->get_def(inst.word(1));
2136
2137 if (type.opcode() == spv::OpTypeVector) {
2138 // Get the element type
2139 type = module->get_def(type.word(2));
2140 }
2141
2142 if (type.opcode() == spv::OpTypeBool) {
2143 break;
2144 }
2145
2146 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2147 const uint32_t width = type.word(2);
2148
2149 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2150 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002151 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
Tony-LunarGa74d3fe2019-11-22 15:43:20 -07002152 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes");
Jeff Bolz526f2d52019-09-18 13:18:08 -05002153 }
2154 break;
2155 }
2156 }
2157 }
Jeff Bolzee743412019-06-20 22:24:32 -05002158 }
2159
2160 return skip;
2161}
2162
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002163bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002164 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002165 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2166 pStage->stage == VK_SHADER_STAGE_ALL) {
2167 return false;
2168 }
2169
2170 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002171 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002172
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002173 std::set<uint32_t> patchIDs;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002174 struct Variable {
2175 uint32_t baseTypePtrID;
2176 uint32_t ID;
2177 uint32_t storageClass;
2178 };
2179 std::vector<Variable> variables;
2180
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002181 uint32_t numVertices = 0;
2182
Jeff Bolzf234bf82019-11-04 14:07:15 -06002183 auto entrypointVariables = FindEntrypointInterfaces(entrypoint);
2184
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002185 for (auto insn : *src) {
2186 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002187 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002188 case spv::OpDecorate:
2189 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002190 case spv::DecorationPatch: {
2191 patchIDs.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002192 break;
2193 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002194 default:
2195 break;
2196 }
2197 break;
2198 // Find all input and output variables
2199 case spv::OpVariable: {
2200 Variable var = {};
2201 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002202 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2203 // Only include variables in the entrypoint's interface
2204 find(entrypointVariables.begin(), entrypointVariables.end(), insn.word(2)) != entrypointVariables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002205 var.baseTypePtrID = insn.word(1);
2206 var.ID = insn.word(2);
2207 variables.push_back(var);
2208 }
2209 break;
2210 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002211 case spv::OpExecutionMode:
2212 if (insn.word(1) == entrypoint.word(2)) {
2213 switch (insn.word(2)) {
2214 default:
2215 break;
2216 case spv::ExecutionModeOutputVertices:
2217 numVertices = insn.word(3);
2218 break;
2219 }
2220 }
2221 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002222 default:
2223 break;
2224 }
2225 }
2226
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002227 bool strip_output_array_level =
2228 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2229 bool strip_input_array_level =
2230 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2231 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2232
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002233 uint32_t numCompIn = 0, numCompOut = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002234 int maxCompIn = 0, maxCompOut = 0;
2235
2236 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2237 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2238
2239 // Find max component location used for input variables.
2240 for (auto &var : inputs) {
2241 int location = var.first.first;
2242 int component = var.first.second;
2243 interface_var &iv = var.second;
2244
2245 // Only need to look at the first location, since we use the type's whole size
2246 if (iv.offset != 0) {
2247 continue;
2248 }
2249
2250 if (iv.is_patch) {
2251 continue;
2252 }
2253
2254 int numComponents = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2255 maxCompIn = std::max(maxCompIn, location * 4 + component + numComponents);
2256 }
2257
2258 // Find max component location used for output variables.
2259 for (auto &var : outputs) {
2260 int location = var.first.first;
2261 int component = var.first.second;
2262 interface_var &iv = var.second;
2263
2264 // Only need to look at the first location, since we use the type's whole size
2265 if (iv.offset != 0) {
2266 continue;
2267 }
2268
2269 if (iv.is_patch) {
2270 continue;
2271 }
2272
2273 int numComponents = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2274 maxCompOut = std::max(maxCompOut, location * 4 + component + numComponents);
2275 }
2276
2277 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2278 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002279 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002280 // Check if the variable is a patch. Patches can also be members of blocks,
2281 // but if they are then the top-level arrayness has already been stripped
2282 // by the time GetComponentsConsumedByType gets to it.
2283 bool isPatch = patchIDs.find(var.ID) != patchIDs.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002284
2285 if (var.storageClass == spv::StorageClassInput) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002286 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002287 } else { // var.storageClass == spv::StorageClassOutput
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002288 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002289 }
2290 }
2291
2292 switch (pStage->stage) {
2293 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002294 if (numCompOut > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002295 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2296 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2297 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2298 "components by %u components",
2299 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002300 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002301 if (maxCompOut > (int)limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002302 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2303 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2304 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2305 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002306 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002307 break;
2308
2309 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002310 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002311 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2312 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2313 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2314 "components by %u components",
2315 limits.maxTessellationControlPerVertexInputComponents,
2316 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002317 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002318 if (maxCompIn > (int)limits.maxTessellationControlPerVertexInputComponents) {
2319 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002320 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2321 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2322 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2323 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002324 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002325 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002326 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2327 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2328 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2329 "components by %u components",
2330 limits.maxTessellationControlPerVertexOutputComponents,
2331 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002332 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002333 if (maxCompOut > (int)limits.maxTessellationControlPerVertexOutputComponents) {
2334 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002335 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2336 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2337 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2338 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002339 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002340 break;
2341
2342 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002343 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002344 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2345 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2346 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2347 "components by %u components",
2348 limits.maxTessellationEvaluationInputComponents,
2349 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002350 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002351 if (maxCompIn > (int)limits.maxTessellationEvaluationInputComponents) {
2352 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002353 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2354 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2355 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2356 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002357 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002358 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002359 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2360 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2361 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2362 "components by %u components",
2363 limits.maxTessellationEvaluationOutputComponents,
2364 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002365 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002366 if (maxCompOut > (int)limits.maxTessellationEvaluationOutputComponents) {
2367 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002368 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2369 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2370 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2371 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002372 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002373 break;
2374
2375 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002376 if (numCompIn > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002377 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2378 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2379 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2380 "components by %u components",
2381 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002382 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002383 if (maxCompIn > (int)limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002384 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2385 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2386 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2387 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002388 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002389 if (numCompOut > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002390 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2391 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2392 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2393 "components by %u components",
2394 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002395 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002396 if (maxCompOut > (int)limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002397 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2398 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2399 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2400 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002401 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002402 if (numCompOut * numVertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002403 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2404 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2405 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2406 "components by %u components",
2407 limits.maxGeometryTotalOutputComponents,
2408 numCompOut * numVertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002409 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002410 break;
2411
2412 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002413 if (numCompIn > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002414 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2415 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2416 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2417 "components by %u components",
2418 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002419 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002420 if (maxCompIn > (int)limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002421 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2422 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2423 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2424 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002425 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002426 break;
2427
Jeff Bolz148d94e2018-12-13 21:25:56 -06002428 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2429 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2430 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2431 case VK_SHADER_STAGE_MISS_BIT_NV:
2432 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2433 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2434 case VK_SHADER_STAGE_TASK_BIT_NV:
2435 case VK_SHADER_STAGE_MESH_BIT_NV:
2436 break;
2437
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002438 default:
2439 assert(false); // This should never happen
2440 }
2441 return skip;
2442}
2443
sfricke-samsungdc96f302020-03-18 20:42:10 -07002444bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2445 bool skip = false;
2446 uint32_t total_resources = 0;
2447
2448 // Only currently testing for graphics and compute pipelines
2449 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2450 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2451 return false;
2452 }
2453
2454 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2455 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2456 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2457 }
2458
2459 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2460 // input from CreatePipeline and CreatePipelineLayout level
2461 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2462 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2463 continue;
2464 }
2465
2466 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2467 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2468 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2469 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2470 // Check only descriptor types listed in maxPerStageResources description in spec
2471 switch (binding->descriptorType) {
2472 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2473 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2474 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2475 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2476 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2477 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2478 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2479 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2480 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2481 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2482 total_resources += binding->descriptorCount;
2483 break;
2484 default:
2485 break;
2486 }
2487 }
2488 }
2489 }
2490
2491 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2492 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2493 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2494 skip |= LogError(pipeline->pipeline, vuid,
2495 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2496 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2497 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2498 }
2499
2500 return skip;
2501}
2502
Jeff Bolze4356752019-03-07 11:23:46 -06002503// copy the specialization constant value into buf, if it is present
2504void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2505 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2506
2507 if (spec && spec_id < spec->mapEntryCount) {
2508 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2509 }
2510}
2511
2512// Fill in value with the constant or specialization constant value, if available.
2513// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002514static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002515 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2516 auto type_id = src->get_def(insn.word(1));
2517 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2518 return false;
2519 }
2520 switch (insn.opcode()) {
2521 case spv::OpSpecConstant:
2522 *value = insn.word(3);
2523 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2524 return true;
2525 case spv::OpConstant:
2526 *value = insn.word(3);
2527 return true;
2528 default:
2529 return false;
2530 }
2531}
2532
2533// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002534VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002535 switch (insn.opcode()) {
2536 case spv::OpTypeInt:
2537 switch (insn.word(2)) {
2538 case 8:
2539 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2540 case 16:
2541 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2542 case 32:
2543 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2544 case 64:
2545 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2546 default:
2547 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2548 }
2549 case spv::OpTypeFloat:
2550 switch (insn.word(2)) {
2551 case 16:
2552 return VK_COMPONENT_TYPE_FLOAT16_NV;
2553 case 32:
2554 return VK_COMPONENT_TYPE_FLOAT32_NV;
2555 case 64:
2556 return VK_COMPONENT_TYPE_FLOAT64_NV;
2557 default:
2558 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2559 }
2560 default:
2561 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2562 }
2563}
2564
2565// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2566// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002567bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002568 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002569 bool skip = false;
2570
2571 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2572 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2573 // Map SPIR-V result ID to the ID of its type.
2574 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2575
2576 struct CoopMatType {
2577 uint32_t scope, rows, cols;
2578 VkComponentTypeNV component_type;
2579 bool all_constant;
2580
2581 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2582
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002583 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002584 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2585 spirv_inst_iter insn = src->get_def(id);
2586 uint32_t component_type_id = insn.word(2);
2587 uint32_t scope_id = insn.word(3);
2588 uint32_t rows_id = insn.word(4);
2589 uint32_t cols_id = insn.word(5);
2590 auto component_type_iter = src->get_def(component_type_id);
2591 auto scope_iter = src->get_def(scope_id);
2592 auto rows_iter = src->get_def(rows_id);
2593 auto cols_iter = src->get_def(cols_id);
2594
2595 all_constant = true;
2596 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2597 all_constant = false;
2598 }
2599 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2600 all_constant = false;
2601 }
2602 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2603 all_constant = false;
2604 }
2605 component_type = GetComponentType(component_type_iter, src);
2606 }
2607 };
2608
2609 bool seen_coopmat_capability = false;
2610
2611 for (auto insn : *src) {
2612 // Whitelist instructions whose result can be a cooperative matrix type, and
2613 // keep track of their types. It would be nice if SPIRV-Headers generated code
2614 // to identify which instructions have a result type and result id. Lacking that,
2615 // this whitelist is based on the set of instructions that
2616 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2617 switch (insn.opcode()) {
2618 case spv::OpLoad:
2619 case spv::OpCooperativeMatrixLoadNV:
2620 case spv::OpCooperativeMatrixMulAddNV:
2621 case spv::OpSNegate:
2622 case spv::OpFNegate:
2623 case spv::OpIAdd:
2624 case spv::OpFAdd:
2625 case spv::OpISub:
2626 case spv::OpFSub:
2627 case spv::OpFDiv:
2628 case spv::OpSDiv:
2629 case spv::OpUDiv:
2630 case spv::OpMatrixTimesScalar:
2631 case spv::OpConstantComposite:
2632 case spv::OpCompositeConstruct:
2633 case spv::OpConvertFToU:
2634 case spv::OpConvertFToS:
2635 case spv::OpConvertSToF:
2636 case spv::OpConvertUToF:
2637 case spv::OpUConvert:
2638 case spv::OpSConvert:
2639 case spv::OpFConvert:
2640 id_to_type_id[insn.word(2)] = insn.word(1);
2641 break;
2642 default:
2643 break;
2644 }
2645
2646 switch (insn.opcode()) {
2647 case spv::OpDecorate:
2648 if (insn.word(2) == spv::DecorationSpecId) {
2649 id_to_spec_id[insn.word(1)] = insn.word(3);
2650 }
2651 break;
2652 case spv::OpCapability:
2653 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2654 seen_coopmat_capability = true;
2655
2656 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002657 skip |= LogError(
2658 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2659 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2660 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002661 }
2662 }
2663 break;
2664 case spv::OpMemoryModel:
2665 // If the capability isn't enabled, don't bother with the rest of this function.
2666 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2667 if (!seen_coopmat_capability) {
2668 return skip;
2669 }
2670 break;
2671 case spv::OpTypeCooperativeMatrixNV: {
2672 CoopMatType M;
2673 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2674
2675 if (M.all_constant) {
2676 // Validate that the type parameters are all supported for one of the
2677 // operands of a cooperative matrix property.
2678 bool valid = false;
2679 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2680 if (cooperative_matrix_properties[i].AType == M.component_type &&
2681 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2682 cooperative_matrix_properties[i].scope == M.scope) {
2683 valid = true;
2684 break;
2685 }
2686 if (cooperative_matrix_properties[i].BType == M.component_type &&
2687 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2688 cooperative_matrix_properties[i].scope == M.scope) {
2689 valid = true;
2690 break;
2691 }
2692 if (cooperative_matrix_properties[i].CType == M.component_type &&
2693 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2694 cooperative_matrix_properties[i].scope == M.scope) {
2695 valid = true;
2696 break;
2697 }
2698 if (cooperative_matrix_properties[i].DType == M.component_type &&
2699 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2700 cooperative_matrix_properties[i].scope == M.scope) {
2701 valid = true;
2702 break;
2703 }
2704 }
2705 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002706 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2707 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2708 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002709 }
2710 }
2711 break;
2712 }
2713 case spv::OpCooperativeMatrixMulAddNV: {
2714 CoopMatType A, B, C, D;
2715 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2716 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2717 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2718 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002719 // Couldn't find type of matrix
2720 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002721 break;
2722 }
2723 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2724 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2725 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2726 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2727
2728 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2729 // Validate that the type parameters are all supported for the same
2730 // cooperative matrix property.
2731 bool valid = false;
2732 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2733 if (cooperative_matrix_properties[i].AType == A.component_type &&
2734 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2735 cooperative_matrix_properties[i].scope == A.scope &&
2736
2737 cooperative_matrix_properties[i].BType == B.component_type &&
2738 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2739 cooperative_matrix_properties[i].scope == B.scope &&
2740
2741 cooperative_matrix_properties[i].CType == C.component_type &&
2742 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2743 cooperative_matrix_properties[i].scope == C.scope &&
2744
2745 cooperative_matrix_properties[i].DType == D.component_type &&
2746 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2747 cooperative_matrix_properties[i].scope == D.scope) {
2748 valid = true;
2749 break;
2750 }
2751 }
2752 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002753 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2754 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2755 "VkCooperativeMatrixPropertiesNV",
2756 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002757 }
2758 }
2759 break;
2760 }
2761 default:
2762 break;
2763 }
2764 }
2765
2766 return skip;
2767}
2768
John Zulaufac4c6e12019-07-01 16:05:58 -06002769bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002770 auto entrypoint_id = entrypoint.word(2);
2771
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002772 // The first denorm execution mode encountered, along with its bit width.
2773 // Used to check if SeparateDenormSettings is respected.
2774 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002775
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002776 // The first rounding mode encountered, along with its bit width.
2777 // Used to check if SeparateRoundingModeSettings is respected.
2778 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002779
2780 bool skip = false;
2781
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002782 uint32_t verticesOut = 0;
2783 uint32_t invocations = 0;
2784
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002785 for (auto insn : *src) {
2786 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2787 auto mode = insn.word(2);
2788 switch (mode) {
2789 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2790 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002791 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2792 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2793 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002794 skip |= LogError(
2795 device, kVUID_Core_Shader_FeatureNotEnabled,
2796 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2797 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002798 }
2799 break;
2800 }
2801
2802 case spv::ExecutionModeDenormPreserve: {
2803 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002804 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2805 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2806 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002807 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2808 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2809 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002810 }
2811
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002812 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2813 // Register the first denorm execution mode found
2814 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002815 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002816 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002817 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2818 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002819 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2820 "Shader uses different denorm execution modes for 16 and 64-bit but "
2821 "denormBehaviorIndependence is "
2822 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002823 }
2824 break;
2825
2826 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2827 break;
2828
2829 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002830 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2831 "Shader uses different denorm execution modes for different bit widths but "
2832 "denormBehaviorIndependence is "
2833 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002834 break;
2835
2836 default:
2837 break;
2838 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002839 }
2840 break;
2841 }
2842
2843 case spv::ExecutionModeDenormFlushToZero: {
2844 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002845 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2846 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2847 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002848 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2849 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2850 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002851 }
2852
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002853 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2854 // Register the first denorm execution mode found
2855 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002856 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002857 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002858 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2859 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002860 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2861 "Shader uses different denorm execution modes for 16 and 64-bit but "
2862 "denormBehaviorIndependence is "
2863 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002864 }
2865 break;
2866
2867 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2868 break;
2869
2870 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002871 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2872 "Shader uses different denorm execution modes for different bit widths but "
2873 "denormBehaviorIndependence is "
2874 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002875 break;
2876
2877 default:
2878 break;
2879 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002880 }
2881 break;
2882 }
2883
2884 case spv::ExecutionModeRoundingModeRTE: {
2885 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002886 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
2887 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
2888 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002889 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2890 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2891 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002892 }
2893
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002894 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2895 // Register the first rounding mode found
2896 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002897 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002898 switch (phys_dev_props_core12.roundingModeIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002899 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2900 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002901 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2902 "Shader uses different rounding modes for 16 and 64-bit but "
2903 "roundingModeIndependence is "
2904 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002905 }
2906 break;
2907
2908 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2909 break;
2910
2911 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002912 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2913 "Shader uses different rounding modes for different bit widths but "
2914 "roundingModeIndependence is "
2915 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002916 break;
2917
2918 default:
2919 break;
2920 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002921 }
2922 break;
2923 }
2924
2925 case spv::ExecutionModeRoundingModeRTZ: {
2926 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002927 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
2928 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
2929 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002930 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2931 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
2932 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002933 }
2934
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002935 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2936 // Register the first rounding mode found
2937 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002938 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002939 switch (phys_dev_props_core12.roundingModeIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002940 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2941 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002942 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2943 "Shader uses different rounding modes for 16 and 64-bit but "
2944 "roundingModeIndependence is "
2945 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002946 }
2947 break;
2948
2949 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2950 break;
2951
2952 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002953 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2954 "Shader uses different rounding modes for different bit widths but "
2955 "roundingModeIndependence is "
2956 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002957 break;
2958
2959 default:
2960 break;
2961 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002962 }
2963 break;
2964 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002965
2966 case spv::ExecutionModeOutputVertices: {
2967 verticesOut = insn.word(3);
2968 break;
2969 }
2970
2971 case spv::ExecutionModeInvocations: {
2972 invocations = insn.word(3);
2973 break;
2974 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002975 }
2976 }
2977 }
2978
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002979 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
2980 if (verticesOut == 0 || verticesOut > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002981 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
2982 "Geometry shader entry point must have an OpExecutionMode instruction that "
2983 "specifies a maximum output vertex count that is greater than 0 and less "
2984 "than or equal to maxGeometryOutputVertices. "
2985 "OutputVertices=%d, maxGeometryOutputVertices=%d",
2986 verticesOut, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002987 }
2988
2989 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002990 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
2991 "Geometry shader entry point must have an OpExecutionMode instruction that "
2992 "specifies an invocation count that is greater than 0 and less "
2993 "than or equal to maxGeometryShaderInvocations. "
2994 "Invocations=%d, maxGeometryShaderInvocations=%d",
2995 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002996 }
2997 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002998 return skip;
2999}
3000
locke-lunargd9a069d2019-09-17 01:50:19 -06003001uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003002 auto type = module->get_def(type_id);
3003
3004 while (true) {
3005 switch (type.opcode()) {
3006 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003007 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003008 case spv::OpTypeSampledImage:
3009 type = module->get_def(type.word(2));
3010 break;
3011 case spv::OpTypePointer:
3012 type = module->get_def(type.word(3));
3013 break;
3014 case spv::OpTypeImage: {
3015 auto dim = type.word(3);
3016 auto arrayed = type.word(5);
3017 auto msaa = type.word(6);
3018
Chris Forbes74ba2232018-08-27 15:19:27 -07003019 uint32_t bits = 0;
3020 switch (GetFundamentalType(module, type.word(2))) {
3021 case FORMAT_TYPE_FLOAT:
3022 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3023 break;
3024 case FORMAT_TYPE_UINT:
3025 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3026 break;
3027 case FORMAT_TYPE_SINT:
3028 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3029 break;
3030 default:
3031 break;
3032 }
3033
Chris Forbes47567b72017-06-09 12:09:45 -07003034 switch (dim) {
3035 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003036 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3037 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003038 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003039 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3040 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3041 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003042 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003043 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3044 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003045 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003046 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3047 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003048 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003049 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3050 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003051 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003052 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003053 }
3054 }
3055 default:
3056 return 0;
3057 }
3058 }
3059}
3060
3061// For given pipelineLayout verify that the set_layout_node at slot.first
3062// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003063static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003064 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003065 if (!pipelineLayout) return nullptr;
3066
3067 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3068
3069 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3070}
3071
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003072int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3073 if (module == nullptr) return -1;
3074
3075 auto type = module->get_def(resource.type_id);
3076 while (true) {
3077 switch (type.opcode()) {
3078 case spv::OpTypeSampledImage:
3079 type = module->get_def(type.word(2));
3080 break;
3081 case spv::OpTypePointer:
3082 type = module->get_def(type.word(3));
3083 break;
3084 case spv::OpTypeImage:
3085 return type.word(3);
3086 default:
3087 return -1;
3088 }
3089 }
3090}
3091
3092bool 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 -06003093 for (auto insn : *src) {
3094 if (insn.opcode() == spv::OpEntryPoint) {
3095 auto executionModel = insn.word(1);
3096 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
3097 if (entrypointStageBits == VK_SHADER_STAGE_COMPUTE_BIT) {
3098 auto entrypoint_id = insn.word(2);
3099 for (auto insn1 : *src) {
3100 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3101 insn1.word(2) == spv::ExecutionModeLocalSize) {
3102 local_size_x = insn1.word(3);
3103 local_size_y = insn1.word(4);
3104 local_size_z = insn1.word(5);
3105 return true;
3106 }
3107 }
3108 }
3109 }
3110 }
3111 return false;
3112}
3113
locke-lunargd9a069d2019-09-17 01:50:19 -06003114void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003115 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003116 bool is_point_mode = false;
3117
3118 for (auto insn : *src) {
3119 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3120 switch (insn.word(2)) {
3121 case spv::ExecutionModePointMode:
3122 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3123 is_point_mode = true;
3124 break;
3125
3126 case spv::ExecutionModeOutputPoints:
3127 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3128 break;
3129
3130 case spv::ExecutionModeIsolines:
3131 case spv::ExecutionModeOutputLineStrip:
3132 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3133 break;
3134
3135 case spv::ExecutionModeTriangles:
3136 case spv::ExecutionModeQuads:
3137 case spv::ExecutionModeOutputTriangleStrip:
3138 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3139 break;
3140 }
3141 }
3142 }
3143
3144 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3145}
3146
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003147// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3148// o If there is only a vertex shader : gl_PointSize must be written when using points
3149// o If there is a geometry or tessellation shader:
3150// - If shaderTessellationAndGeometryPointSize feature is enabled:
3151// * gl_PointSize must be written in the final geometry stage
3152// - If shaderTessellationAndGeometryPointSize feature is disabled:
3153// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003154bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003155 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003156 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3157 return false;
3158 }
3159
3160 bool pointsize_written = false;
3161 bool skip = false;
3162
3163 // Search for PointSize built-in decorations
3164 std::vector<uint32_t> pointsize_builtin_offsets;
3165 spirv_inst_iter insn = entrypoint;
3166 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3167 if (insn.opcode() == spv::OpMemberDecorate) {
3168 if (insn.word(3) == spv::DecorationBuiltIn) {
3169 if (insn.word(4) == spv::BuiltInPointSize) {
3170 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
3171 }
3172 }
3173 } else if (insn.opcode() == spv::OpDecorate) {
3174 if (insn.word(2) == spv::DecorationBuiltIn) {
3175 if (insn.word(3) == spv::BuiltInPointSize) {
3176 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
3177 }
3178 }
3179 }
3180
3181 insn++;
3182 }
3183
3184 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003185 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003186 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003187 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3188 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3189 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003190 }
3191 } else if (!pointsize_written) {
3192 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003193 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3194 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3195 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003196 }
3197 return skip;
3198}
John Zulauf14c355b2019-06-27 16:09:37 -06003199
3200bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3201 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003202 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003203 bool skip = false;
3204
3205 // Check the module
3206 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003207 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3208 "%s does not contain valid spirv for stage %s.",
3209 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003210 }
3211
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003212 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3213 // specializations should be applied and validated.
3214 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3215 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3216 // Gather the specialization-constant values.
3217 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003218 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003219 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3220 id_value_map.reserve(specialization_info->mapEntryCount);
3221 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3222 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003223
Jeremy Hayes521221d2020-01-15 16:48:49 -07003224 // Expect only scalar types.
3225 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3226 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3227 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003228 }
3229
3230 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003231 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003232 spvtools::Optimizer optimizer(spirv_environment);
3233 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3234 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003235 skip |= LogError(
3236 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003237 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3238 };
3239 optimizer.SetMessageConsumer(consumer);
3240 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3241 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3242 std::vector<uint32_t> specialized_spirv;
3243 auto const optimized =
3244 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3245 assert(optimized == true);
3246
3247 if (optimized) {
3248 spv_context ctx = spvContextCreate(spirv_environment);
3249 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3250 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003251 spvtools::ValidatorOptions options;
3252 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003253 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3254 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003255 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003256 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3257 report_data->FormatHandle(module->vk_shader_module).c_str(),
3258 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003259 }
3260
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003261 spvDiagnosticDestroy(diag);
3262 spvContextDestroy(ctx);
3263 }
3264 }
3265
John Zulauf14c355b2019-06-27 16:09:37 -06003266 // Check the entrypoint
3267 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003268 skip |=
3269 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3270 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003271 }
3272 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3273
3274 // Mark accessible ids
3275 auto &accessible_ids = stage_state.accessible_ids;
3276
Chris Forbes47567b72017-06-09 12:09:45 -07003277 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003278 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3279 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003280
Chris Forbes349b3132018-03-07 11:38:08 -08003281 // Validate shader capabilities against enabled device features
Jeff Bolzee743412019-06-20 22:24:32 -05003282 skip |= ValidateShaderCapabilities(module, pStage->stage);
locke-lunarg63e4daf2020-08-17 17:53:25 -06003283 skip |=
3284 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003285 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003286 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Jeff Bolz526f2d52019-09-18 13:18:08 -05003287 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003288 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003289 skip |= ValidateSpecializationOffsets(pStage);
3290 skip |= ValidatePushConstantUsage(pipeline->pipeline_layout->push_constant_ranges.get(), module, accessible_ids, pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003291 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003292 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003293 }
Jeff Bolze4356752019-03-07 11:23:46 -06003294 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07003295
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003296 std::string vuid_layout_mismatch;
3297 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3298 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3299 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3300 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3301 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3302 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3303 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3304 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3305 }
3306
Chris Forbes47567b72017-06-09 12:09:45 -07003307 // Validate descriptor use
3308 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003309 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003310 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003311 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05003312 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07003313
3314 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003315 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003316 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3317 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003318 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003319 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003320 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3321 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003322 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003323 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003324 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3325 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3326 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003327 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003328 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003329 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3330 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003331 }
3332 }
3333
3334 // Validate use of input attachments against subpass structure
3335 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003336 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003337
Petr Krause91f7a12017-12-14 20:57:36 +01003338 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003339 auto subpass = pipeline->graphicsPipelineCI.subpass;
3340
3341 for (auto use : input_attachment_uses) {
3342 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3343 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003344 ? input_attachments[use.first].attachment
3345 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003346
3347 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003348 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3349 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003350 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003351 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003352 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3353 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3354 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003355 }
3356 }
3357 }
Lockeaa8fdc02019-04-02 11:59:20 -06003358 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3359 skip |= ValidateComputeWorkGroupSizes(module);
3360 }
Chris Forbes47567b72017-06-09 12:09:45 -07003361 return skip;
3362}
3363
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003364bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3365 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3366 spirv_inst_iter consumer_entrypoint,
3367 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003368 bool skip = false;
3369
3370 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003371 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3372 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003373
3374 auto a_it = outputs.begin();
3375 auto b_it = inputs.begin();
3376
3377 // Maps sorted by key (location); walk them together to find mismatches
3378 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3379 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3380 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3381 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3382 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3383
3384 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003385 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3386 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3387 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003388 a_it++;
3389 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003390 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3391 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3392 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003393 b_it++;
3394 } else {
3395 // subtleties of arrayed interfaces:
3396 // - if is_patch, then the member is not arrayed, even though the interface may be.
3397 // - if is_block_member, then the extra array level of an arrayed interface is not
3398 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003399 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3400 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3401 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003402 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3403 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3404 DescribeType(producer, a_it->second.type_id).c_str(),
3405 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003406 }
3407 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003408 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3409 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3410 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3411 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003412 }
3413 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003414 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3415 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3416 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003417 }
3418 a_it++;
3419 b_it++;
3420 }
3421 }
3422
Ari Suonpaa696b3432019-03-11 14:02:57 +02003423 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3424 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3425 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3426
3427 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3428 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003429 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3430 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
3431 producer_stage->name, (int)builtins_producer.size(), consumer_stage->name,
3432 (int)builtins_consumer.size());
Ari Suonpaa696b3432019-03-11 14:02:57 +02003433 } else {
3434 auto it_producer = builtins_producer.begin();
3435 auto it_consumer = builtins_consumer.begin();
3436 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3437 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003438 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3439 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3440 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003441 break;
3442 }
3443 it_producer++;
3444 it_consumer++;
3445 }
3446 }
3447 }
3448 }
3449
Chris Forbes47567b72017-06-09 12:09:45 -07003450 return skip;
3451}
3452
John Zulauf14c355b2019-06-27 16:09:37 -06003453static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003454 uint32_t stage_mask = 0;
3455 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3456 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3457 stage_mask |= pCreateInfo->pStages[i].stage;
3458 }
3459 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003460 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3461 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3462 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003463 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3464 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3465 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3466 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3467 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003468 }
3469 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003470 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003471}
3472
Chris Forbes47567b72017-06-09 12:09:45 -07003473// Validate that the shaders used by the given pipeline and store the active_slots
3474// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003475bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Chris Forbesa400a8a2017-07-20 13:10:24 -07003476 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003477 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3478 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003479
John Zulauf14c355b2019-06-27 16:09:37 -06003480 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003481 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003482 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003483 memset(entrypoints, 0, sizeof(entrypoints));
3484 bool skip = false;
3485
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003486 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
3487
Chris Forbes47567b72017-06-09 12:09:45 -07003488 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3489 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003490 auto stage_id = GetShaderStageId(pStage->stage);
John Zulauf14c355b2019-06-27 16:09:37 -06003491 shaders[stage_id] = GetShaderModuleState(pStage->module);
3492 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], pStage->pName, pStage->stage);
3493 skip |= ValidatePipelineShaderStage(pStage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003494 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003495 }
3496
3497 // if the shader stages are no good individually, cross-stage validation is pointless.
3498 if (skip) return true;
3499
3500 auto vi = pCreateInfo->pVertexInputState;
3501
3502 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003503 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003504 }
3505
3506 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003507 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003508 }
3509
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003510 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3511 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003512
3513 while (!shaders[producer] && producer != fragment_stage) {
3514 producer++;
3515 consumer++;
3516 }
3517
3518 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3519 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003520 if (shaders[consumer]) {
3521 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003522 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3523 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003524 }
Chris Forbes47567b72017-06-09 12:09:45 -07003525
3526 producer = consumer;
3527 }
3528 }
3529
3530 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003531 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003532 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003533 }
3534
3535 return skip;
3536}
3537
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003538bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003539 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003540
John Zulauf14c355b2019-06-27 16:09:37 -06003541 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3542 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003543
John Zulauf14c355b2019-06-27 16:09:37 -06003544 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003545}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003546
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003547bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003548 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003549
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003550 if (isKHR) {
3551 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsKHR.maxRecursionDepth) {
3552 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxRecursionDepth-03464", ": %d > %d",
3553 pipeline->raytracingPipelineCI.maxRecursionDepth,
3554 phys_dev_ext_props.ray_tracing_propsKHR.maxRecursionDepth);
3555 }
sourav parmar83c31b12020-05-06 12:30:54 -07003556 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.libraries.libraryCount; ++i) {
3557 const PIPELINE_STATE *pLibrary_pipelinestate = GetPipelineState(pipeline->raytracingPipelineCI.libraries.pLibraries[i]);
3558 if (pLibrary_pipelinestate->raytracingPipelineCI.maxRecursionDepth !=
3559 pipeline->raytracingPipelineCI.maxRecursionDepth) {
3560 skip |= LogError(
3561 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03467",
3562 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3563 "created with the value of maxRecursionDepth (%d) equal to that in this pipeline (%d) .",
3564 i, pLibrary_pipelinestate->raytracingPipelineCI.maxRecursionDepth,
3565 pipeline->raytracingPipelineCI.maxRecursionDepth);
3566 }
3567 if (pLibrary_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxAttributeSize !=
3568 pipeline->raytracingPipelineCI.pLibraryInterface->maxAttributeSize ||
3569 pLibrary_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPayloadSize !=
3570 pipeline->raytracingPipelineCI.pLibraryInterface->maxPayloadSize ||
3571 pLibrary_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxCallableSize !=
3572 pipeline->raytracingPipelineCI.pLibraryInterface->maxCallableSize) {
3573 skip |=
3574 LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03469",
3575 "vkCreateRayTracingPipelinesKHR: Each element of the pLibraries member of libraries must have been "
3576 "created with values of the maxPayloadSize,"
3577 "maxAttributeSize, and maxCallableSize members of pLibraryInterface equal to those in this pipeline.");
3578 }
3579 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003580 } else {
3581 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
3582 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457", ": %d > %d",
3583 pipeline->raytracingPipelineCI.maxRecursionDepth,
3584 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3585 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003586 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003587 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3588 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3589
3590 uint32_t raygen_stages_found = 0;
John Zulaufe4474e72019-07-01 17:28:27 -06003591 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003592 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003593
John Zulaufe4474e72019-07-01 17:28:27 -06003594 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3595 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003596
John Zulaufe4474e72019-07-01 17:28:27 -06003597 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003598
3599 if (stage.stage == VK_SHADER_STAGE_RAYGEN_BIT_NV) {
3600 raygen_stages_found++;
3601 }
3602 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003603 if (raygen_stages_found == 0) {
3604 skip |= LogError(
3605 device,
3606 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3607 " : zero raygen stages specified");
Jason Macnak15f95e82019-08-21 21:52:02 -04003608 }
3609
3610 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3611 const auto &group = groups[group_index];
3612
3613 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3614 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3615 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3616 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3617 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003618 skip |= LogError(device,
3619 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3620 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3621 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003622 }
3623 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3624 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003625 skip |= LogError(device,
3626 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3627 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3628 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003629 }
3630 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3631 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3632 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003633 skip |= LogError(device,
3634 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3635 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3636 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003637 }
3638 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3639 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003640 skip |= LogError(device,
3641 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3642 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3643 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003644 }
3645 }
3646
3647 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3648 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3649 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3650 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003651 skip |= LogError(device,
3652 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3653 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3654 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003655 }
3656 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3657 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3658 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003659 skip |= LogError(device,
3660 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3661 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3662 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003663 }
3664 }
John Zulaufe4474e72019-07-01 17:28:27 -06003665 }
3666 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003667}
3668
Dave Houltona9df0ce2018-02-07 10:51:23 -07003669uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003670
Dave Houltona9df0ce2018-02-07 10:51:23 -07003671static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06003672 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
3673 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003674 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003675 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003676 return nullptr;
3677}
3678
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003679bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003680 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003681 bool skip = false;
3682 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003683
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003684 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003685 return false;
3686 }
3687
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003688 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003689
3690 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003691 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3692 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3693 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003694 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003695 auto cache = GetValidationCacheInfo(pCreateInfo);
3696 uint32_t hash = 0;
3697 if (cache) {
3698 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003699 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003700 }
3701
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003702 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
3703 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003704 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06003705 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003706 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003707 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003708 spvtools::ValidatorOptions options;
3709 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06003710 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003711 if (spv_valid != SPV_SUCCESS) {
3712 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003713 if (spv_valid == SPV_WARNING) {
3714 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3715 diag && diag->error ? diag->error : "(no error text)");
3716 } else {
3717 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3718 diag && diag->error ? diag->error : "(no error text)");
3719 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003720 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003721 } else {
3722 if (cache) {
3723 cache->Insert(hash);
3724 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003725 }
3726
3727 spvDiagnosticDestroy(diag);
3728 spvContextDestroy(ctx);
3729 }
3730
Chris Forbes4ae55b32017-06-09 14:42:56 -07003731 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003732}
3733
John Zulaufac4c6e12019-07-01 16:05:58 -06003734bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003735 bool skip = false;
3736 uint32_t local_size_x = 0;
3737 uint32_t local_size_y = 0;
3738 uint32_t local_size_z = 0;
3739 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3740 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003741 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3742 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
3743 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3744 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06003745 }
3746 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003747 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3748 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
3749 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3750 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06003751 }
3752 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003753 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3754 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
3755 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3756 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06003757 }
3758
3759 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
3760 uint64_t invocations = local_size_x * local_size_y;
3761 // Prevent overflow.
3762 bool fail = false;
3763 if (invocations > UINT32_MAX || invocations > limit) {
3764 fail = true;
3765 }
3766 if (!fail) {
3767 invocations *= local_size_z;
3768 if (invocations > UINT32_MAX || invocations > limit) {
3769 fail = true;
3770 }
3771 }
3772 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003773 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
3774 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
3775 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
3776 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
3777 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06003778 }
3779 }
3780 return skip;
3781}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003782
3783spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
3784 if (api_version >= VK_API_VERSION_1_2) {
3785 return SPV_ENV_VULKAN_1_2;
3786 } else if (api_version >= VK_API_VERSION_1_1) {
3787 if (spirv_1_4) {
3788 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
3789 } else {
3790 return SPV_ENV_VULKAN_1_1;
3791 }
3792 }
3793 return SPV_ENV_VULKAN_1_0;
3794}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003795
3796void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
3797 spvtools::ValidatorOptions &options) {
3798 if (device_extensions.vk_khr_relaxed_block_layout) {
3799 options.SetRelaxBlockLayout(true);
3800 }
3801 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
3802 options.SetUniformBufferStandardLayout(true);
3803 }
3804 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
3805 options.SetScalarBlockLayout(true);
3806 }
3807}