blob: 5a2d4431ad8de803f0ba9056ec1f61efbf8d9dc6 [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
Chris Forbes47567b72017-06-09 12:09:45 -070034#include <SPIRV/spirv.hpp>
35#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());
817
818 if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600819 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700820 for (unsigned int offset = 0; offset < num_locations; offset++) {
821 interface_var v = {};
822 v.id = id;
823 v.type_id = def.word(1);
824 v.offset = offset;
825 out.emplace_back(attachment_index + offset, v);
826 }
827 }
828 }
829 }
830 }
831 }
832
833 return out;
834}
835
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600836static bool IsWritableDescriptorType(SHADER_MODULE_STATE const *module, uint32_t type_id, bool is_storage_buffer) {
Chris Forbes8af24522018-03-07 11:37:45 -0800837 auto type = module->get_def(type_id);
838
839 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
Chris Forbes062f1222018-08-21 15:34:15 -0700840 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
841 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700842 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -0800843 } else {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700844 type = module->get_def(type.word(3)); // Pointee type
Chris Forbes8af24522018-03-07 11:37:45 -0800845 }
846 }
847
848 switch (type.opcode()) {
849 case spv::OpTypeImage: {
850 auto dim = type.word(3);
851 auto sampled = type.word(7);
852 return sampled == 2 && dim != spv::DimSubpassData;
853 }
854
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700855 case spv::OpTypeStruct: {
856 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800857 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -0800858 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800859 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
860 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700861 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -0800862 }
863 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700864
865 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
866 // as nonwritable.
867 return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
868 }
Chris Forbes8af24522018-03-07 11:37:45 -0800869 }
870
871 return false;
872}
873
locke-lunargd9a069d2019-09-17 01:50:19 -0600874std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700875 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -0700876 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
877
878 for (auto id : accessible_ids) {
879 auto insn = src->get_def(id);
880 assert(insn != src->end());
881
882 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -0800883 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
884 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800885 auto d = src->get_decorations(insn.word(2));
886 unsigned set = d.descriptor_set;
887 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -0700888
889 interface_var v = {};
890 v.id = insn.word(2);
891 v.type_id = insn.word(1);
892 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes8af24522018-03-07 11:37:45 -0800893
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800894 if (!(d.flags & decoration_set::nonwritable_bit) &&
Chris Forbes8d31e5d2018-10-08 17:19:15 -0700895 IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8af24522018-03-07 11:37:45 -0800896 *has_writable_descriptor = true;
897 }
Chris Forbes47567b72017-06-09 12:09:45 -0700898 }
899 }
900
901 return out;
902}
903
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700904bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700905 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
906 // be specified only once.
907 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
908 bool skip = false;
909
910 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
911 auto desc = &vi->pVertexBindingDescriptions[i];
912 auto &binding = bindings[desc->binding];
913 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600914 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700915 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
916 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -0700917 } else {
918 binding = desc;
919 }
920 }
921
922 return skip;
923}
924
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700925bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
926 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700927 bool skip = false;
928
Petr Kraus25810d02019-08-27 17:41:15 +0200929 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700930
931 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +0200932 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -0700933 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +0200934 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
935 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
936 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -0700937 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
938 }
939 }
940 }
941
Petr Kraus25810d02019-08-27 17:41:15 +0200942 struct AttribInputPair {
943 const VkVertexInputAttributeDescription *attrib = nullptr;
944 const interface_var *input = nullptr;
945 };
946 std::map<uint32_t, AttribInputPair> location_map;
947 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
948 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -0700949
Jamie Madillc1f7ca82020-03-16 17:08:26 -0400950 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +0200951 const auto location = location_it.first;
952 const auto attrib = location_it.second.attrib;
953 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600954
Petr Kraus25810d02019-08-27 17:41:15 +0200955 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700956 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
957 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +0200958 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700959 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
960 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +0200961 } else if (attrib && input) {
962 const auto attrib_type = GetFormatType(attrib->format);
963 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700964
965 // Type checking
966 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700967 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
968 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
969 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700970 }
Petr Kraus25810d02019-08-27 17:41:15 +0200971 } else { // !attrib && !input
972 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -0700973 }
974 }
975
976 return skip;
977}
978
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700979bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
980 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +0200981 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -0700982
Petr Kraus25810d02019-08-27 17:41:15 +0200983 const auto rpci = pipeline->rp_state->createInfo.ptr();
984
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600985 struct Attachment {
986 const VkAttachmentReference2KHR *reference = nullptr;
987 const VkAttachmentDescription2KHR *attachment = nullptr;
988 const interface_var *output = nullptr;
989 };
990 std::map<uint32_t, Attachment> location_map;
991
Petr Kraus25810d02019-08-27 17:41:15 +0200992 const auto subpass = rpci->pSubpasses[subpass_index];
993 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600994 auto const &reference = subpass.pColorAttachments[i];
995 location_map[i].reference = &reference;
996 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
997 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
998 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -0700999 }
1000 }
1001
Chris Forbes47567b72017-06-09 12:09:45 -07001002 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1003
Petr Kraus25810d02019-08-27 17:41:15 +02001004 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001005 for (const auto &output_it : outputs) {
1006 auto const location = output_it.first.first;
1007 location_map[location].output = &output_it.second;
1008 }
Chris Forbes47567b72017-06-09 12:09:45 -07001009
Petr Kraus25810d02019-08-27 17:41:15 +02001010 const bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1011 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001012
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001013 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001014 const auto reference = location_it.second.reference;
1015 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1016 continue;
1017 }
1018
Petr Kraus25810d02019-08-27 17:41:15 +02001019 const auto location = location_it.first;
1020 const auto attachment = location_it.second.attachment;
1021 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001022 if (attachment && !output) {
1023 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001024 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1025 "Attachment %" PRIu32
1026 " not written by fragment shader; undefined values will be written to attachment",
1027 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001028 }
1029 } else if (!attachment && output) {
1030 if (!(alphaToCoverageEnabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001031 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1032 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001033 }
Petr Kraus25810d02019-08-27 17:41:15 +02001034 } else if (attachment && output) {
1035 const auto attachment_type = GetFormatType(attachment->format);
1036 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001037
1038 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001039 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001040 skip |=
1041 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1042 "Attachment %" PRIu32
1043 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1044 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001045 }
Petr Kraus25810d02019-08-27 17:41:15 +02001046 } else { // !attachment && !output
1047 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001048 }
1049 }
1050
Petr Kraus25810d02019-08-27 17:41:15 +02001051 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
1052 bool locationZeroHasAlpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1053 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001054 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001055 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1056 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001057 }
1058
Chris Forbes47567b72017-06-09 12:09:45 -07001059 return skip;
1060}
1061
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001062// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1063// This function examines instructions in the static call tree for a write to this variable.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001064static bool IsPointSizeWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001065 auto type = builtin_instr.opcode();
1066 uint32_t target_id = builtin_instr.word(1);
1067 bool init_complete = false;
1068
1069 if (type == spv::OpMemberDecorate) {
1070 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1071 auto insn = entrypoint;
1072 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1073 switch (insn.opcode()) {
1074 case spv::OpTypePointer:
1075 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1076 target_id = insn.word(1);
1077 }
1078 break;
1079 case spv::OpVariable:
1080 if (insn.word(1) == target_id) {
1081 target_id = insn.word(2);
1082 init_complete = true;
1083 }
1084 break;
1085 }
1086 insn++;
1087 }
1088 }
1089
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001090 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1091
1092 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001093 std::unordered_set<uint32_t> worklist;
1094 worklist.insert(entrypoint.word(2));
1095
1096 // Follow instructions in call graph looking for writes to target
1097 while (!worklist.empty() && !found_write) {
1098 auto id_iter = worklist.begin();
1099 auto id = *id_iter;
1100 worklist.erase(id_iter);
1101
1102 auto insn = src->get_def(id);
1103 if (insn == src->end()) {
1104 continue;
1105 }
1106
1107 if (insn.opcode() == spv::OpFunction) {
1108 // Scan body of function looking for other function calls or items in our ID chain
1109 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1110 switch (insn.opcode()) {
1111 case spv::OpAccessChain:
1112 if (insn.word(3) == target_id) {
1113 if (type == spv::OpMemberDecorate) {
1114 auto value = GetConstantValue(src, insn.word(4));
1115 if (value == builtin_instr.word(2)) {
1116 target_id = insn.word(2);
1117 }
1118 } else {
1119 target_id = insn.word(2);
1120 }
1121 }
1122 break;
1123 case spv::OpStore:
1124 if (insn.word(1) == target_id) {
1125 found_write = true;
1126 }
1127 break;
1128 case spv::OpFunctionCall:
1129 worklist.insert(insn.word(3));
1130 break;
1131 }
1132 }
1133 }
1134 }
1135 return found_write;
1136}
1137
Chris Forbes47567b72017-06-09 12:09:45 -07001138// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1139// important for identifying the set of shader resources actually used by an entrypoint, for example.
1140// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1141// - NOT the shader input/output interfaces.
1142//
1143// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1144// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001145std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001146 std::unordered_set<uint32_t> ids;
1147 std::unordered_set<uint32_t> worklist;
1148 worklist.insert(entrypoint.word(2));
1149
1150 while (!worklist.empty()) {
1151 auto id_iter = worklist.begin();
1152 auto id = *id_iter;
1153 worklist.erase(id_iter);
1154
1155 auto insn = src->get_def(id);
1156 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001157 // 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 -07001158 // that we may not care about.
1159 continue;
1160 }
1161
1162 // Try to add to the output set
1163 if (!ids.insert(id).second) {
1164 continue; // If we already saw this id, we don't want to walk it again.
1165 }
1166
1167 switch (insn.opcode()) {
1168 case spv::OpFunction:
1169 // Scan whole body of the function, enlisting anything interesting
1170 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1171 switch (insn.opcode()) {
1172 case spv::OpLoad:
1173 case spv::OpAtomicLoad:
1174 case spv::OpAtomicExchange:
1175 case spv::OpAtomicCompareExchange:
1176 case spv::OpAtomicCompareExchangeWeak:
1177 case spv::OpAtomicIIncrement:
1178 case spv::OpAtomicIDecrement:
1179 case spv::OpAtomicIAdd:
1180 case spv::OpAtomicISub:
1181 case spv::OpAtomicSMin:
1182 case spv::OpAtomicUMin:
1183 case spv::OpAtomicSMax:
1184 case spv::OpAtomicUMax:
1185 case spv::OpAtomicAnd:
1186 case spv::OpAtomicOr:
1187 case spv::OpAtomicXor:
1188 worklist.insert(insn.word(3)); // ptr
1189 break;
1190 case spv::OpStore:
1191 case spv::OpAtomicStore:
1192 worklist.insert(insn.word(1)); // ptr
1193 break;
1194 case spv::OpAccessChain:
1195 case spv::OpInBoundsAccessChain:
1196 worklist.insert(insn.word(3)); // base ptr
1197 break;
1198 case spv::OpSampledImage:
1199 case spv::OpImageSampleImplicitLod:
1200 case spv::OpImageSampleExplicitLod:
1201 case spv::OpImageSampleDrefImplicitLod:
1202 case spv::OpImageSampleDrefExplicitLod:
1203 case spv::OpImageSampleProjImplicitLod:
1204 case spv::OpImageSampleProjExplicitLod:
1205 case spv::OpImageSampleProjDrefImplicitLod:
1206 case spv::OpImageSampleProjDrefExplicitLod:
1207 case spv::OpImageFetch:
1208 case spv::OpImageGather:
1209 case spv::OpImageDrefGather:
1210 case spv::OpImageRead:
1211 case spv::OpImage:
1212 case spv::OpImageQueryFormat:
1213 case spv::OpImageQueryOrder:
1214 case spv::OpImageQuerySizeLod:
1215 case spv::OpImageQuerySize:
1216 case spv::OpImageQueryLod:
1217 case spv::OpImageQueryLevels:
1218 case spv::OpImageQuerySamples:
1219 case spv::OpImageSparseSampleImplicitLod:
1220 case spv::OpImageSparseSampleExplicitLod:
1221 case spv::OpImageSparseSampleDrefImplicitLod:
1222 case spv::OpImageSparseSampleDrefExplicitLod:
1223 case spv::OpImageSparseSampleProjImplicitLod:
1224 case spv::OpImageSparseSampleProjExplicitLod:
1225 case spv::OpImageSparseSampleProjDrefImplicitLod:
1226 case spv::OpImageSparseSampleProjDrefExplicitLod:
1227 case spv::OpImageSparseFetch:
1228 case spv::OpImageSparseGather:
1229 case spv::OpImageSparseDrefGather:
1230 case spv::OpImageTexelPointer:
1231 worklist.insert(insn.word(3)); // Image or sampled image
1232 break;
1233 case spv::OpImageWrite:
1234 worklist.insert(insn.word(1)); // Image -- different operand order to above
1235 break;
1236 case spv::OpFunctionCall:
1237 for (uint32_t i = 3; i < insn.len(); i++) {
1238 worklist.insert(insn.word(i)); // fn itself, and all args
1239 }
1240 break;
1241
1242 case spv::OpExtInst:
1243 for (uint32_t i = 5; i < insn.len(); i++) {
1244 worklist.insert(insn.word(i)); // Operands to ext inst
1245 }
1246 break;
1247 }
1248 }
1249 break;
1250 }
1251 }
1252
1253 return ids;
1254}
1255
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001256bool CoreChecks::ValidatePushConstantBlockAgainstPipeline(std::vector<VkPushConstantRange> const *push_constant_ranges,
1257 SHADER_MODULE_STATE const *src, spirv_inst_iter type,
1258 VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001259 bool skip = false;
1260
1261 // Strip off ptrs etc
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001262 type = GetStructType(src, type, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001263 assert(type != src->end());
1264
1265 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
1266 // TODO: arrays, matrices, weird sizes
1267 for (auto insn : *src) {
1268 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1269 if (insn.word(3) == spv::DecorationOffset) {
1270 unsigned offset = insn.word(4);
1271 auto size = 4; // Bytes; TODO: calculate this based on the type
1272
1273 bool found_range = false;
1274 for (auto const &range : *push_constant_ranges) {
Jeremy Hayese883b362019-12-10 15:12:26 -07001275 if ((range.offset <= offset) && ((range.offset + range.size) >= (offset + size)) &&
1276 (range.stageFlags & stage)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001277 found_range = true;
1278
Chris Forbes47567b72017-06-09 12:09:45 -07001279 break;
1280 }
1281 }
1282
1283 if (!found_range) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001284 skip |= LogError(device, kVUID_Core_Shader_PushConstantOutOfRange,
1285 "Push constant range covering variable starting at offset %u not declared in layout", offset);
Chris Forbes47567b72017-06-09 12:09:45 -07001286 }
1287 }
1288 }
1289 }
1290
1291 return skip;
1292}
1293
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001294bool CoreChecks::ValidatePushConstantUsage(std::vector<VkPushConstantRange> const *push_constant_ranges,
1295 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> accessible_ids,
1296 VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001297 bool skip = false;
1298
1299 for (auto id : accessible_ids) {
1300 auto def_insn = src->get_def(id);
1301 if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001302 skip |= ValidatePushConstantBlockAgainstPipeline(push_constant_ranges, src, src->get_def(def_insn.word(1)), stage);
Chris Forbes47567b72017-06-09 12:09:45 -07001303 }
1304 }
1305
1306 return skip;
1307}
1308
1309// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001310bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001311 bool skip = false;
1312
1313 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1314
1315 if (spec) {
1316 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001317 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001318 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
1319 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1320 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1321 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1322 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001323
1324 continue;
1325 }
Chris Forbes47567b72017-06-09 12:09:45 -07001326 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001327 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
1328 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1329 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1330 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1331 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001332 }
1333 }
1334 }
1335
1336 return skip;
1337}
1338
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001339// TODO (jbolz): Can this return a const reference?
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001340static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001341 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001342 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001343 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001344 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001345
1346 // 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 -05001347 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1348 if (type.opcode() == spv::OpTypeRuntimeArray) {
1349 descriptor_count = 0;
1350 type = module->get_def(type.word(2));
1351 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001352 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001353 type = module->get_def(type.word(2));
1354 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001355 if (type.word(2) == spv::StorageClassStorageBuffer) {
1356 is_storage_buffer = true;
1357 }
Chris Forbes47567b72017-06-09 12:09:45 -07001358 type = module->get_def(type.word(3));
1359 }
1360 }
1361
1362 switch (type.opcode()) {
1363 case spv::OpTypeStruct: {
1364 for (auto insn : *module) {
1365 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1366 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001367 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001368 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1369 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1370 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001371 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001372 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1373 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1374 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1375 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001376 }
Chris Forbes47567b72017-06-09 12:09:45 -07001377 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001378 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1379 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1380 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001381 }
1382 }
1383 }
1384
1385 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001386 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001387 }
1388
1389 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001390 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1391 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1392 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001393
Chris Forbes73c00bf2018-06-22 16:28:06 -07001394 case spv::OpTypeSampledImage: {
1395 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1396 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1397 auto image_type = module->get_def(type.word(2));
1398 auto dim = image_type.word(3);
1399 auto sampled = image_type.word(7);
1400 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001401 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1402 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001403 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001404 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001405 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1406 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001407
1408 case spv::OpTypeImage: {
1409 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1410 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1411 auto dim = type.word(3);
1412 auto sampled = type.word(7);
1413
1414 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001415 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1416 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001417 } else if (dim == spv::DimBuffer) {
1418 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001419 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1420 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001421 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001422 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1423 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001424 }
1425 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001426 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1427 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1428 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001429 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001430 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1431 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001432 }
1433 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001434 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001435 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001436 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001437
1438 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1439 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001440 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001441 }
1442}
1443
Jeff Bolze54ae892018-09-08 12:16:29 -05001444static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001445 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001446 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1447 if (ss.tellp()) ss << ", ";
1448 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001449 }
1450 return ss.str();
1451}
1452
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001453bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001454 if (!check) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001455 if (LogError(device, kVUID_Core_Shader_ExceedDeviceLimit,
1456 "Shader requires flag %s set in %s but it is not set on the device", flag, structure)) {
Jeff Bolzee743412019-06-20 22:24:32 -05001457 return true;
1458 }
1459 }
1460
1461 return false;
1462}
1463
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001464bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001465 if (!feature) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001466 if (LogError(device, kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device",
1467 feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001468 return true;
1469 }
1470 }
1471
1472 return false;
1473}
1474
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001475bool CoreChecks::RequireExtension(bool extension, char const *extension_name) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001476 if (!extension) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001477 if (LogError(device, kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
1478 extension_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07001479 return true;
1480 }
1481 }
1482
1483 return false;
1484}
1485
John Zulaufac4c6e12019-07-01 16:05:58 -06001486bool CoreChecks::ValidateShaderCapabilities(SHADER_MODULE_STATE const *src, VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001487 bool skip = false;
1488
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001489 struct FeaturePointer {
1490 // Callable object to test if this feature is enabled in the given aggregate feature struct
1491 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
1492
1493 // Test if feature pointer is populated
1494 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
1495
1496 // Default and nullptr constructor to create an empty FeaturePointer
1497 FeaturePointer() : IsEnabled(nullptr) {}
1498 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
1499
1500 // Constructors to populate FeaturePointer based on given pointer to member
1501 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
1502 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001503 FeaturePointer(VkBool32 VkPhysicalDeviceVulkan11Features::*ptr)
1504 : IsEnabled([=](const DeviceFeatures &features) { return features.core11.*ptr; }) {}
1505 FeaturePointer(VkBool32 VkPhysicalDeviceVulkan12Features::*ptr)
1506 : IsEnabled([=](const DeviceFeatures &features) { return features.core12.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001507 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
1508 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06001509 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
1510 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Jason Macnakc5a621d2019-06-10 12:42:50 -07001511 FeaturePointer(VkBool32 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::*ptr)
1512 : IsEnabled([=](const DeviceFeatures &features) { return features.compute_shader_derivatives_features.*ptr; }) {}
Jason Macnak325e8b52019-06-10 13:33:10 -07001513 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::*ptr)
1514 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_barycentric_features.*ptr; }) {}
Jason Macnakd7fddf82019-06-13 09:52:49 -07001515 FeaturePointer(VkBool32 VkPhysicalDeviceShaderImageFootprintFeaturesNV::*ptr)
1516 : IsEnabled([=](const DeviceFeatures &features) { return features.shader_image_footprint_features.*ptr; }) {}
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001517 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::*ptr)
1518 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_interlock_features.*ptr; }) {}
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001519 FeaturePointer(VkBool32 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::*ptr)
1520 : IsEnabled([=](const DeviceFeatures &features) { return features.demote_to_helper_invocation_features.*ptr; }) {}
Jeff Bolz443c2ca2020-03-19 12:11:51 -05001521 FeaturePointer(VkBool32 VkPhysicalDeviceRayTracingFeaturesKHR::*ptr)
1522 : IsEnabled([=](const DeviceFeatures &features) { return features.ray_tracing_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001523 };
1524
Chris Forbes47567b72017-06-09 12:09:45 -07001525 struct CapabilityInfo {
1526 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001527 FeaturePointer feature;
Tony-LunarG2ec96bb2019-11-26 13:43:02 -07001528 ExtEnabled DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07001529 };
1530
Chris Forbes47567b72017-06-09 12:09:45 -07001531 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07001532 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07001533 // Capabilities always supported by a Vulkan 1.0 implementation -- no
1534 // feature bits.
1535 {spv::CapabilityMatrix, {nullptr}},
1536 {spv::CapabilityShader, {nullptr}},
1537 {spv::CapabilityInputAttachment, {nullptr}},
1538 {spv::CapabilitySampled1D, {nullptr}},
1539 {spv::CapabilityImage1D, {nullptr}},
1540 {spv::CapabilitySampledBuffer, {nullptr}},
Toni Merilehtib13a4a22019-05-21 12:58:44 +03001541 {spv::CapabilityStorageImageExtendedFormats, {nullptr}},
Chris Forbes47567b72017-06-09 12:09:45 -07001542 {spv::CapabilityImageQuery, {nullptr}},
1543 {spv::CapabilityDerivativeControl, {nullptr}},
1544
1545 // Capabilities that are optionally supported, but require a feature to
1546 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001547 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
1548 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
1549 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
1550 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
1551 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1552 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
1553 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
1554 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
1555 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
1556 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
1557 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1558 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
1559 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
1560 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
1561 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1562 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1563 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
1564 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
1565 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
1566 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001567 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
1568 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
1569 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
1570 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05001571
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001572 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001573 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::runtimeDescriptorArray", &VkPhysicalDeviceVulkan12Features::runtimeDescriptorArray}},
1574 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderInputAttachmentArrayDynamicIndexing}},
1575 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformTexelBufferArrayDynamicIndexing}},
1576 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageTexelBufferArrayDynamicIndexing}},
1577 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformBufferArrayNonUniformIndexing}},
1578 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderSampledImageArrayNonUniformIndexing}},
1579 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageBufferArrayNonUniformIndexing}},
1580 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageImageArrayNonUniformIndexing}},
1581 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderInputAttachmentArrayNonUniformIndexing}},
1582 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformTexelBufferArrayNonUniformIndexing}},
1583 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001584
1585 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06001586 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
1587 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
1588 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
1589 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
1590 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1591 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
1592 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
1593 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Jason Macnakb7d091c2019-06-10 11:13:11 -07001594 {spv::CapabilityGroupNonUniformPartitionedNV, {VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_shader_subgroup_partitioned}},
aqnuep7033c702018-09-11 18:03:29 +02001595 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
amhaganfa0b34d2019-10-15 16:03:53 -04001596 {spv::CapabilityShaderClockKHR, {VK_KHR_SHADER_CLOCK_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_clock }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02001597
Jason Macnakc5a621d2019-06-10 12:42:50 -07001598 {spv::CapabilityComputeDerivativeGroupQuadsNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
1599 {spv::CapabilityComputeDerivativeGroupLinearNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
Jason Macnakf7019582019-06-13 10:07:26 -07001600 {spv::CapabilityFragmentBarycentricNV, {"VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric", &VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric, &DeviceExtensions::vk_nv_fragment_shader_barycentric}},
Jason Macnakc5a621d2019-06-10 12:42:50 -07001601
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001602 {spv::CapabilityStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDeviceVulkan12Features::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1603 {spv::CapabilityUniformAndStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDeviceVulkan12Features::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
1604 {spv::CapabilityStoragePushConstant8, {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDeviceVulkan12Features::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07001605
Jason Macnakf7019582019-06-13 10:07:26 -07001606 {spv::CapabilityTransformFeedback, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
1607 {spv::CapabilityGeometryStreams, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01001608
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001609 {spv::CapabilityFloat16, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceVulkan12Features::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
1610 {spv::CapabilityInt8, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceVulkan12Features::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06001611
Jason Macnakd7fddf82019-06-13 09:52:49 -07001612 {spv::CapabilityImageFootprintNV, {"VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint", &VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint, &DeviceExtensions::vk_nv_shader_image_footprint}},
1613
Jeff Bolze4356752019-03-07 11:23:46 -06001614 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001615
Graeme Leese41e6b842019-08-02 10:49:14 +01001616 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserve", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1617 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserve", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1618 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZero", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1619 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTE", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
1620 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZ", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
Jeff Bolz38f6cb52019-06-30 16:26:44 -05001621
1622 {spv::CapabilityFragmentShaderSampleInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1623 {spv::CapabilityFragmentShaderPixelInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
1624 {spv::CapabilityFragmentShaderShadingRateInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
Jeff Bolza38fd3b2019-07-21 11:42:11 -05001625 {spv::CapabilityDemoteToHelperInvocationEXT, {"VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation", &VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation, &DeviceExtensions::vk_ext_shader_demote_to_helper_invocation}},
Jeff Bolz4563f2a2019-12-10 13:30:30 -06001626
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001627 {spv::CapabilityPhysicalStorageBufferAddresses, {"VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress", &VkPhysicalDeviceVulkan12Features::bufferDeviceAddress, &DeviceExtensions::vk_ext_buffer_device_address}},
Jeff Bolz4563f2a2019-12-10 13:30:30 -06001628 // 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 -07001629 {spv::CapabilityPhysicalStorageBufferAddressesEXT, {"VkPhysicalDeviceBufferDeviceAddressFeaturesEXT::bufferDeviceAddress", &VkPhysicalDeviceVulkan12Features::bufferDeviceAddress, &DeviceExtensions::vk_khr_buffer_device_address}},
Jeff Bolz443c2ca2020-03-19 12:11:51 -05001630
1631 {spv::CapabilityRayTracingProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayTracing", &VkPhysicalDeviceRayTracingFeaturesKHR::rayTracing, &DeviceExtensions::vk_khr_ray_tracing}},
1632 {spv::CapabilityRayQueryProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayQuery", &VkPhysicalDeviceRayTracingFeaturesKHR::rayQuery, &DeviceExtensions::vk_khr_ray_tracing}},
1633 {spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayTracingPrimitiveCulling", &VkPhysicalDeviceRayTracingFeaturesKHR::rayTracingPrimitiveCulling, &DeviceExtensions::vk_khr_ray_tracing}},
Chris Forbes47567b72017-06-09 12:09:45 -07001634 };
1635 // clang-format on
1636
1637 for (auto insn : *src) {
1638 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07001639 size_t n = capabilities.count(insn.word(1));
1640 if (1 == n) { // key occurs exactly once
1641 auto it = capabilities.find(insn.word(1));
1642 if (it != capabilities.end()) {
1643 if (it->second.feature) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001644 skip |= RequireFeature(it->second.feature.IsEnabled(enabled_features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001645 }
1646 if (it->second.extension) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001647 skip |= RequireExtension(IsExtEnabled((device_extensions.*(it->second.extension))), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001648 }
Chris Forbes47567b72017-06-09 12:09:45 -07001649 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07001650 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
1651 bool needs_feature = false, has_feature = false;
1652 bool needs_ext = false, has_ext = false;
1653 std::string feature_names = "(one of) [ ";
1654 std::string extension_names = feature_names;
1655 auto caps = capabilities.equal_range(insn.word(1));
1656 for (auto it = caps.first; it != caps.second; ++it) {
1657 if (it->second.feature) {
1658 needs_feature = true;
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001659 has_feature = has_feature || it->second.feature.IsEnabled(enabled_features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001660 feature_names += it->second.name;
1661 feature_names += " ";
1662 }
1663 if (it->second.extension) {
1664 needs_ext = true;
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001665 has_ext = has_ext || device_extensions.*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07001666 extension_names += it->second.name;
1667 extension_names += " ";
1668 }
1669 }
1670 if (needs_feature) {
1671 feature_names += "]";
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001672 skip |= RequireFeature(has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07001673 }
1674 if (needs_ext) {
1675 extension_names += "]";
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001676 skip |= RequireExtension(has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001677 }
Graeme Leesec82dbe02019-08-02 10:44:21 +01001678 }
1679
1680 { // Do group non-uniform checks
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001681 const VkSubgroupFeatureFlags supportedOperations = phys_dev_props_core11.subgroupSupportedOperations;
1682 const VkSubgroupFeatureFlags supportedStages = phys_dev_props_core11.subgroupSupportedStages;
Jeff Bolzee743412019-06-20 22:24:32 -05001683
1684 switch (insn.word(1)) {
1685 default:
1686 break;
1687 case spv::CapabilityGroupNonUniform:
1688 case spv::CapabilityGroupNonUniformVote:
1689 case spv::CapabilityGroupNonUniformArithmetic:
1690 case spv::CapabilityGroupNonUniformBallot:
1691 case spv::CapabilityGroupNonUniformShuffle:
1692 case spv::CapabilityGroupNonUniformShuffleRelative:
1693 case spv::CapabilityGroupNonUniformClustered:
1694 case spv::CapabilityGroupNonUniformQuad:
1695 case spv::CapabilityGroupNonUniformPartitionedNV:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001696 RequirePropertyFlag(supportedStages & stage, string_VkShaderStageFlagBits(stage),
Jeff Bolzee743412019-06-20 22:24:32 -05001697 "VkPhysicalDeviceSubgroupProperties::supportedStages");
1698 break;
1699 }
1700
1701 switch (insn.word(1)) {
1702 default:
1703 break;
1704 case spv::CapabilityGroupNonUniform:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001705 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT, "VK_SUBGROUP_FEATURE_BASIC_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05001706 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1707 break;
1708 case spv::CapabilityGroupNonUniformVote:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001709 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT, "VK_SUBGROUP_FEATURE_VOTE_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05001710 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1711 break;
1712 case spv::CapabilityGroupNonUniformArithmetic:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001713 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05001714 "VK_SUBGROUP_FEATURE_ARITHMETIC_BIT",
1715 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1716 break;
1717 case spv::CapabilityGroupNonUniformBallot:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001718 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT, "VK_SUBGROUP_FEATURE_BALLOT_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05001719 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1720 break;
1721 case spv::CapabilityGroupNonUniformShuffle:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001722 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05001723 "VK_SUBGROUP_FEATURE_SHUFFLE_BIT",
1724 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1725 break;
1726 case spv::CapabilityGroupNonUniformShuffleRelative:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001727 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05001728 "VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT",
1729 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1730 break;
1731 case spv::CapabilityGroupNonUniformClustered:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001732 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05001733 "VK_SUBGROUP_FEATURE_CLUSTERED_BIT",
1734 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1735 break;
1736 case spv::CapabilityGroupNonUniformQuad:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001737 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT, "VK_SUBGROUP_FEATURE_QUAD_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05001738 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1739 break;
1740 case spv::CapabilityGroupNonUniformPartitionedNV:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001741 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV,
Jeff Bolzee743412019-06-20 22:24:32 -05001742 "VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV",
1743 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
1744 break;
1745 }
Chris Forbes47567b72017-06-09 12:09:45 -07001746 }
baldurk4095f932020-02-16 13:24:42 +00001747 } else if (insn.opcode() == spv::OpExtension) {
1748 std::string extension_name = (char const *)&insn.word(1);
1749
1750 if (extension_name == "SPV_KHR_non_semantic_info") {
1751 skip |= RequireExtension(IsExtEnabled(device_extensions.vk_khr_shader_non_semantic_info),
1752 VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME);
1753 }
Chris Forbes47567b72017-06-09 12:09:45 -07001754 }
1755 }
1756
Jeff Bolzee743412019-06-20 22:24:32 -05001757 return skip;
1758}
1759
John Zulaufac4c6e12019-07-01 16:05:58 -06001760bool CoreChecks::ValidateShaderStageWritableDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001761 bool skip = false;
1762
Chris Forbes349b3132018-03-07 11:38:08 -08001763 if (has_writable_descriptor) {
1764 switch (stage) {
1765 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06001766 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
1767 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
1768 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1769 case VK_SHADER_STAGE_MISS_BIT_NV:
1770 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1771 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1772 case VK_SHADER_STAGE_TASK_BIT_NV:
1773 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08001774 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06001775 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08001776 break;
1777 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001778 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001779 break;
1780 default:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001781 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08001782 break;
1783 }
1784 }
1785
Chris Forbes47567b72017-06-09 12:09:45 -07001786 return skip;
1787}
1788
Jeff Bolz526f2d52019-09-18 13:18:08 -05001789bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001790 bool skip = false;
1791
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001792 auto const subgroup_props = phys_dev_props_core11;
Jeff Bolzee743412019-06-20 22:24:32 -05001793
Jeff Bolz526f2d52019-09-18 13:18:08 -05001794 for (auto inst : *module) {
Jeff Bolzee743412019-06-20 22:24:32 -05001795 // Check the quad operations.
1796 switch (inst.opcode()) {
1797 default:
1798 break;
1799 case spv::OpGroupNonUniformQuadBroadcast:
1800 case spv::OpGroupNonUniformQuadSwap:
1801 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001802 skip |= RequireFeature(subgroup_props.subgroupQuadOperationsInAllStages,
Jeff Bolzee743412019-06-20 22:24:32 -05001803 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages");
1804 }
1805 break;
1806 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05001807
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001808 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
Jeff Bolz526f2d52019-09-18 13:18:08 -05001809 switch (inst.opcode()) {
1810 default:
1811 break;
1812 case spv::OpGroupNonUniformAllEqual:
1813 case spv::OpGroupNonUniformBroadcast:
1814 case spv::OpGroupNonUniformBroadcastFirst:
1815 case spv::OpGroupNonUniformShuffle:
1816 case spv::OpGroupNonUniformShuffleXor:
1817 case spv::OpGroupNonUniformShuffleUp:
1818 case spv::OpGroupNonUniformShuffleDown:
1819 case spv::OpGroupNonUniformIAdd:
1820 case spv::OpGroupNonUniformFAdd:
1821 case spv::OpGroupNonUniformIMul:
1822 case spv::OpGroupNonUniformFMul:
1823 case spv::OpGroupNonUniformSMin:
1824 case spv::OpGroupNonUniformUMin:
1825 case spv::OpGroupNonUniformFMin:
1826 case spv::OpGroupNonUniformSMax:
1827 case spv::OpGroupNonUniformUMax:
1828 case spv::OpGroupNonUniformFMax:
1829 case spv::OpGroupNonUniformBitwiseAnd:
1830 case spv::OpGroupNonUniformBitwiseOr:
1831 case spv::OpGroupNonUniformBitwiseXor:
1832 case spv::OpGroupNonUniformLogicalAnd:
1833 case spv::OpGroupNonUniformLogicalOr:
1834 case spv::OpGroupNonUniformLogicalXor:
1835 case spv::OpGroupNonUniformQuadBroadcast:
1836 case spv::OpGroupNonUniformQuadSwap: {
1837 auto type = module->get_def(inst.word(1));
1838
1839 if (type.opcode() == spv::OpTypeVector) {
1840 // Get the element type
1841 type = module->get_def(type.word(2));
1842 }
1843
1844 if (type.opcode() == spv::OpTypeBool) {
1845 break;
1846 }
1847
1848 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
1849 const uint32_t width = type.word(2);
1850
1851 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
1852 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001853 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
Tony-LunarGa74d3fe2019-11-22 15:43:20 -07001854 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes");
Jeff Bolz526f2d52019-09-18 13:18:08 -05001855 }
1856 break;
1857 }
1858 }
1859 }
Jeff Bolzee743412019-06-20 22:24:32 -05001860 }
1861
1862 return skip;
1863}
1864
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001865bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06001866 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001867 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
1868 pStage->stage == VK_SHADER_STAGE_ALL) {
1869 return false;
1870 }
1871
1872 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001873 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001874
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001875 std::set<uint32_t> patchIDs;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001876 struct Variable {
1877 uint32_t baseTypePtrID;
1878 uint32_t ID;
1879 uint32_t storageClass;
1880 };
1881 std::vector<Variable> variables;
1882
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001883 uint32_t numVertices = 0;
1884
Jeff Bolzf234bf82019-11-04 14:07:15 -06001885 auto entrypointVariables = FindEntrypointInterfaces(entrypoint);
1886
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001887 for (auto insn : *src) {
1888 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001889 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001890 case spv::OpDecorate:
1891 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001892 case spv::DecorationPatch: {
1893 patchIDs.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001894 break;
1895 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001896 default:
1897 break;
1898 }
1899 break;
1900 // Find all input and output variables
1901 case spv::OpVariable: {
1902 Variable var = {};
1903 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06001904 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
1905 // Only include variables in the entrypoint's interface
1906 find(entrypointVariables.begin(), entrypointVariables.end(), insn.word(2)) != entrypointVariables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001907 var.baseTypePtrID = insn.word(1);
1908 var.ID = insn.word(2);
1909 variables.push_back(var);
1910 }
1911 break;
1912 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001913 case spv::OpExecutionMode:
1914 if (insn.word(1) == entrypoint.word(2)) {
1915 switch (insn.word(2)) {
1916 default:
1917 break;
1918 case spv::ExecutionModeOutputVertices:
1919 numVertices = insn.word(3);
1920 break;
1921 }
1922 }
1923 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001924 default:
1925 break;
1926 }
1927 }
1928
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001929 bool strip_output_array_level =
1930 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
1931 bool strip_input_array_level =
1932 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
1933 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
1934
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001935 uint32_t numCompIn = 0, numCompOut = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06001936 int maxCompIn = 0, maxCompOut = 0;
1937
1938 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
1939 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
1940
1941 // Find max component location used for input variables.
1942 for (auto &var : inputs) {
1943 int location = var.first.first;
1944 int component = var.first.second;
1945 interface_var &iv = var.second;
1946
1947 // Only need to look at the first location, since we use the type's whole size
1948 if (iv.offset != 0) {
1949 continue;
1950 }
1951
1952 if (iv.is_patch) {
1953 continue;
1954 }
1955
1956 int numComponents = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
1957 maxCompIn = std::max(maxCompIn, location * 4 + component + numComponents);
1958 }
1959
1960 // Find max component location used for output variables.
1961 for (auto &var : outputs) {
1962 int location = var.first.first;
1963 int component = var.first.second;
1964 interface_var &iv = var.second;
1965
1966 // Only need to look at the first location, since we use the type's whole size
1967 if (iv.offset != 0) {
1968 continue;
1969 }
1970
1971 if (iv.is_patch) {
1972 continue;
1973 }
1974
1975 int numComponents = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
1976 maxCompOut = std::max(maxCompOut, location * 4 + component + numComponents);
1977 }
1978
1979 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
1980 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001981 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001982 // Check if the variable is a patch. Patches can also be members of blocks,
1983 // but if they are then the top-level arrayness has already been stripped
1984 // by the time GetComponentsConsumedByType gets to it.
1985 bool isPatch = patchIDs.find(var.ID) != patchIDs.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001986
1987 if (var.storageClass == spv::StorageClassInput) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001988 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001989 } else { // var.storageClass == spv::StorageClassOutput
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001990 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001991 }
1992 }
1993
1994 switch (pStage->stage) {
1995 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07001996 if (numCompOut > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001997 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
1998 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
1999 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2000 "components by %u components",
2001 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002002 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002003 if (maxCompOut > (int)limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002004 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2005 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2006 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2007 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002008 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002009 break;
2010
2011 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002012 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002013 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2014 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2015 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2016 "components by %u components",
2017 limits.maxTessellationControlPerVertexInputComponents,
2018 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002019 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002020 if (maxCompIn > (int)limits.maxTessellationControlPerVertexInputComponents) {
2021 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002022 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2023 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2024 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2025 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002026 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002027 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002028 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2029 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2030 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2031 "components by %u components",
2032 limits.maxTessellationControlPerVertexOutputComponents,
2033 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002034 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002035 if (maxCompOut > (int)limits.maxTessellationControlPerVertexOutputComponents) {
2036 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002037 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2038 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2039 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2040 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002041 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002042 break;
2043
2044 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002045 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002046 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2047 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2048 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2049 "components by %u components",
2050 limits.maxTessellationEvaluationInputComponents,
2051 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002052 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002053 if (maxCompIn > (int)limits.maxTessellationEvaluationInputComponents) {
2054 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002055 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2056 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2057 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2058 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002059 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002060 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002061 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2062 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2063 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2064 "components by %u components",
2065 limits.maxTessellationEvaluationOutputComponents,
2066 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002067 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002068 if (maxCompOut > (int)limits.maxTessellationEvaluationOutputComponents) {
2069 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002070 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2071 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2072 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2073 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002074 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002075 break;
2076
2077 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002078 if (numCompIn > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002079 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2080 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2081 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2082 "components by %u components",
2083 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002084 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002085 if (maxCompIn > (int)limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002086 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2087 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2088 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2089 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002090 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002091 if (numCompOut > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002092 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2093 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2094 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2095 "components by %u components",
2096 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002097 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002098 if (maxCompOut > (int)limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002099 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2100 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2101 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2102 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002103 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002104 if (numCompOut * numVertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002105 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2106 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2107 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2108 "components by %u components",
2109 limits.maxGeometryTotalOutputComponents,
2110 numCompOut * numVertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002111 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002112 break;
2113
2114 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002115 if (numCompIn > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002116 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2117 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2118 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2119 "components by %u components",
2120 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002121 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002122 if (maxCompIn > (int)limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002123 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2124 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2125 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2126 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002127 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002128 break;
2129
Jeff Bolz148d94e2018-12-13 21:25:56 -06002130 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2131 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2132 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2133 case VK_SHADER_STAGE_MISS_BIT_NV:
2134 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2135 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2136 case VK_SHADER_STAGE_TASK_BIT_NV:
2137 case VK_SHADER_STAGE_MESH_BIT_NV:
2138 break;
2139
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002140 default:
2141 assert(false); // This should never happen
2142 }
2143 return skip;
2144}
2145
sfricke-samsungdc96f302020-03-18 20:42:10 -07002146bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2147 bool skip = false;
2148 uint32_t total_resources = 0;
2149
2150 // Only currently testing for graphics and compute pipelines
2151 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2152 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2153 return false;
2154 }
2155
2156 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2157 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2158 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2159 }
2160
2161 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2162 // input from CreatePipeline and CreatePipelineLayout level
2163 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2164 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2165 continue;
2166 }
2167
2168 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2169 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2170 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2171 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2172 // Check only descriptor types listed in maxPerStageResources description in spec
2173 switch (binding->descriptorType) {
2174 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2175 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2176 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2177 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2178 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2179 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2180 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2181 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2182 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2183 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2184 total_resources += binding->descriptorCount;
2185 break;
2186 default:
2187 break;
2188 }
2189 }
2190 }
2191 }
2192
2193 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2194 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2195 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2196 skip |= LogError(pipeline->pipeline, vuid,
2197 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2198 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2199 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2200 }
2201
2202 return skip;
2203}
2204
Jeff Bolze4356752019-03-07 11:23:46 -06002205// copy the specialization constant value into buf, if it is present
2206void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2207 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2208
2209 if (spec && spec_id < spec->mapEntryCount) {
2210 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2211 }
2212}
2213
2214// Fill in value with the constant or specialization constant value, if available.
2215// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002216static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002217 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2218 auto type_id = src->get_def(insn.word(1));
2219 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2220 return false;
2221 }
2222 switch (insn.opcode()) {
2223 case spv::OpSpecConstant:
2224 *value = insn.word(3);
2225 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2226 return true;
2227 case spv::OpConstant:
2228 *value = insn.word(3);
2229 return true;
2230 default:
2231 return false;
2232 }
2233}
2234
2235// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002236VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002237 switch (insn.opcode()) {
2238 case spv::OpTypeInt:
2239 switch (insn.word(2)) {
2240 case 8:
2241 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2242 case 16:
2243 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2244 case 32:
2245 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2246 case 64:
2247 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2248 default:
2249 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2250 }
2251 case spv::OpTypeFloat:
2252 switch (insn.word(2)) {
2253 case 16:
2254 return VK_COMPONENT_TYPE_FLOAT16_NV;
2255 case 32:
2256 return VK_COMPONENT_TYPE_FLOAT32_NV;
2257 case 64:
2258 return VK_COMPONENT_TYPE_FLOAT64_NV;
2259 default:
2260 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2261 }
2262 default:
2263 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2264 }
2265}
2266
2267// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2268// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002269bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002270 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002271 bool skip = false;
2272
2273 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2274 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2275 // Map SPIR-V result ID to the ID of its type.
2276 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2277
2278 struct CoopMatType {
2279 uint32_t scope, rows, cols;
2280 VkComponentTypeNV component_type;
2281 bool all_constant;
2282
2283 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2284
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002285 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002286 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2287 spirv_inst_iter insn = src->get_def(id);
2288 uint32_t component_type_id = insn.word(2);
2289 uint32_t scope_id = insn.word(3);
2290 uint32_t rows_id = insn.word(4);
2291 uint32_t cols_id = insn.word(5);
2292 auto component_type_iter = src->get_def(component_type_id);
2293 auto scope_iter = src->get_def(scope_id);
2294 auto rows_iter = src->get_def(rows_id);
2295 auto cols_iter = src->get_def(cols_id);
2296
2297 all_constant = true;
2298 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2299 all_constant = false;
2300 }
2301 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2302 all_constant = false;
2303 }
2304 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2305 all_constant = false;
2306 }
2307 component_type = GetComponentType(component_type_iter, src);
2308 }
2309 };
2310
2311 bool seen_coopmat_capability = false;
2312
2313 for (auto insn : *src) {
2314 // Whitelist instructions whose result can be a cooperative matrix type, and
2315 // keep track of their types. It would be nice if SPIRV-Headers generated code
2316 // to identify which instructions have a result type and result id. Lacking that,
2317 // this whitelist is based on the set of instructions that
2318 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2319 switch (insn.opcode()) {
2320 case spv::OpLoad:
2321 case spv::OpCooperativeMatrixLoadNV:
2322 case spv::OpCooperativeMatrixMulAddNV:
2323 case spv::OpSNegate:
2324 case spv::OpFNegate:
2325 case spv::OpIAdd:
2326 case spv::OpFAdd:
2327 case spv::OpISub:
2328 case spv::OpFSub:
2329 case spv::OpFDiv:
2330 case spv::OpSDiv:
2331 case spv::OpUDiv:
2332 case spv::OpMatrixTimesScalar:
2333 case spv::OpConstantComposite:
2334 case spv::OpCompositeConstruct:
2335 case spv::OpConvertFToU:
2336 case spv::OpConvertFToS:
2337 case spv::OpConvertSToF:
2338 case spv::OpConvertUToF:
2339 case spv::OpUConvert:
2340 case spv::OpSConvert:
2341 case spv::OpFConvert:
2342 id_to_type_id[insn.word(2)] = insn.word(1);
2343 break;
2344 default:
2345 break;
2346 }
2347
2348 switch (insn.opcode()) {
2349 case spv::OpDecorate:
2350 if (insn.word(2) == spv::DecorationSpecId) {
2351 id_to_spec_id[insn.word(1)] = insn.word(3);
2352 }
2353 break;
2354 case spv::OpCapability:
2355 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2356 seen_coopmat_capability = true;
2357
2358 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002359 skip |= LogError(
2360 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2361 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2362 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002363 }
2364 }
2365 break;
2366 case spv::OpMemoryModel:
2367 // If the capability isn't enabled, don't bother with the rest of this function.
2368 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2369 if (!seen_coopmat_capability) {
2370 return skip;
2371 }
2372 break;
2373 case spv::OpTypeCooperativeMatrixNV: {
2374 CoopMatType M;
2375 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2376
2377 if (M.all_constant) {
2378 // Validate that the type parameters are all supported for one of the
2379 // operands of a cooperative matrix property.
2380 bool valid = false;
2381 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2382 if (cooperative_matrix_properties[i].AType == M.component_type &&
2383 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2384 cooperative_matrix_properties[i].scope == M.scope) {
2385 valid = true;
2386 break;
2387 }
2388 if (cooperative_matrix_properties[i].BType == M.component_type &&
2389 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2390 cooperative_matrix_properties[i].scope == M.scope) {
2391 valid = true;
2392 break;
2393 }
2394 if (cooperative_matrix_properties[i].CType == M.component_type &&
2395 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2396 cooperative_matrix_properties[i].scope == M.scope) {
2397 valid = true;
2398 break;
2399 }
2400 if (cooperative_matrix_properties[i].DType == M.component_type &&
2401 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2402 cooperative_matrix_properties[i].scope == M.scope) {
2403 valid = true;
2404 break;
2405 }
2406 }
2407 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002408 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2409 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2410 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002411 }
2412 }
2413 break;
2414 }
2415 case spv::OpCooperativeMatrixMulAddNV: {
2416 CoopMatType A, B, C, D;
2417 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2418 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2419 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2420 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002421 // Couldn't find type of matrix
2422 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002423 break;
2424 }
2425 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2426 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2427 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2428 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2429
2430 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2431 // Validate that the type parameters are all supported for the same
2432 // cooperative matrix property.
2433 bool valid = false;
2434 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2435 if (cooperative_matrix_properties[i].AType == A.component_type &&
2436 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2437 cooperative_matrix_properties[i].scope == A.scope &&
2438
2439 cooperative_matrix_properties[i].BType == B.component_type &&
2440 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2441 cooperative_matrix_properties[i].scope == B.scope &&
2442
2443 cooperative_matrix_properties[i].CType == C.component_type &&
2444 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2445 cooperative_matrix_properties[i].scope == C.scope &&
2446
2447 cooperative_matrix_properties[i].DType == D.component_type &&
2448 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2449 cooperative_matrix_properties[i].scope == D.scope) {
2450 valid = true;
2451 break;
2452 }
2453 }
2454 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002455 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2456 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2457 "VkCooperativeMatrixPropertiesNV",
2458 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002459 }
2460 }
2461 break;
2462 }
2463 default:
2464 break;
2465 }
2466 }
2467
2468 return skip;
2469}
2470
John Zulaufac4c6e12019-07-01 16:05:58 -06002471bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002472 auto entrypoint_id = entrypoint.word(2);
2473
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002474 // The first denorm execution mode encountered, along with its bit width.
2475 // Used to check if SeparateDenormSettings is respected.
2476 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002477
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002478 // The first rounding mode encountered, along with its bit width.
2479 // Used to check if SeparateRoundingModeSettings is respected.
2480 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002481
2482 bool skip = false;
2483
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002484 uint32_t verticesOut = 0;
2485 uint32_t invocations = 0;
2486
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002487 for (auto insn : *src) {
2488 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2489 auto mode = insn.word(2);
2490 switch (mode) {
2491 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2492 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002493 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2494 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2495 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002496 skip |= LogError(
2497 device, kVUID_Core_Shader_FeatureNotEnabled,
2498 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2499 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002500 }
2501 break;
2502 }
2503
2504 case spv::ExecutionModeDenormPreserve: {
2505 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002506 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2507 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2508 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002509 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2510 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2511 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002512 }
2513
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002514 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2515 // Register the first denorm execution mode found
2516 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002517 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002518 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002519 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2520 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002521 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2522 "Shader uses different denorm execution modes for 16 and 64-bit but "
2523 "denormBehaviorIndependence is "
2524 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002525 }
2526 break;
2527
2528 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2529 break;
2530
2531 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002532 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2533 "Shader uses different denorm execution modes for different bit widths but "
2534 "denormBehaviorIndependence is "
2535 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002536 break;
2537
2538 default:
2539 break;
2540 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002541 }
2542 break;
2543 }
2544
2545 case spv::ExecutionModeDenormFlushToZero: {
2546 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002547 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2548 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2549 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002550 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2551 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2552 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002553 }
2554
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002555 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2556 // Register the first denorm execution mode found
2557 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002558 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002559 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002560 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2561 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002562 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2563 "Shader uses different denorm execution modes for 16 and 64-bit but "
2564 "denormBehaviorIndependence is "
2565 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002566 }
2567 break;
2568
2569 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2570 break;
2571
2572 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002573 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2574 "Shader uses different denorm execution modes for different bit widths but "
2575 "denormBehaviorIndependence is "
2576 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002577 break;
2578
2579 default:
2580 break;
2581 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002582 }
2583 break;
2584 }
2585
2586 case spv::ExecutionModeRoundingModeRTE: {
2587 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002588 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
2589 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
2590 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002591 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2592 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
2593 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002594 }
2595
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002596 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2597 // Register the first rounding mode found
2598 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002599 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002600 switch (phys_dev_props_core12.roundingModeIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002601 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2602 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002603 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2604 "Shader uses different rounding modes for 16 and 64-bit but "
2605 "roundingModeIndependence is "
2606 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002607 }
2608 break;
2609
2610 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2611 break;
2612
2613 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002614 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2615 "Shader uses different rounding modes for different bit widths but "
2616 "roundingModeIndependence is "
2617 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002618 break;
2619
2620 default:
2621 break;
2622 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002623 }
2624 break;
2625 }
2626
2627 case spv::ExecutionModeRoundingModeRTZ: {
2628 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002629 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
2630 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
2631 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002632 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2633 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
2634 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002635 }
2636
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002637 if (first_rounding_mode.first == spv::ExecutionModeMax) {
2638 // Register the first rounding mode found
2639 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002640 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002641 switch (phys_dev_props_core12.roundingModeIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002642 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
2643 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002644 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2645 "Shader uses different rounding modes for 16 and 64-bit but "
2646 "roundingModeIndependence is "
2647 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002648 }
2649 break;
2650
2651 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
2652 break;
2653
2654 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002655 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2656 "Shader uses different rounding modes for different bit widths but "
2657 "roundingModeIndependence is "
2658 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002659 break;
2660
2661 default:
2662 break;
2663 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002664 }
2665 break;
2666 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002667
2668 case spv::ExecutionModeOutputVertices: {
2669 verticesOut = insn.word(3);
2670 break;
2671 }
2672
2673 case spv::ExecutionModeInvocations: {
2674 invocations = insn.word(3);
2675 break;
2676 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002677 }
2678 }
2679 }
2680
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002681 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
2682 if (verticesOut == 0 || verticesOut > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002683 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
2684 "Geometry shader entry point must have an OpExecutionMode instruction that "
2685 "specifies a maximum output vertex count that is greater than 0 and less "
2686 "than or equal to maxGeometryOutputVertices. "
2687 "OutputVertices=%d, maxGeometryOutputVertices=%d",
2688 verticesOut, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002689 }
2690
2691 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002692 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
2693 "Geometry shader entry point must have an OpExecutionMode instruction that "
2694 "specifies an invocation count that is greater than 0 and less "
2695 "than or equal to maxGeometryShaderInvocations. "
2696 "Invocations=%d, maxGeometryShaderInvocations=%d",
2697 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002698 }
2699 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002700 return skip;
2701}
2702
locke-lunargd9a069d2019-09-17 01:50:19 -06002703uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07002704 auto type = module->get_def(type_id);
2705
2706 while (true) {
2707 switch (type.opcode()) {
2708 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07002709 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07002710 case spv::OpTypeSampledImage:
2711 type = module->get_def(type.word(2));
2712 break;
2713 case spv::OpTypePointer:
2714 type = module->get_def(type.word(3));
2715 break;
2716 case spv::OpTypeImage: {
2717 auto dim = type.word(3);
2718 auto arrayed = type.word(5);
2719 auto msaa = type.word(6);
2720
Chris Forbes74ba2232018-08-27 15:19:27 -07002721 uint32_t bits = 0;
2722 switch (GetFundamentalType(module, type.word(2))) {
2723 case FORMAT_TYPE_FLOAT:
2724 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
2725 break;
2726 case FORMAT_TYPE_UINT:
2727 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
2728 break;
2729 case FORMAT_TYPE_SINT:
2730 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
2731 break;
2732 default:
2733 break;
2734 }
2735
Chris Forbes47567b72017-06-09 12:09:45 -07002736 switch (dim) {
2737 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002738 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
2739 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002740 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002741 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2742 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
2743 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002744 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07002745 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
2746 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002747 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07002748 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
2749 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002750 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07002751 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
2752 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002753 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07002754 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07002755 }
2756 }
2757 default:
2758 return 0;
2759 }
2760 }
2761}
2762
2763// For given pipelineLayout verify that the set_layout_node at slot.first
2764// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06002765static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002766 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07002767 if (!pipelineLayout) return nullptr;
2768
2769 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
2770
2771 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
2772}
2773
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002774static bool FindLocalSize(SHADER_MODULE_STATE const *src, uint32_t &local_size_x, uint32_t &local_size_y, uint32_t &local_size_z) {
Locke1ec6d952019-04-02 11:57:21 -06002775 for (auto insn : *src) {
2776 if (insn.opcode() == spv::OpEntryPoint) {
2777 auto executionModel = insn.word(1);
2778 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
2779 if (entrypointStageBits == VK_SHADER_STAGE_COMPUTE_BIT) {
2780 auto entrypoint_id = insn.word(2);
2781 for (auto insn1 : *src) {
2782 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
2783 insn1.word(2) == spv::ExecutionModeLocalSize) {
2784 local_size_x = insn1.word(3);
2785 local_size_y = insn1.word(4);
2786 local_size_z = insn1.word(5);
2787 return true;
2788 }
2789 }
2790 }
2791 }
2792 }
2793 return false;
2794}
2795
locke-lunargd9a069d2019-09-17 01:50:19 -06002796void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05002797 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07002798 bool is_point_mode = false;
2799
2800 for (auto insn : *src) {
2801 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2802 switch (insn.word(2)) {
2803 case spv::ExecutionModePointMode:
2804 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
2805 is_point_mode = true;
2806 break;
2807
2808 case spv::ExecutionModeOutputPoints:
2809 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2810 break;
2811
2812 case spv::ExecutionModeIsolines:
2813 case spv::ExecutionModeOutputLineStrip:
2814 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
2815 break;
2816
2817 case spv::ExecutionModeTriangles:
2818 case spv::ExecutionModeQuads:
2819 case spv::ExecutionModeOutputTriangleStrip:
2820 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
2821 break;
2822 }
2823 }
2824 }
2825
2826 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
2827}
2828
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002829// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
2830// o If there is only a vertex shader : gl_PointSize must be written when using points
2831// o If there is a geometry or tessellation shader:
2832// - If shaderTessellationAndGeometryPointSize feature is enabled:
2833// * gl_PointSize must be written in the final geometry stage
2834// - If shaderTessellationAndGeometryPointSize feature is disabled:
2835// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002836bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06002837 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002838 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
2839 return false;
2840 }
2841
2842 bool pointsize_written = false;
2843 bool skip = false;
2844
2845 // Search for PointSize built-in decorations
2846 std::vector<uint32_t> pointsize_builtin_offsets;
2847 spirv_inst_iter insn = entrypoint;
2848 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
2849 if (insn.opcode() == spv::OpMemberDecorate) {
2850 if (insn.word(3) == spv::DecorationBuiltIn) {
2851 if (insn.word(4) == spv::BuiltInPointSize) {
2852 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2853 }
2854 }
2855 } else if (insn.opcode() == spv::OpDecorate) {
2856 if (insn.word(2) == spv::DecorationBuiltIn) {
2857 if (insn.word(3) == spv::BuiltInPointSize) {
2858 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
2859 }
2860 }
2861 }
2862
2863 insn++;
2864 }
2865
2866 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002867 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002868 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002869 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
2870 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
2871 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002872 }
2873 } else if (!pointsize_written) {
2874 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002875 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
2876 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
2877 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002878 }
2879 return skip;
2880}
John Zulauf14c355b2019-06-27 16:09:37 -06002881
2882bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
2883 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06002884 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06002885 bool skip = false;
2886
2887 // Check the module
2888 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002889 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
2890 "%s does not contain valid spirv for stage %s.",
2891 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06002892 }
2893
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002894 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
2895 // specializations should be applied and validated.
2896 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
2897 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
2898 // Gather the specialization-constant values.
2899 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07002900 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002901 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
2902 id_value_map.reserve(specialization_info->mapEntryCount);
2903 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
2904 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002905
Jeremy Hayes521221d2020-01-15 16:48:49 -07002906 // Expect only scalar types.
2907 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
2908 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
2909 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002910 }
2911
2912 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG1a9cd5a2020-02-03 15:59:57 -07002913 spv_target_env spirv_environment;
2914 if (api_version >= VK_API_VERSION_1_2)
2915 spirv_environment = SPV_ENV_VULKAN_1_2;
2916 else if (api_version >= VK_API_VERSION_1_1)
2917 spirv_environment = SPV_ENV_VULKAN_1_1;
2918 else
2919 spirv_environment = SPV_ENV_VULKAN_1_0;
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002920 spvtools::Optimizer optimizer(spirv_environment);
2921 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
2922 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002923 skip |= LogError(
2924 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002925 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
2926 };
2927 optimizer.SetMessageConsumer(consumer);
2928 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
2929 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
2930 std::vector<uint32_t> specialized_spirv;
2931 auto const optimized =
2932 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
2933 assert(optimized == true);
2934
2935 if (optimized) {
2936 spv_context ctx = spvContextCreate(spirv_environment);
2937 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
2938 spv_diagnostic diag = nullptr;
2939 spv_validator_options options = spvValidatorOptionsCreate();
2940 if (device_extensions.vk_khr_relaxed_block_layout) {
2941 spvValidatorOptionsSetRelaxBlockLayout(options, true);
2942 }
2943 if (device_extensions.vk_khr_uniform_buffer_standard_layout &&
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002944 enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002945 spvValidatorOptionsSetUniformBufferStandardLayout(options, true);
2946 }
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002947 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002948 spvValidatorOptionsSetScalarBlockLayout(options, true);
2949 }
2950 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
2951 if (spv_valid != SPV_SUCCESS) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002952 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
2953 "After specialization was applied, %s does not contain valid spirv for stage %s.",
2954 report_data->FormatHandle(module->vk_shader_module).c_str(),
2955 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002956 }
2957
2958 spvValidatorOptionsDestroy(options);
2959 spvDiagnosticDestroy(diag);
2960 spvContextDestroy(ctx);
2961 }
2962 }
2963
John Zulauf14c355b2019-06-27 16:09:37 -06002964 // Check the entrypoint
2965 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002966 skip |=
2967 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
2968 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06002969 }
2970 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
2971
2972 // Mark accessible ids
2973 auto &accessible_ids = stage_state.accessible_ids;
2974
Chris Forbes47567b72017-06-09 12:09:45 -07002975 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06002976 bool has_writable_descriptor = stage_state.has_writable_descriptor;
2977 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07002978
Chris Forbes349b3132018-03-07 11:38:08 -08002979 // Validate shader capabilities against enabled device features
Jeff Bolzee743412019-06-20 22:24:32 -05002980 skip |= ValidateShaderCapabilities(module, pStage->stage);
2981 skip |= ValidateShaderStageWritableDescriptor(pStage->stage, has_writable_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002982 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07002983 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002984 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002985 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002986 skip |= ValidateSpecializationOffsets(pStage);
2987 skip |= ValidatePushConstantUsage(pipeline->pipeline_layout->push_constant_ranges.get(), module, accessible_ids, pStage->stage);
Jeff Bolze54ae892018-09-08 12:16:29 -05002988 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002989 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002990 }
Jeff Bolze4356752019-03-07 11:23:46 -06002991 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07002992
2993 // Validate descriptor use
2994 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07002995 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05002996 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07002997 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05002998 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07002999
3000 if (!binding) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003001 skip |= LogError(device, kVUID_Core_Shader_MissingDescriptor,
3002 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3003 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003004 } else if (~binding->stageFlags & pStage->stage) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003005 skip |= LogError(device, kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
3006 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3007 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003008 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003009 skip |= LogError(device, kVUID_Core_Shader_DescriptorTypeMismatch,
3010 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3011 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3012 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003013 } else if (binding->descriptorCount < required_descriptor_count) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003014 skip |= LogError(device, kVUID_Core_Shader_DescriptorTypeMismatch,
3015 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3016 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003017 }
3018 }
3019
3020 // Validate use of input attachments against subpass structure
3021 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003022 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003023
Petr Krause91f7a12017-12-14 20:57:36 +01003024 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003025 auto subpass = pipeline->graphicsPipelineCI.subpass;
3026
3027 for (auto use : input_attachment_uses) {
3028 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3029 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003030 ? input_attachments[use.first].attachment
3031 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003032
3033 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003034 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3035 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003036 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003037 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003038 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3039 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3040 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003041 }
3042 }
3043 }
Lockeaa8fdc02019-04-02 11:59:20 -06003044 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3045 skip |= ValidateComputeWorkGroupSizes(module);
3046 }
Chris Forbes47567b72017-06-09 12:09:45 -07003047 return skip;
3048}
3049
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003050bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3051 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3052 spirv_inst_iter consumer_entrypoint,
3053 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003054 bool skip = false;
3055
3056 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003057 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3058 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003059
3060 auto a_it = outputs.begin();
3061 auto b_it = inputs.begin();
3062
3063 // Maps sorted by key (location); walk them together to find mismatches
3064 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3065 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3066 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3067 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3068 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3069
3070 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003071 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3072 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3073 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003074 a_it++;
3075 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003076 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3077 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3078 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003079 b_it++;
3080 } else {
3081 // subtleties of arrayed interfaces:
3082 // - if is_patch, then the member is not arrayed, even though the interface may be.
3083 // - if is_block_member, then the extra array level of an arrayed interface is not
3084 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003085 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3086 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3087 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003088 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3089 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3090 DescribeType(producer, a_it->second.type_id).c_str(),
3091 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003092 }
3093 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003094 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3095 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3096 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3097 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003098 }
3099 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003100 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3101 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3102 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003103 }
3104 a_it++;
3105 b_it++;
3106 }
3107 }
3108
Ari Suonpaa696b3432019-03-11 14:02:57 +02003109 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3110 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3111 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3112
3113 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3114 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003115 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3116 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
3117 producer_stage->name, (int)builtins_producer.size(), consumer_stage->name,
3118 (int)builtins_consumer.size());
Ari Suonpaa696b3432019-03-11 14:02:57 +02003119 } else {
3120 auto it_producer = builtins_producer.begin();
3121 auto it_consumer = builtins_consumer.begin();
3122 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3123 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003124 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3125 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3126 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003127 break;
3128 }
3129 it_producer++;
3130 it_consumer++;
3131 }
3132 }
3133 }
3134 }
3135
Chris Forbes47567b72017-06-09 12:09:45 -07003136 return skip;
3137}
3138
John Zulauf14c355b2019-06-27 16:09:37 -06003139static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003140 uint32_t stage_mask = 0;
3141 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3142 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3143 stage_mask |= pCreateInfo->pStages[i].stage;
3144 }
3145 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003146 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3147 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3148 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003149 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3150 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3151 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3152 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3153 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003154 }
3155 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003156 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003157}
3158
Chris Forbes47567b72017-06-09 12:09:45 -07003159// Validate that the shaders used by the given pipeline and store the active_slots
3160// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003161bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Chris Forbesa400a8a2017-07-20 13:10:24 -07003162 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003163 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3164 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003165
John Zulauf14c355b2019-06-27 16:09:37 -06003166 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003167 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003168 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003169 memset(entrypoints, 0, sizeof(entrypoints));
3170 bool skip = false;
3171
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003172 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
3173
Chris Forbes47567b72017-06-09 12:09:45 -07003174 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3175 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003176 auto stage_id = GetShaderStageId(pStage->stage);
John Zulauf14c355b2019-06-27 16:09:37 -06003177 shaders[stage_id] = GetShaderModuleState(pStage->module);
3178 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], pStage->pName, pStage->stage);
3179 skip |= ValidatePipelineShaderStage(pStage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003180 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003181 }
3182
3183 // if the shader stages are no good individually, cross-stage validation is pointless.
3184 if (skip) return true;
3185
3186 auto vi = pCreateInfo->pVertexInputState;
3187
3188 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003189 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003190 }
3191
3192 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003193 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003194 }
3195
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003196 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3197 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003198
3199 while (!shaders[producer] && producer != fragment_stage) {
3200 producer++;
3201 consumer++;
3202 }
3203
3204 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3205 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003206 if (shaders[consumer]) {
3207 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003208 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3209 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003210 }
Chris Forbes47567b72017-06-09 12:09:45 -07003211
3212 producer = consumer;
3213 }
3214 }
3215
3216 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003217 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003218 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003219 }
3220
3221 return skip;
3222}
3223
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003224bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003225 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003226
John Zulauf14c355b2019-06-27 16:09:37 -06003227 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3228 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003229
John Zulauf14c355b2019-06-27 16:09:37 -06003230 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003231}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003232
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003233bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003234 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003235
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003236 if (isKHR) {
3237 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsKHR.maxRecursionDepth) {
3238 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxRecursionDepth-03464", ": %d > %d",
3239 pipeline->raytracingPipelineCI.maxRecursionDepth,
3240 phys_dev_ext_props.ray_tracing_propsKHR.maxRecursionDepth);
3241 }
3242 } else {
3243 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
3244 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457", ": %d > %d",
3245 pipeline->raytracingPipelineCI.maxRecursionDepth,
3246 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3247 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003248 }
3249
3250 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3251 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3252
3253 uint32_t raygen_stages_found = 0;
John Zulaufe4474e72019-07-01 17:28:27 -06003254 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003255 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003256
John Zulaufe4474e72019-07-01 17:28:27 -06003257 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3258 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003259
John Zulaufe4474e72019-07-01 17:28:27 -06003260 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003261
3262 if (stage.stage == VK_SHADER_STAGE_RAYGEN_BIT_NV) {
3263 raygen_stages_found++;
3264 }
3265 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003266 if (raygen_stages_found == 0) {
3267 skip |= LogError(
3268 device,
3269 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3270 " : zero raygen stages specified");
Jason Macnak15f95e82019-08-21 21:52:02 -04003271 }
3272
3273 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3274 const auto &group = groups[group_index];
3275
3276 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3277 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3278 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3279 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3280 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003281 skip |= LogError(device,
3282 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3283 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3284 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003285 }
3286 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3287 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003288 skip |= LogError(device,
3289 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3290 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3291 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003292 }
3293 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3294 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3295 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003296 skip |= LogError(device,
3297 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3298 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3299 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003300 }
3301 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3302 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003303 skip |= LogError(device,
3304 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3305 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3306 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003307 }
3308 }
3309
3310 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3311 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3312 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3313 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003314 skip |= LogError(device,
3315 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3316 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3317 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003318 }
3319 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3320 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3321 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003322 skip |= LogError(device,
3323 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3324 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3325 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003326 }
3327 }
John Zulaufe4474e72019-07-01 17:28:27 -06003328 }
3329 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003330}
3331
Dave Houltona9df0ce2018-02-07 10:51:23 -07003332uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003333
Dave Houltona9df0ce2018-02-07 10:51:23 -07003334static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06003335 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
3336 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003337 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003338 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003339 return nullptr;
3340}
3341
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003342bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003343 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003344 bool skip = false;
3345 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003346
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06003347 if (disabled.shader_validation) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003348 return false;
3349 }
3350
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003351 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003352
3353 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003354 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3355 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3356 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003357 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003358 auto cache = GetValidationCacheInfo(pCreateInfo);
3359 uint32_t hash = 0;
3360 if (cache) {
3361 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003362 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003363 }
3364
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003365 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
3366 // the default values will be used during validation.
Jeremy Hayes0be25de2019-09-11 18:13:49 -06003367 spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
Tony-LunarG034e63a2020-01-16 13:39:24 -07003368 if (api_version >= VK_API_VERSION_1_2) {
3369 spirv_environment = SPV_ENV_VULKAN_1_2;
3370 } else if (api_version >= VK_API_VERSION_1_1) {
Jesse Halla0389fc2019-09-25 16:46:21 -05003371 if (device_extensions.vk_khr_spirv_1_4) {
3372 spirv_environment = SPV_ENV_VULKAN_1_1_SPIRV_1_4;
3373 } else {
3374 spirv_environment = SPV_ENV_VULKAN_1_1;
3375 }
Jeremy Hayes0be25de2019-09-11 18:13:49 -06003376 }
Dave Houlton0ea2d012018-06-21 14:00:26 -06003377 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003378 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003379 spv_diagnostic diag = nullptr;
Karl Schultzfda1b382018-08-08 18:56:11 -06003380 spv_validator_options options = spvValidatorOptionsCreate();
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003381 if (device_extensions.vk_khr_relaxed_block_layout) {
Karl Schultzfda1b382018-08-08 18:56:11 -06003382 spvValidatorOptionsSetRelaxBlockLayout(options, true);
3383 }
Graeme Leese9b6a1522019-06-07 20:49:45 +01003384 if (device_extensions.vk_khr_uniform_buffer_standard_layout &&
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003385 enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
Graeme Leese9b6a1522019-06-07 20:49:45 +01003386 spvValidatorOptionsSetUniformBufferStandardLayout(options, true);
3387 }
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003388 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
Tobias Hector6a0ece72018-12-10 12:24:05 +00003389 spvValidatorOptionsSetScalarBlockLayout(options, true);
3390 }
Karl Schultzfda1b382018-08-08 18:56:11 -06003391 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003392 if (spv_valid != SPV_SUCCESS) {
3393 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003394 if (spv_valid == SPV_WARNING) {
3395 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3396 diag && diag->error ? diag->error : "(no error text)");
3397 } else {
3398 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3399 diag && diag->error ? diag->error : "(no error text)");
3400 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003401 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003402 } else {
3403 if (cache) {
3404 cache->Insert(hash);
3405 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003406 }
3407
Karl Schultzfda1b382018-08-08 18:56:11 -06003408 spvValidatorOptionsDestroy(options);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003409 spvDiagnosticDestroy(diag);
3410 spvContextDestroy(ctx);
3411 }
3412
Chris Forbes4ae55b32017-06-09 14:42:56 -07003413 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003414}
3415
John Zulaufac4c6e12019-07-01 16:05:58 -06003416bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003417 bool skip = false;
3418 uint32_t local_size_x = 0;
3419 uint32_t local_size_y = 0;
3420 uint32_t local_size_z = 0;
3421 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3422 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003423 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3424 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
3425 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3426 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06003427 }
3428 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003429 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3430 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
3431 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3432 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06003433 }
3434 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003435 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3436 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
3437 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3438 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06003439 }
3440
3441 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
3442 uint64_t invocations = local_size_x * local_size_y;
3443 // Prevent overflow.
3444 bool fail = false;
3445 if (invocations > UINT32_MAX || invocations > limit) {
3446 fail = true;
3447 }
3448 if (!fail) {
3449 invocations *= local_size_z;
3450 if (invocations > UINT32_MAX || invocations > limit) {
3451 fail = true;
3452 }
3453 }
3454 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003455 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
3456 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
3457 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
3458 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
3459 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06003460 }
3461 }
3462 return skip;
3463}