blob: c8ef9b255fff34cfd40ef64d7f11a2d778c8de33 [file] [log] [blame]
sfricke-samsung691299b2021-01-01 20:48:48 -08001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
4 * Copyright (C) 2015-2021 Google Inc.
Tobias Hector6663c9b2020-11-05 10:18:02 +00005 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Chris Forbes47567b72017-06-09 12:09:45 -07006 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * Author: Chris Forbes <chrisf@ijw.co.nz>
Dave Houlton51653902018-06-22 17:32:13 -060020 * Author: Dave Houlton <daveh@lunarg.com>
Tobias Hector6663c9b2020-11-05 10:18:02 +000021 * Author: Tobias Hector <tobias.hector@amd.com>
Chris Forbes47567b72017-06-09 12:09:45 -070022 */
23
Petr Kraus25810d02019-08-27 17:41:15 +020024#include "shader_validation.h"
25
Chris Forbes47567b72017-06-09 12:09:45 -070026#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020027#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020028#include <cinttypes>
Jeff Bolzf234bf82019-11-04 14:07:15 -060029#include <cmath>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070031#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020032#include <string>
33#include <unordered_map>
34#include <vector>
35
Mark Lobodzinski102687e2020-04-28 11:03:28 -060036#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_loader_platform.h"
38#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039#include "vk_layer_data.h"
40#include "vk_layer_extension_utils.h"
41#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070042#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070043#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020044
Chris Forbes4ae55b32017-06-09 14:42:56 -070045#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070046#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070047
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080048void decoration_set::add(uint32_t decoration, uint32_t value) {
49 switch (decoration) {
50 case spv::DecorationLocation:
51 flags |= location_bit;
52 location = value;
53 break;
54 case spv::DecorationPatch:
55 flags |= patch_bit;
56 break;
57 case spv::DecorationRelaxedPrecision:
58 flags |= relaxed_precision_bit;
59 break;
60 case spv::DecorationBlock:
61 flags |= block_bit;
62 break;
63 case spv::DecorationBufferBlock:
64 flags |= buffer_block_bit;
65 break;
66 case spv::DecorationComponent:
67 flags |= component_bit;
68 component = value;
69 break;
70 case spv::DecorationInputAttachmentIndex:
71 flags |= input_attachment_index_bit;
72 input_attachment_index = value;
73 break;
74 case spv::DecorationDescriptorSet:
75 flags |= descriptor_set_bit;
76 descriptor_set = value;
77 break;
78 case spv::DecorationBinding:
79 flags |= binding_bit;
80 binding = value;
81 break;
82 case spv::DecorationNonWritable:
83 flags |= nonwritable_bit;
84 break;
85 case spv::DecorationBuiltIn:
86 flags |= builtin_bit;
87 builtin = value;
88 break;
89 }
90}
91
Chris Forbes47567b72017-06-09 12:09:45 -070092enum FORMAT_TYPE {
93 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
94 FORMAT_TYPE_SINT = 2,
95 FORMAT_TYPE_UINT = 4,
96};
97
98typedef std::pair<unsigned, unsigned> location_t;
99
Chris Forbes47567b72017-06-09 12:09:45 -0700100static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200101 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
102 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
103 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
104 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
105 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700106};
107
John Zulauf14c355b2019-06-27 16:09:37 -0600108unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
109
Chris Forbes47567b72017-06-09 12:09:45 -0700110// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600111void SHADER_MODULE_STATE::BuildDefIndex() {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600112 function_set func_set = {};
113 EntryPoint *entry_point = nullptr;
114
Chris Forbes47567b72017-06-09 12:09:45 -0700115 for (auto insn : *this) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600116 // offset is not 0, it means it's updated and the offset is in a Function.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 if (func_set.offset) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600118 func_set.op_lists.insert({insn.opcode(), insn.offset()});
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700119 } else if (entry_point) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600120 entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
121 }
122
Chris Forbes47567b72017-06-09 12:09:45 -0700123 switch (insn.opcode()) {
124 // Types
125 case spv::OpTypeVoid:
126 case spv::OpTypeBool:
127 case spv::OpTypeInt:
128 case spv::OpTypeFloat:
129 case spv::OpTypeVector:
130 case spv::OpTypeMatrix:
131 case spv::OpTypeImage:
132 case spv::OpTypeSampler:
133 case spv::OpTypeSampledImage:
134 case spv::OpTypeArray:
135 case spv::OpTypeRuntimeArray:
136 case spv::OpTypeStruct:
137 case spv::OpTypeOpaque:
138 case spv::OpTypePointer:
139 case spv::OpTypeFunction:
140 case spv::OpTypeEvent:
141 case spv::OpTypeDeviceEvent:
142 case spv::OpTypeReserveId:
143 case spv::OpTypeQueue:
144 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600145 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600146 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700147 def_index[insn.word(1)] = insn.offset();
148 break;
149
150 // Fixed constants
151 case spv::OpConstantTrue:
152 case spv::OpConstantFalse:
153 case spv::OpConstant:
154 case spv::OpConstantComposite:
155 case spv::OpConstantSampler:
156 case spv::OpConstantNull:
157 def_index[insn.word(2)] = insn.offset();
158 break;
159
160 // Specialization constants
161 case spv::OpSpecConstantTrue:
162 case spv::OpSpecConstantFalse:
163 case spv::OpSpecConstant:
164 case spv::OpSpecConstantComposite:
165 case spv::OpSpecConstantOp:
166 def_index[insn.word(2)] = insn.offset();
167 break;
168
169 // Variables
170 case spv::OpVariable:
171 def_index[insn.word(2)] = insn.offset();
172 break;
173
174 // Functions
175 case spv::OpFunction:
176 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600177 func_set.id = insn.word(2);
178 func_set.offset = insn.offset();
179 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700180 break;
181
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800182 // Decorations
183 case spv::OpDecorate: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700184 auto target_id = insn.word(1);
185 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800186 } break;
187 case spv::OpGroupDecorate: {
188 auto const &src = decorations[insn.word(1)];
189 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
190 } break;
191
John Zulauf14c355b2019-06-27 16:09:37 -0600192 // Entry points ... add to the entrypoint table
193 case spv::OpEntryPoint: {
194 // Entry points do not have an id (the id is the function id) and thus need their own table
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700195 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600196 auto execution_model = insn.word(1);
197 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600198 entry_points.emplace(entrypoint_name,
199 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
200
201 auto range = entry_points.equal_range(entrypoint_name);
202 for (auto it = range.first; it != range.second; ++it) {
203 if (it->second.offset == insn.offset()) {
204 entry_point = &(it->second);
205 break;
206 }
207 }
208 assert(entry_point != nullptr);
209 break;
210 }
211 case spv::OpFunctionEnd: {
212 assert(entry_point != nullptr);
213 func_set.length = insn.offset() - func_set.offset;
214 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600215 break;
216 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800217
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700218 // Copy operations
219 case spv::OpCopyLogical:
220 case spv::OpCopyObject: {
221 def_index[insn.word(2)] = insn.offset();
222 break;
223 }
224
Chris Forbes47567b72017-06-09 12:09:45 -0700225 default:
226 // We don't care about any other defs for now.
227 break;
228 }
229 }
230}
231
Jeff Bolz105d6492018-09-29 15:46:44 -0500232unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
233 switch (mode) {
234 case spv::ExecutionModelVertex:
235 return VK_SHADER_STAGE_VERTEX_BIT;
236 case spv::ExecutionModelTessellationControl:
237 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
238 case spv::ExecutionModelTessellationEvaluation:
239 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
240 case spv::ExecutionModelGeometry:
241 return VK_SHADER_STAGE_GEOMETRY_BIT;
242 case spv::ExecutionModelFragment:
243 return VK_SHADER_STAGE_FRAGMENT_BIT;
244 case spv::ExecutionModelGLCompute:
245 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600246 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700247 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600248 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700249 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600250 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700251 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600252 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700253 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600254 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700255 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600256 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700257 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500258 case spv::ExecutionModelTaskNV:
259 return VK_SHADER_STAGE_TASK_BIT_NV;
260 case spv::ExecutionModelMeshNV:
261 return VK_SHADER_STAGE_MESH_BIT_NV;
262 default:
263 return 0;
264 }
265}
266
locke-lunargde3f0fa2020-09-10 11:55:31 -0600267const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
268 VkShaderStageFlagBits stageBits) {
269 auto range = src->entry_points.equal_range(name);
270 for (auto it = range.first; it != range.second; ++it) {
271 if (it->second.stage == stageBits) {
272 return &(it->second);
273 }
274 }
275 return nullptr;
276}
277
locke-lunargd9a069d2019-09-17 01:50:19 -0600278spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600279 auto range = src->entry_points.equal_range(name);
280 for (auto it = range.first; it != range.second; ++it) {
281 if (it->second.stage == stageBits) {
282 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700283 }
284 }
Chris Forbes47567b72017-06-09 12:09:45 -0700285 return src->end();
286}
287
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600288static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700289 switch (sc) {
290 case spv::StorageClassInput:
291 return "input";
292 case spv::StorageClassOutput:
293 return "output";
294 case spv::StorageClassUniformConstant:
295 return "const uniform";
296 case spv::StorageClassUniform:
297 return "uniform";
298 case spv::StorageClassWorkgroup:
299 return "workgroup local";
300 case spv::StorageClassCrossWorkgroup:
301 return "workgroup global";
302 case spv::StorageClassPrivate:
303 return "private global";
304 case spv::StorageClassFunction:
305 return "function";
306 case spv::StorageClassGeneric:
307 return "generic";
308 case spv::StorageClassAtomicCounter:
309 return "atomic counter";
310 case spv::StorageClassImage:
311 return "image";
312 case spv::StorageClassPushConstant:
313 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800314 case spv::StorageClassStorageBuffer:
315 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700316 default:
317 return "unknown";
318 }
319}
320
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700321// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
322// Otherwise, returns src->end().
323spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700324 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700325
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700326 // If id is a copy, see where it was copied from
327 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
328 id = value.word(3);
329 value = src->get_def(id);
330 }
331
332 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
333 return value;
334 }
335 return src->end();
336}
337
338// Assumes itr points to an OpConstant instruction
339uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
340
341// Either returns the constant value described by the instruction at id, or 1
342uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
343 auto value = GetConstantDef(src, id);
344
345 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700346 // TODO: Either ensure that the specialization transform is already performed on a module we're
347 // considering here, OR -- specialize on the fly now.
348 return 1;
349 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700350 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700351}
352
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600353static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700354 auto insn = src->get_def(type);
355 assert(insn != src->end());
356
357 switch (insn.opcode()) {
358 case spv::OpTypeBool:
359 ss << "bool";
360 break;
361 case spv::OpTypeInt:
362 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
363 break;
364 case spv::OpTypeFloat:
365 ss << "float" << insn.word(2);
366 break;
367 case spv::OpTypeVector:
368 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600369 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700370 break;
371 case spv::OpTypeMatrix:
372 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600373 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700374 break;
375 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600376 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
377 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700378 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700379 case spv::OpTypeRuntimeArray:
380 ss << "runtime arr[] of ";
381 DescribeTypeInner(ss, src, insn.word(2));
382 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700383 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600384 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
385 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700386 break;
387 case spv::OpTypeStruct: {
388 ss << "struct of (";
389 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600390 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700391 if (i == insn.len() - 1) {
392 ss << ")";
393 } else {
394 ss << ", ";
395 }
396 }
397 break;
398 }
399 case spv::OpTypeSampler:
400 ss << "sampler";
401 break;
402 case spv::OpTypeSampledImage:
403 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600404 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700405 break;
406 case spv::OpTypeImage:
407 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
408 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600409 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500410 ss << "accelerationStruture";
411 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700412 default:
413 ss << "oddtype";
414 break;
415 }
416}
417
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600418static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700419 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600420 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700421 return ss.str();
422}
423
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600424static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700425 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
426 return type.word(2) < 64;
427}
428
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600429static 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 -0600430 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700431 // Walk two type trees together, and complain about differences
432 auto a_insn = a->get_def(a_type);
433 auto b_insn = b->get_def(b_type);
434 assert(a_insn != a->end());
435 assert(b_insn != b->end());
436
Chris Forbes062f1222018-08-21 15:34:15 -0700437 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
438
Chris Forbes47567b72017-06-09 12:09:45 -0700439 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600440 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700441 }
442
443 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
444 // 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 -0600445 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700446 }
447
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600448 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
449 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700450 }
451
452 if (a_insn.opcode() != b_insn.opcode()) {
453 return false;
454 }
455
456 if (a_insn.opcode() == spv::OpTypePointer) {
457 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600458 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700459 }
460
461 if (a_arrayed || b_arrayed) {
462 // If we havent resolved array-of-verts by here, we're not going to.
463 return false;
464 }
465
466 switch (a_insn.opcode()) {
467 case spv::OpTypeBool:
468 return true;
469 case spv::OpTypeInt:
470 // Match on width, signedness
471 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
472 case spv::OpTypeFloat:
473 // Match on width
474 return a_insn.word(2) == b_insn.word(2);
475 case spv::OpTypeVector:
476 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600477 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
478 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700479 return a_insn.word(3) >= b_insn.word(3);
480 } else {
481 return a_insn.word(3) == b_insn.word(3);
482 }
483 case spv::OpTypeMatrix:
484 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600485 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700486 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700487 case spv::OpTypeArray:
488 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
489 // 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 -0600490 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
491 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700492 case spv::OpTypeStruct:
493 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700494 {
495 if (a_insn.len() != b_insn.len()) {
496 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700497 }
Chris Forbes47567b72017-06-09 12:09:45 -0700498
Dave Houltona9df0ce2018-02-07 10:51:23 -0700499 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600500 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700501 return false;
502 }
503 }
504
505 return true;
506 }
Chris Forbes47567b72017-06-09 12:09:45 -0700507 default:
508 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
509 return false;
510 }
511}
512
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600513static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700514 auto insn = src->get_def(type);
515 assert(insn != src->end());
516
517 switch (insn.opcode()) {
518 case spv::OpTypePointer:
519 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
520 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600521 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700522 case spv::OpTypeArray:
523 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600524 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700525 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600526 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700527 }
528 case spv::OpTypeMatrix:
529 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600530 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700531 case spv::OpTypeVector: {
532 auto scalar_type = src->get_def(insn.word(2));
533 auto bit_width =
534 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
535
536 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
537 return (bit_width * insn.word(3) + 127) / 128;
538 }
539 default:
540 // Everything else is just 1.
541 return 1;
542
543 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
544 }
545}
546
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600547static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200548 auto insn = src->get_def(type);
549 assert(insn != src->end());
550
551 switch (insn.opcode()) {
552 case spv::OpTypePointer:
553 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
554 // pointers around.
555 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
556 case spv::OpTypeStruct: {
557 uint32_t sum = 0;
558 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
559 sum += GetComponentsConsumedByType(src, insn.word(i), false);
560 }
561 return sum;
562 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500563 case spv::OpTypeArray:
564 if (strip_array_level) {
565 return GetComponentsConsumedByType(src, insn.word(2), false);
566 } else {
567 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200568 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200569 case spv::OpTypeMatrix:
570 // Num locations is the dimension * element size
571 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
572 case spv::OpTypeVector: {
573 auto scalar_type = src->get_def(insn.word(2));
574 auto bit_width =
575 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
576 // One component is 32-bit
577 return (bit_width * insn.word(3) + 31) / 32;
578 }
579 case spv::OpTypeFloat: {
580 auto bit_width = insn.word(2);
581 return (bit_width + 31) / 32;
582 }
583 case spv::OpTypeInt: {
584 auto bit_width = insn.word(2);
585 return (bit_width + 31) / 32;
586 }
587 case spv::OpConstant:
588 return GetComponentsConsumedByType(src, insn.word(1), false);
589 default:
590 return 0;
591 }
592}
593
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600594static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700595 switch (format) {
596 case VK_FORMAT_R64G64B64A64_SFLOAT:
597 case VK_FORMAT_R64G64B64A64_SINT:
598 case VK_FORMAT_R64G64B64A64_UINT:
599 case VK_FORMAT_R64G64B64_SFLOAT:
600 case VK_FORMAT_R64G64B64_SINT:
601 case VK_FORMAT_R64G64B64_UINT:
602 return 2;
603 default:
604 return 1;
605 }
606}
607
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600608static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700609 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
610 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
611 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
612 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700613 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
614 return FORMAT_TYPE_FLOAT;
615}
616
617// 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 -0700618// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600619static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700620 auto insn = src->get_def(type);
621 assert(insn != src->end());
622
623 switch (insn.opcode()) {
624 case spv::OpTypeInt:
625 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
626 case spv::OpTypeFloat:
627 return FORMAT_TYPE_FLOAT;
628 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700629 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700630 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700631 case spv::OpTypeRuntimeArray:
632 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600633 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700634 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600635 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700636
637 default:
638 return 0;
639 }
640}
641
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600642static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700643 uint32_t bit_pos = uint32_t(u_ffs(stage));
644 return bit_pos - 1;
645}
646
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600647static 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 -0700648 while (true) {
649 if (def.opcode() == spv::OpTypePointer) {
650 def = src->get_def(def.word(3));
651 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
652 def = src->get_def(def.word(2));
653 is_array_of_verts = false;
654 } else if (def.opcode() == spv::OpTypeStruct) {
655 return def;
656 } else {
657 return src->end();
658 }
659 }
660}
661
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600662static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800663 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
664 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700665 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600666 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800667 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700668 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700669 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700670 }
671
672 std::unordered_map<unsigned, unsigned> member_components;
673 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700674 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700675
676 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
677 for (auto insn : *src) {
678 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
679 unsigned member_index = insn.word(2);
680
681 if (insn.word(3) == spv::DecorationComponent) {
682 unsigned component = insn.word(4);
683 member_components[member_index] = component;
684 }
685
686 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
687 member_relaxed_precision[member_index] = 1;
688 }
Chris Forbesa313d772017-06-13 13:59:41 -0700689
690 if (insn.word(3) == spv::DecorationPatch) {
691 member_patch[member_index] = 1;
692 }
Chris Forbes47567b72017-06-09 12:09:45 -0700693 }
694 }
695
Chris Forbesa313d772017-06-13 13:59:41 -0700696 // TODO: correctly handle location assignment from outside
697
Chris Forbes47567b72017-06-09 12:09:45 -0700698 // Second pass -- produce the output, from Location decorations
699 for (auto insn : *src) {
700 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
701 unsigned member_index = insn.word(2);
702 unsigned member_type_id = type.word(2 + member_index);
703
704 if (insn.word(3) == spv::DecorationLocation) {
705 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600706 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700707 auto component_it = member_components.find(member_index);
708 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
709 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700710 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700711
712 for (unsigned int offset = 0; offset < num_locations; offset++) {
713 interface_var v = {};
714 v.id = id;
715 // TODO: member index in interface_var too?
716 v.type_id = member_type_id;
717 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700718 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700719 v.is_block_member = true;
720 v.is_relaxed_precision = is_relaxed_precision;
721 (*out)[std::make_pair(location + offset, component)] = v;
722 }
723 }
724 }
725 }
Chris Forbesa313d772017-06-13 13:59:41 -0700726
727 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700728}
729
Ari Suonpaa696b3432019-03-11 14:02:57 +0200730static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800731 assert(entrypoint.opcode() == spv::OpEntryPoint);
732
Ari Suonpaa696b3432019-03-11 14:02:57 +0200733 std::vector<uint32_t> interfaces;
734 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
735 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
736 uint32_t word = 3;
737 while (entrypoint.word(word) & 0xff000000u) {
738 ++word;
739 }
740 ++word;
741
742 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
743
744 return interfaces;
745}
746
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600747static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600748 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700749 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
750
Chris Forbes47567b72017-06-09 12:09:45 -0700751 std::map<location_t, interface_var> out;
752
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800753 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
754 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700755 assert(insn != src->end());
756 assert(insn.opcode() == spv::OpVariable);
757
758 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800759 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700760 unsigned id = insn.word(2);
761 unsigned type = insn.word(1);
762
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800763 int location = d.location;
764 int builtin = d.builtin;
765 unsigned component = d.component;
766 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
767 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700768
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700769 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700770 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700771 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700772 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
773 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600774 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700775 for (unsigned int offset = 0; offset < num_locations; offset++) {
776 interface_var v = {};
777 v.id = id;
778 v.type_id = type;
779 v.offset = offset;
780 v.is_patch = is_patch;
781 v.is_relaxed_precision = is_relaxed_precision;
782 out[std::make_pair(location + offset, component)] = v;
783 }
Chris Forbes47567b72017-06-09 12:09:45 -0700784 }
785 }
786 }
787
788 return out;
789}
790
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600791static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200792 uint32_t storageClass) {
793 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700794 std::vector<uint32_t> builtin_struct_members;
795 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200796
797 for (auto insn : *src) {
798 switch (insn.opcode()) {
799 // Find all built-in member decorations
800 case spv::OpMemberDecorate:
801 if (insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700802 builtin_struct_members.push_back(insn.word(1));
Ari Suonpaa696b3432019-03-11 14:02:57 +0200803 }
804 break;
805 // Find all built-in decorations
806 case spv::OpDecorate:
807 switch (insn.word(2)) {
808 case spv::DecorationBlock: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700809 uint32_t block_id = insn.word(1);
810 for (auto built_in_block_id : builtin_struct_members) {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200811 // Check if one of the members of the block are built-in -> the block is built-in
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700812 if (block_id == built_in_block_id) {
813 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200814 break;
815 }
816 }
817 break;
818 }
819 case spv::DecorationBuiltIn:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700820 builtin_decorations.push_back(insn.word(1));
Ari Suonpaa696b3432019-03-11 14:02:57 +0200821 break;
822 default:
823 break;
824 }
825 break;
826 default:
827 break;
828 }
829 }
830
831 // Find all interface variables belonging to the entrypoint and matching the storage class
832 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
833 auto def = src->get_def(id);
834 assert(def != src->end());
835 assert(def.opcode() == spv::OpVariable);
836
837 if (def.word(3) == storageClass) variables.push_back(def.word(1));
838 }
839
840 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700841 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200842 for (auto &var : variables) {
843 auto def = src->get_def(src->get_def(var).word(3));
844
845 // It could be an array of IO blocks. The element type should be the struct defining the block contents
846 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
847
848 // Now find all members belonging to the struct defining the IO block
849 if (def.opcode() == spv::OpTypeStruct) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700850 for (auto built_in_id : builtin_decorations) {
851 if (built_in_id == def.word(1)) {
852 for (int i = 2; i < static_cast<int>(def.len()); i++) {
853 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
854 }
855 // These shouldn't be left after replacing.
Ari Suonpaa696b3432019-03-11 14:02:57 +0200856 for (auto insn : *src) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700857 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == built_in_id &&
Ari Suonpaa696b3432019-03-11 14:02:57 +0200858 insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700859 auto struct_index = insn.word(2);
860 assert(struct_index < builtin_block_members.size());
861 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200862 }
863 }
864 }
865 }
866 }
867 }
868
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700869 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200870}
871
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600872static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600873 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700874 std::vector<std::pair<uint32_t, interface_var>> out;
875
876 for (auto insn : *src) {
877 if (insn.opcode() == spv::OpDecorate) {
878 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
879 auto attachment_index = insn.word(3);
880 auto id = insn.word(1);
881
882 if (accessible_ids.count(id)) {
883 auto def = src->get_def(id);
884 assert(def != src->end());
locke-lunarg9a16ebb2020-07-30 16:56:33 -0600885 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600886 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700887 for (unsigned int offset = 0; offset < num_locations; offset++) {
888 interface_var v = {};
889 v.id = id;
890 v.type_id = def.word(1);
891 v.offset = offset;
892 out.emplace_back(attachment_index + offset, v);
893 }
894 }
895 }
896 }
897 }
898 }
899
900 return out;
901}
902
locke-lunarg25b6c352020-08-06 17:44:18 -0600903static bool AtomicOperation(uint32_t opcode) {
904 switch (opcode) {
905 case spv::OpAtomicLoad:
906 case spv::OpAtomicStore:
907 case spv::OpAtomicExchange:
908 case spv::OpAtomicCompareExchange:
909 case spv::OpAtomicCompareExchangeWeak:
910 case spv::OpAtomicIIncrement:
911 case spv::OpAtomicIDecrement:
912 case spv::OpAtomicIAdd:
913 case spv::OpAtomicISub:
914 case spv::OpAtomicSMin:
915 case spv::OpAtomicUMin:
916 case spv::OpAtomicSMax:
917 case spv::OpAtomicUMax:
918 case spv::OpAtomicAnd:
919 case spv::OpAtomicOr:
920 case spv::OpAtomicXor:
921 case spv::OpAtomicFAddEXT:
922 return true;
923 default:
924 return false;
925 }
926 return false;
927}
928
sfricke-samsung0065ce02020-12-03 22:46:37 -0800929// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
930// covered with VUID 01090
931static bool GroupOperation(uint32_t opcode) {
932 switch (opcode) {
933 case spv::OpGroupNonUniformElect:
934 case spv::OpGroupNonUniformAll:
935 case spv::OpGroupNonUniformAny:
936 case spv::OpGroupNonUniformAllEqual:
937 case spv::OpGroupNonUniformBroadcast:
938 case spv::OpGroupNonUniformBroadcastFirst:
939 case spv::OpGroupNonUniformBallot:
940 case spv::OpGroupNonUniformInverseBallot:
941 case spv::OpGroupNonUniformBallotBitExtract:
942 case spv::OpGroupNonUniformBallotBitCount:
943 case spv::OpGroupNonUniformBallotFindLSB:
944 case spv::OpGroupNonUniformBallotFindMSB:
945 case spv::OpGroupNonUniformShuffle:
946 case spv::OpGroupNonUniformShuffleXor:
947 case spv::OpGroupNonUniformShuffleUp:
948 case spv::OpGroupNonUniformShuffleDown:
949 case spv::OpGroupNonUniformIAdd:
950 case spv::OpGroupNonUniformFAdd:
951 case spv::OpGroupNonUniformIMul:
952 case spv::OpGroupNonUniformFMul:
953 case spv::OpGroupNonUniformSMin:
954 case spv::OpGroupNonUniformUMin:
955 case spv::OpGroupNonUniformFMin:
956 case spv::OpGroupNonUniformSMax:
957 case spv::OpGroupNonUniformUMax:
958 case spv::OpGroupNonUniformFMax:
959 case spv::OpGroupNonUniformBitwiseAnd:
960 case spv::OpGroupNonUniformBitwiseOr:
961 case spv::OpGroupNonUniformBitwiseXor:
962 case spv::OpGroupNonUniformLogicalAnd:
963 case spv::OpGroupNonUniformLogicalOr:
964 case spv::OpGroupNonUniformLogicalXor:
965 case spv::OpGroupNonUniformQuadBroadcast:
966 case spv::OpGroupNonUniformQuadSwap:
967 case spv::OpGroupNonUniformPartitionNV:
968 return true;
969 default:
970 return false;
971 }
972 return false;
973}
974
locke-lunarg12d20992020-09-21 12:46:49 -0600975bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
976 const std::unordered_map<unsigned, unsigned> &load_members,
977 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
978 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600979 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600980 auto load_it = load_members.find(load_id);
981 if (load_it == load_members.end()) {
982 continue;
983 }
984 if (load_it->second == object_id) {
985 return true;
986 }
987
988 auto accesschain_it = accesschain_members.find(load_it->second);
989 if (accesschain_it == accesschain_members.end()) {
990 continue;
991 }
992 if (accesschain_it->second.first == object_id) {
993 return true;
994 }
995 }
996 return false;
997}
998
locke-lunargae2a43c2020-09-22 17:21:57 -0600999bool CheckImageOperandsBiasOffset(uint32_t type) {
1000 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1001 spv::ImageOperandsConstOffsetsMask)
1002 ? true
1003 : false;
1004}
1005
locke-lunargd3da0422020-09-23 01:02:11 -06001006struct shader_module_used_operators {
1007 bool updated;
1008 std::vector<unsigned> imagwrite_members;
1009 std::vector<unsigned> atomic_members;
1010 std::vector<unsigned> store_members;
1011 std::vector<unsigned> atomic_store_members;
1012 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1013 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001014 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
locke-lunargd3da0422020-09-23 01:02:11 -06001015 std::unordered_map<unsigned, unsigned> load_members;
1016 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1017 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
1018
1019 shader_module_used_operators() : updated(false) {}
1020
1021 void update(SHADER_MODULE_STATE const *module) {
1022 if (updated) return;
1023 updated = true;
1024
1025 for (auto insn : *module) {
1026 switch (insn.opcode()) {
1027 case spv::OpImageSampleImplicitLod:
1028 case spv::OpImageSampleProjImplicitLod:
1029 case spv::OpImageSampleProjExplicitLod:
1030 case spv::OpImageSparseSampleImplicitLod:
1031 case spv::OpImageSparseSampleProjImplicitLod:
1032 case spv::OpImageSparseSampleProjExplicitLod: {
1033 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1034 // ImageOperands in index: 5
1035 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1036 sampler_bias_offset_members.emplace_back(insn.word(3));
1037 }
1038 break;
1039 }
1040 case spv::OpImageSampleDrefImplicitLod:
1041 case spv::OpImageSampleDrefExplicitLod:
1042 case spv::OpImageSampleProjDrefImplicitLod:
1043 case spv::OpImageSampleProjDrefExplicitLod:
1044 case spv::OpImageSparseSampleDrefImplicitLod:
1045 case spv::OpImageSparseSampleDrefExplicitLod:
1046 case spv::OpImageSparseSampleProjDrefImplicitLod:
1047 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1048 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1049 // ImageOperands in index: 6
1050 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1051 sampler_bias_offset_members.emplace_back(insn.word(3));
1052 }
1053 break;
1054 }
1055 case spv::OpImageSampleExplicitLod:
1056 case spv::OpImageSparseSampleExplicitLod: {
1057 // ImageOperands in index: 5
1058 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1059 sampler_bias_offset_members.emplace_back(insn.word(3));
1060 }
1061 break;
1062 }
1063 case spv::OpStore: {
1064 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1065 break;
1066 }
1067 case spv::OpImageWrite: {
1068 imagwrite_members.emplace_back(insn.word(1)); // Load id
1069 break;
1070 }
1071 case spv::OpSampledImage: {
1072 // 3: image load id, 4: sampler load id
1073 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1074 break;
1075 }
1076 case spv::OpLoad: {
1077 // 2: Load id, 3: object id or AccessChain id
1078 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1079 break;
1080 }
1081 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001082 if (insn.len() == 4) {
1083 // If it is for struct, the length is only 4.
1084 // 2: AccessChain id, 3: object id
1085 accesschain_members.insert(std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0)));
1086 } else {
1087 // 2: AccessChain id, 3: object id, 4: object id of array index
1088 accesschain_members.insert(
1089 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
1090 }
locke-lunargd3da0422020-09-23 01:02:11 -06001091 break;
1092 }
1093 case spv::OpImageTexelPointer: {
1094 // 2: ImageTexelPointer id, 3: object id
1095 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1096 break;
1097 }
1098 default: {
1099 if (AtomicOperation(insn.opcode())) {
1100 if (insn.opcode() == spv::OpAtomicStore) {
1101 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1102 } else {
1103 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1104 }
1105 }
1106 break;
1107 }
1108 }
1109 }
1110 }
1111};
1112
sfricke-samsung691299b2021-01-01 20:48:48 -08001113// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1114// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001115static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001116 bool is_check_writable, interface_var &out_interface_var,
1117 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001118 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001119 unsigned int id = id_it.word(2);
1120
Chris Forbes8af24522018-03-07 11:37:45 -08001121 auto type = module->get_def(type_id);
1122
1123 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
locke-lunarg12d20992020-09-21 12:46:49 -06001124 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1125 type.opcode() == spv::OpTypeSampledImage) {
1126 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1127 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001128 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001129 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001130 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001131 }
1132 }
Chris Forbes8af24522018-03-07 11:37:45 -08001133 switch (type.opcode()) {
1134 case spv::OpTypeImage: {
1135 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001136 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001137 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001138
locke-lunargd3da0422020-09-23 01:02:11 -06001139 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1140 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001141 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001142 }
1143 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1144 used_operators.accesschain_members)) {
1145 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001146 }
locke-lunargd3da0422020-09-23 01:02:11 -06001147 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1148 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001149 out_interface_var.is_sampler_bias_offset = true;
1150 }
locke-lunargd3da0422020-09-23 01:02:11 -06001151 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1152 used_operators.accesschain_members) ||
1153 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1154 used_operators.accesschain_members)) {
1155 out_interface_var.is_atomic_operation = true;
1156 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001157
locke-lunargd3da0422020-09-23 01:02:11 -06001158 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001159 // Find if image id match.
1160 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001161 auto load_it = used_operators.load_members.find(itp_id.first);
1162 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001163 continue;
1164 } else {
1165 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001166 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1167 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001168 continue;
1169 } else {
1170 if (accesschain_it->second.first != id) {
1171 continue;
1172 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001173
1174 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1175 if (const_itr == module->end()) {
1176 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001177 break;
1178 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001179 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001180 }
1181 }
1182 }
1183 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001184 load_it = used_operators.load_members.find(itp_id.second);
1185 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001186 continue;
1187 } else {
1188 uint32_t sampler_id = load_it->second;
1189 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001190 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001191
locke-lunargd3da0422020-09-23 01:02:11 -06001192 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001193 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1194 if (const_itr == module->end()) {
1195 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001196 break;
1197 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001198 sampler_id = const_itr.offset();
1199 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001200 }
1201 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001202 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1203 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1204 }
1205 out_interface_var.samplers_used_by_image[image_index].emplace(
1206 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001207 }
1208 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001209 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001210 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001211 }
1212
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001213 case spv::OpTypeStruct: {
1214 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001215 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -08001216 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001217 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
1218 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001219 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001220 }
1221 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001222
1223 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1224 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001225 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001226 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001227
locke-lunargd3da0422020-09-23 01:02:11 -06001228 for (auto oid : used_operators.store_members) {
1229 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001230 out_interface_var.is_writable = true;
1231 return;
1232 }
locke-lunargd3da0422020-09-23 01:02:11 -06001233 auto accesschain_it = used_operators.accesschain_members.find(oid);
1234 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001235 continue;
1236 }
locke-lunargd3da0422020-09-23 01:02:11 -06001237 if (accesschain_it->second.first == id) {
1238 out_interface_var.is_writable = true;
1239 return;
1240 }
1241 }
1242 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1243 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001244 out_interface_var.is_writable = true;
1245 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001246 }
1247 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001248 }
Chris Forbes8af24522018-03-07 11:37:45 -08001249 }
Chris Forbes8af24522018-03-07 11:37:45 -08001250}
1251
locke-lunargd9a069d2019-09-17 01:50:19 -06001252std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001253 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1254 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001255 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001256 shader_module_used_operators operators;
1257
Chris Forbes47567b72017-06-09 12:09:45 -07001258 for (auto id : accessible_ids) {
1259 auto insn = src->get_def(id);
1260 assert(insn != src->end());
1261
1262 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001263 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1264 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001265 auto d = src->get_decorations(insn.word(2));
1266 unsigned set = d.descriptor_set;
1267 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001268
1269 interface_var v = {};
1270 v.id = insn.word(2);
1271 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001272
locke-lunarg25b6c352020-08-06 17:44:18 -06001273 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001274 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001275 if (v.is_writable) *has_writable_descriptor = true;
1276 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001277 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001278 }
1279 }
1280
1281 return out;
1282}
1283
locke-lunargde3f0fa2020-09-10 11:55:31 -06001284void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1285 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1286 const auto struct_it = GetStructType(&src, it, false);
1287 assert(struct_it != src.end());
1288 data.size = 0;
1289
1290 shader_struct_member data1;
1291 uint32_t i = 2;
1292 uint32_t local_offset = 0;
1293 std::vector<uint32_t> offsets;
1294 offsets.resize(struct_it.len() - i);
1295
1296 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1297 for (const auto offset : memberDecorate_offsets) {
1298 const auto member_decorate = src.at(offset);
1299 if (member_decorate.word(1) != struct_it.word(1)) {
1300 continue;
1301 }
1302
1303 offsets[member_decorate.word(2)] = member_decorate.word(4);
1304 }
1305
1306 for (const auto offset : offsets) {
1307 local_offset = offset;
1308 data1 = {};
1309 data1.root = data.root;
1310 data1.offset = local_offset;
1311 auto def_member = src.get_def(struct_it.word(i));
1312
1313 // Array could be multi-dimensional
1314 while (def_member.opcode() == spv::OpTypeArray) {
1315 const auto len_id = def_member.word(3);
1316 const auto def_len = src.get_def(len_id);
1317 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1318 def_member = src.get_def(def_member.word(2));
1319 }
1320
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001321 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001322 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001323 } else if (def_member.opcode() == spv::OpTypePointer) {
1324 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1325 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1326 // that "points to something."
1327 data1.size = 8;
1328 } else {
1329 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1330 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1331 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001332 } else {
1333 if (def_member.opcode() == spv::OpTypeMatrix) {
1334 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1335 def_member = src.get_def(def_member.word(2));
1336 }
1337
1338 if (def_member.opcode() == spv::OpTypeVector) {
1339 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1340 def_member = src.get_def(def_member.word(2));
1341 }
1342
1343 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1344 data1.size = (def_member.word(2) / 8);
1345 }
1346 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1347 if (array_length_hierarchy_szie > 0) {
1348 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1349
1350 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1351 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1352 }
1353 }
1354 data.struct_members.emplace_back(data1);
1355 ++i;
1356 }
1357 uint32_t total_array_length = 1;
1358 for (const auto length : data1.array_length_hierarchy) {
1359 total_array_length *= length;
1360 }
1361 data.size = local_offset + data1.size * total_array_length;
1362}
1363
1364uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1365 int array_indices_size = static_cast<int>(array_indices.size());
1366 if (array_indices_size) {
1367 uint32_t array_index = 0;
1368 uint32_t i = 0;
1369 for (const auto index : array_indices) {
1370 array_index += (data.array_block_size[i] * index);
1371 ++i;
1372 }
1373 offset += (array_index * data.size);
1374 }
1375 return offset;
1376}
1377
1378void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1379 int array_indices_size = static_cast<int>(array_indices.size());
1380 uint32_t block_memory_size = data.size;
1381 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1382 block_memory_size *= data.array_length_hierarchy[i];
1383 }
1384
1385 offset = UpdateOffset(offset, array_indices, data);
1386
1387 uint32_t end = offset + block_memory_size;
1388 auto used_bytes = data.GetUsedbytes();
1389 if (used_bytes->size() < end) {
1390 used_bytes->resize(end, 0);
1391 }
1392 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1393}
1394
1395void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1396 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1397 if (access_chain_word_index < access_chain_it.len()) {
1398 if (data.array_length_hierarchy.size() > array_indices.size()) {
1399 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1400 ++access_chain_word_index;
1401
1402 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1403 array_indices.emplace_back(def_it.word(3));
1404 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1405 } else {
1406 // If it is a variable, set the all array is used.
1407 if (access_chain_word_index < access_chain_it.len()) {
1408 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1409 for (uint32_t i = 0; i < array_length; ++i) {
1410 auto array_indices2 = array_indices;
1411 array_indices2.emplace_back(i);
1412 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1413 }
1414 } else {
1415 SetUsedBytes(offset, array_indices, data);
1416 }
1417 }
1418 } else {
1419 offset = UpdateOffset(offset, array_indices, data);
1420 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1421 }
1422 } else {
1423 SetUsedBytes(offset, array_indices, data);
1424 }
1425}
1426
1427void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1428 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1429 std::vector<uint32_t> array_indices_emptry;
1430
1431 if (access_chain_word_index < access_chain_it.len()) {
1432 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1433 ++access_chain_word_index;
1434
1435 auto data1 = data.struct_members[strcut_member_index];
1436 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1437 }
1438}
1439
1440void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1441 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1442 for (const auto &func_set : function_set_list) {
1443 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1444 for (auto it = range.first; it != range.second; ++it) {
1445 auto access_chain = src.at(it->second);
1446 if (access_chain.word(3) == variable_id) {
1447 RunUsedStruct(src, 0, 4, access_chain, data);
1448 }
1449 }
1450 }
1451}
1452
1453void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1454 for (auto &entrypoint : src.entry_points) {
1455 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1456 for (auto it = range.first; it != range.second; ++it) {
1457 const auto def_insn = src.at(it->second);
1458
1459 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1460 spirv_inst_iter type = src.get_def(def_insn.word(1));
1461 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1462 std::vector<uint32_t> offsets;
1463
1464 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1465 auto member_decorate = src.at(it2->second);
1466 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1467 offsets.emplace_back(member_decorate.offset());
1468 }
1469 }
1470 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1471 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1472 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1473 entrypoint.second.push_constant_used_in_shader);
1474 }
1475 }
1476 }
1477}
1478
locke-lunarg96dc9632020-06-10 17:22:18 -06001479std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1480 const VkPipelineShaderStageCreateInfo &stage_info) {
1481 std::unordered_set<uint32_t> location_list;
1482 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1483 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1484 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1485 std::unordered_set<unsigned> store_members;
1486 std::unordered_map<unsigned, unsigned> accesschain_members;
1487
1488 for (auto insn : module) {
1489 switch (insn.opcode()) {
1490 case spv::OpStore:
1491 case spv::OpAtomicStore: {
1492 store_members.insert(insn.word(1)); // object id or AccessChain id
1493 break;
1494 }
1495 case spv::OpAccessChain: {
1496 // 2: AccessChain id, 3: object id
1497 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1498 break;
1499 }
1500 default:
1501 break;
1502 }
1503 }
1504 if (store_members.empty()) {
1505 return location_list;
1506 }
1507 for (auto output : outputs) {
1508 auto store_it = store_members.find(output.second.id);
1509 if (store_it != store_members.end()) {
1510 location_list.insert(output.first.first);
1511 store_members.erase(store_it);
1512 continue;
1513 }
1514 store_it = store_members.begin();
1515 while (store_it != store_members.end()) {
1516 auto accesschain_it = accesschain_members.find(*store_it);
1517 if (accesschain_it == accesschain_members.end()) {
1518 ++store_it;
1519 continue;
1520 }
1521 if (accesschain_it->second == output.second.id) {
1522 location_list.insert(output.first.first);
1523 store_members.erase(store_it);
1524 accesschain_members.erase(accesschain_it);
1525 break;
1526 }
1527 ++store_it;
1528 }
1529 }
1530 return location_list;
1531}
1532
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001533bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001534 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1535 // be specified only once.
1536 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1537 bool skip = false;
1538
1539 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1540 auto desc = &vi->pVertexBindingDescriptions[i];
1541 auto &binding = bindings[desc->binding];
1542 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001543 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001544 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1545 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001546 } else {
1547 binding = desc;
1548 }
1549 }
1550
1551 return skip;
1552}
1553
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001554bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1555 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001556 bool skip = false;
1557
Petr Kraus25810d02019-08-27 17:41:15 +02001558 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001559
1560 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001561 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001562 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001563 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1564 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1565 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001566 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1567 }
1568 }
1569 }
1570
Petr Kraus25810d02019-08-27 17:41:15 +02001571 struct AttribInputPair {
1572 const VkVertexInputAttributeDescription *attrib = nullptr;
1573 const interface_var *input = nullptr;
1574 };
1575 std::map<uint32_t, AttribInputPair> location_map;
1576 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1577 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001578
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001579 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001580 const auto location = location_it.first;
1581 const auto attrib = location_it.second.attrib;
1582 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001583
Petr Kraus25810d02019-08-27 17:41:15 +02001584 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001585 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1586 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001587 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001588 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1589 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001590 } else if (attrib && input) {
1591 const auto attrib_type = GetFormatType(attrib->format);
1592 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001593
1594 // Type checking
1595 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001596 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1597 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1598 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001599 }
Petr Kraus25810d02019-08-27 17:41:15 +02001600 } else { // !attrib && !input
1601 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001602 }
1603 }
1604
1605 return skip;
1606}
1607
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001608bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1609 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001610 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001611
Petr Kraus25810d02019-08-27 17:41:15 +02001612 const auto rpci = pipeline->rp_state->createInfo.ptr();
1613
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001614 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001615 const VkAttachmentReference2 *reference = nullptr;
1616 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001617 const interface_var *output = nullptr;
1618 };
1619 std::map<uint32_t, Attachment> location_map;
1620
Petr Kraus25810d02019-08-27 17:41:15 +02001621 const auto subpass = rpci->pSubpasses[subpass_index];
1622 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001623 auto const &reference = subpass.pColorAttachments[i];
1624 location_map[i].reference = &reference;
1625 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1626 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1627 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001628 }
1629 }
1630
Chris Forbes47567b72017-06-09 12:09:45 -07001631 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1632
Petr Kraus25810d02019-08-27 17:41:15 +02001633 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001634 for (const auto &output_it : outputs) {
1635 auto const location = output_it.first.first;
1636 location_map[location].output = &output_it.second;
1637 }
Chris Forbes47567b72017-06-09 12:09:45 -07001638
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001639 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1640 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001641
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001642 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001643 const auto reference = location_it.second.reference;
1644 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1645 continue;
1646 }
1647
Petr Kraus25810d02019-08-27 17:41:15 +02001648 const auto location = location_it.first;
1649 const auto attachment = location_it.second.attachment;
1650 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001651 if (attachment && !output) {
1652 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001653 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1654 "Attachment %" PRIu32
1655 " not written by fragment shader; undefined values will be written to attachment",
1656 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001657 }
1658 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001659 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001660 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1661 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001662 }
Petr Kraus25810d02019-08-27 17:41:15 +02001663 } else if (attachment && output) {
1664 const auto attachment_type = GetFormatType(attachment->format);
1665 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001666
1667 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001668 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001669 skip |=
1670 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1671 "Attachment %" PRIu32
1672 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1673 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001674 }
Petr Kraus25810d02019-08-27 17:41:15 +02001675 } else { // !attachment && !output
1676 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001677 }
1678 }
1679
Petr Kraus25810d02019-08-27 17:41:15 +02001680 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001681 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1682 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1683 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001684 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1685 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001686 }
1687
Chris Forbes47567b72017-06-09 12:09:45 -07001688 return skip;
1689}
1690
Tobias Hector6663c9b2020-11-05 10:18:02 +00001691// For some built-in analysis we need to know if the variable decorated with as the built-in was actually written to.
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001692// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001693static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001694 auto type = builtin_instr.opcode();
1695 uint32_t target_id = builtin_instr.word(1);
1696 bool init_complete = false;
1697
1698 if (type == spv::OpMemberDecorate) {
1699 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1700 auto insn = entrypoint;
1701 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1702 switch (insn.opcode()) {
1703 case spv::OpTypePointer:
1704 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1705 target_id = insn.word(1);
1706 }
1707 break;
1708 case spv::OpVariable:
1709 if (insn.word(1) == target_id) {
1710 target_id = insn.word(2);
1711 init_complete = true;
1712 }
1713 break;
1714 }
1715 insn++;
1716 }
1717 }
1718
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001719 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1720
1721 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001722 std::unordered_set<uint32_t> worklist;
1723 worklist.insert(entrypoint.word(2));
1724
1725 // Follow instructions in call graph looking for writes to target
1726 while (!worklist.empty() && !found_write) {
1727 auto id_iter = worklist.begin();
1728 auto id = *id_iter;
1729 worklist.erase(id_iter);
1730
1731 auto insn = src->get_def(id);
1732 if (insn == src->end()) {
1733 continue;
1734 }
1735
1736 if (insn.opcode() == spv::OpFunction) {
1737 // Scan body of function looking for other function calls or items in our ID chain
1738 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1739 switch (insn.opcode()) {
1740 case spv::OpAccessChain:
1741 if (insn.word(3) == target_id) {
1742 if (type == spv::OpMemberDecorate) {
1743 auto value = GetConstantValue(src, insn.word(4));
1744 if (value == builtin_instr.word(2)) {
1745 target_id = insn.word(2);
1746 }
1747 } else {
1748 target_id = insn.word(2);
1749 }
1750 }
1751 break;
1752 case spv::OpStore:
1753 if (insn.word(1) == target_id) {
1754 found_write = true;
1755 }
1756 break;
1757 case spv::OpFunctionCall:
1758 worklist.insert(insn.word(3));
1759 break;
1760 }
1761 }
1762 }
1763 }
1764 return found_write;
1765}
1766
Chris Forbes47567b72017-06-09 12:09:45 -07001767// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1768// important for identifying the set of shader resources actually used by an entrypoint, for example.
1769// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1770// - NOT the shader input/output interfaces.
1771//
1772// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1773// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001774std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001775 std::unordered_set<uint32_t> ids;
1776 std::unordered_set<uint32_t> worklist;
1777 worklist.insert(entrypoint.word(2));
1778
1779 while (!worklist.empty()) {
1780 auto id_iter = worklist.begin();
1781 auto id = *id_iter;
1782 worklist.erase(id_iter);
1783
1784 auto insn = src->get_def(id);
1785 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001786 // 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 -07001787 // that we may not care about.
1788 continue;
1789 }
1790
1791 // Try to add to the output set
1792 if (!ids.insert(id).second) {
1793 continue; // If we already saw this id, we don't want to walk it again.
1794 }
1795
1796 switch (insn.opcode()) {
1797 case spv::OpFunction:
1798 // Scan whole body of the function, enlisting anything interesting
1799 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1800 switch (insn.opcode()) {
1801 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001802 worklist.insert(insn.word(3)); // ptr
1803 break;
1804 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001805 worklist.insert(insn.word(1)); // ptr
1806 break;
1807 case spv::OpAccessChain:
1808 case spv::OpInBoundsAccessChain:
1809 worklist.insert(insn.word(3)); // base ptr
1810 break;
1811 case spv::OpSampledImage:
1812 case spv::OpImageSampleImplicitLod:
1813 case spv::OpImageSampleExplicitLod:
1814 case spv::OpImageSampleDrefImplicitLod:
1815 case spv::OpImageSampleDrefExplicitLod:
1816 case spv::OpImageSampleProjImplicitLod:
1817 case spv::OpImageSampleProjExplicitLod:
1818 case spv::OpImageSampleProjDrefImplicitLod:
1819 case spv::OpImageSampleProjDrefExplicitLod:
1820 case spv::OpImageFetch:
1821 case spv::OpImageGather:
1822 case spv::OpImageDrefGather:
1823 case spv::OpImageRead:
1824 case spv::OpImage:
1825 case spv::OpImageQueryFormat:
1826 case spv::OpImageQueryOrder:
1827 case spv::OpImageQuerySizeLod:
1828 case spv::OpImageQuerySize:
1829 case spv::OpImageQueryLod:
1830 case spv::OpImageQueryLevels:
1831 case spv::OpImageQuerySamples:
1832 case spv::OpImageSparseSampleImplicitLod:
1833 case spv::OpImageSparseSampleExplicitLod:
1834 case spv::OpImageSparseSampleDrefImplicitLod:
1835 case spv::OpImageSparseSampleDrefExplicitLod:
1836 case spv::OpImageSparseSampleProjImplicitLod:
1837 case spv::OpImageSparseSampleProjExplicitLod:
1838 case spv::OpImageSparseSampleProjDrefImplicitLod:
1839 case spv::OpImageSparseSampleProjDrefExplicitLod:
1840 case spv::OpImageSparseFetch:
1841 case spv::OpImageSparseGather:
1842 case spv::OpImageSparseDrefGather:
1843 case spv::OpImageTexelPointer:
1844 worklist.insert(insn.word(3)); // Image or sampled image
1845 break;
1846 case spv::OpImageWrite:
1847 worklist.insert(insn.word(1)); // Image -- different operand order to above
1848 break;
1849 case spv::OpFunctionCall:
1850 for (uint32_t i = 3; i < insn.len(); i++) {
1851 worklist.insert(insn.word(i)); // fn itself, and all args
1852 }
1853 break;
1854
1855 case spv::OpExtInst:
1856 for (uint32_t i = 5; i < insn.len(); i++) {
1857 worklist.insert(insn.word(i)); // Operands to ext inst
1858 }
1859 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001860
1861 default: {
1862 if (AtomicOperation(insn.opcode())) {
1863 if (insn.opcode() == spv::OpAtomicStore) {
1864 worklist.insert(insn.word(1)); // ptr
1865 } else {
1866 worklist.insert(insn.word(3)); // ptr
1867 }
1868 }
1869 break;
1870 }
Chris Forbes47567b72017-06-09 12:09:45 -07001871 }
1872 }
1873 break;
1874 }
1875 }
1876
1877 return ids;
1878}
1879
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001880PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1881 const shader_struct_member &push_constant_used_in_shader,
1882 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001883 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001884 const auto used_bytes_size = used_bytes->size();
1885 if (used_bytes_size == 0) return PC_Byte_Updated;
1886
1887 const auto push_constant_data_update_size = push_constant_data_update.size();
1888 const auto *data = push_constant_data_update.data();
1889 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1890 if (used_bytes_size <= push_constant_data_update_size) {
1891 return PC_Byte_Updated;
1892 }
1893 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1894
1895 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1896 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1897 return PC_Byte_Updated;
1898 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001899 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001900
locke-lunargde3f0fa2020-09-10 11:55:31 -06001901 uint32_t i = 0;
1902 for (const auto used : *used_bytes) {
1903 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001904 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001905 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001906 return PC_Byte_Not_Set;
1907 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001908 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001909 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001910 }
1911 }
1912 ++i;
1913 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001914 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001915}
1916
1917bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1918 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001919 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001920 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
locke-lunargde3f0fa2020-09-10 11:55:31 -06001921 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1922 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1923 return skip;
1924 }
1925 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001926
locke-lunargde3f0fa2020-09-10 11:55:31 -06001927 bool found_stage = false;
1928 for (auto const &range : *push_constant_ranges) {
1929 if (range.stageFlags & pStage->stage) {
1930 found_stage = true;
1931 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001932 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001933 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001934 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001935 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001936 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001937 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001938 const auto ret =
1939 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001940
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001941 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001942 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1943 LogObjectList objlist(src->vk_shader_module);
1944 objlist.add(pipeline.pipeline_layout->layout);
1945 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1946 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1947 string_VkShaderStageFlags(pStage->stage).c_str(),
1948 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1949 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001950 }
1951 }
1952 }
1953
locke-lunargde3f0fa2020-09-10 11:55:31 -06001954 if (!found_stage) {
1955 LogObjectList objlist(src->vk_shader_module);
1956 objlist.add(pipeline.pipeline_layout->layout);
1957 skip |= LogError(
1958 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1959 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1960 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001961 }
Chris Forbes47567b72017-06-09 12:09:45 -07001962 return skip;
1963}
1964
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001965bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1966 VkShaderStageFlagBits stage) const {
1967 bool skip = false;
1968
1969 // Currently all builtin tested are only found in fragment shaders
1970 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1971 return skip;
1972 }
1973
1974 for (const auto id : accessible_ids) {
1975 auto insn = src->get_def(id);
1976 const decoration_set decorations = src->get_decorations(insn.word(2));
1977
1978 // Built-ins are obtained from OpVariable
1979 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1980 auto type_pointer = src->get_def(insn.word(1));
1981 assert(type_pointer.opcode() == spv::OpTypePointer);
1982
1983 auto type = src->get_def(type_pointer.word(3));
1984 if (type.opcode() == spv::OpTypeArray) {
1985 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1986
1987 switch (decorations.builtin) {
1988 case spv::BuiltInSampleMask:
1989 // Handles both the input and output sampleMask
1990 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1991 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1992 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1993 "maxSampleMaskWords of %u in %s.",
1994 length, phys_dev_props.limits.maxSampleMaskWords,
1995 report_data->FormatHandle(src->vk_shader_module).c_str());
1996 }
1997 break;
1998 }
1999 }
2000 }
2001 }
2002
2003 return skip;
2004}
2005
Chris Forbes47567b72017-06-09 12:09:45 -07002006// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002007bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002008 bool skip = false;
2009
2010 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2011
2012 if (spec) {
2013 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002014 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002015 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
2016 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2017 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2018 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2019 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002020
2021 continue;
2022 }
Chris Forbes47567b72017-06-09 12:09:45 -07002023 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002024 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2025 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2026 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2027 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2028 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002029 }
2030 }
2031 }
2032
2033 return skip;
2034}
2035
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002036// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002037static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2038 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002039 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002040 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002041 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002042 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002043
2044 // 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 -05002045 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2046 if (type.opcode() == spv::OpTypeRuntimeArray) {
2047 descriptor_count = 0;
2048 type = module->get_def(type.word(2));
2049 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002050 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002051 type = module->get_def(type.word(2));
2052 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002053 if (type.word(2) == spv::StorageClassStorageBuffer) {
2054 is_storage_buffer = true;
2055 }
Chris Forbes47567b72017-06-09 12:09:45 -07002056 type = module->get_def(type.word(3));
2057 }
2058 }
2059
2060 switch (type.opcode()) {
2061 case spv::OpTypeStruct: {
2062 for (auto insn : *module) {
2063 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
2064 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002065 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002066 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2067 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2068 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002069 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002070 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2071 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2072 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2073 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002074 }
Chris Forbes47567b72017-06-09 12:09:45 -07002075 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002076 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2077 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2078 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002079 }
2080 }
2081 }
2082
2083 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002084 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002085 }
2086
2087 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002088 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2089 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2090 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002091
Chris Forbes73c00bf2018-06-22 16:28:06 -07002092 case spv::OpTypeSampledImage: {
2093 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2094 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2095 auto image_type = module->get_def(type.word(2));
2096 auto dim = image_type.word(3);
2097 auto sampled = image_type.word(7);
2098 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002099 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2100 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002101 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002102 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002103 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2104 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002105
2106 case spv::OpTypeImage: {
2107 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2108 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2109 auto dim = type.word(3);
2110 auto sampled = type.word(7);
2111
2112 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002113 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2114 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002115 } else if (dim == spv::DimBuffer) {
2116 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002117 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2118 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002119 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002120 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2121 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002122 }
2123 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002124 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2125 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2126 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002127 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002128 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2129 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002130 }
2131 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002132 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002133 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2134 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002135 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002136
2137 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2138 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002139 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002140 }
2141}
2142
Jeff Bolze54ae892018-09-08 12:16:29 -05002143static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002144 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002145 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2146 if (ss.tellp()) ss << ", ";
2147 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002148 }
2149 return ss.str();
2150}
2151
sfricke-samsung0065ce02020-12-03 22:46:37 -08002152bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002153 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002154 if (LogError(device, vuid, "Shader requires flag %s set in %s but it is not set on the device", flag, structure)) {
Jeff Bolzee743412019-06-20 22:24:32 -05002155 return true;
2156 }
2157 }
2158
2159 return false;
2160}
2161
sfricke-samsung0065ce02020-12-03 22:46:37 -08002162bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002163 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002164 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002165 return true;
2166 }
2167 }
2168
2169 return false;
2170}
2171
locke-lunarg63e4daf2020-08-17 17:53:25 -06002172bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2173 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002174 bool skip = false;
2175
locke-lunarg63e4daf2020-08-17 17:53:25 -06002176 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002177 switch (stage) {
2178 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002179 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2180 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2181 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2182 case VK_SHADER_STAGE_MISS_BIT_NV:
2183 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2184 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2185 case VK_SHADER_STAGE_TASK_BIT_NV:
2186 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002187 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002188 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002189 break;
2190 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002191 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2192 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002193 break;
2194 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002195 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2196 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002197 break;
2198 }
2199 }
2200
Chris Forbes47567b72017-06-09 12:09:45 -07002201 return skip;
2202}
2203
sfricke-samsung94167ca2021-02-26 04:14:59 -08002204bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2205 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002206 bool skip = false;
2207
sfricke-samsung94167ca2021-02-26 04:14:59 -08002208 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2209 if (GroupOperation(insn.opcode()) == true) {
2210 // Check the quad operations.
2211 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2212 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2213 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2214 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2215 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002216 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002217 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002218
sfricke-samsung94167ca2021-02-26 04:14:59 -08002219 uint32_t scope_type = spv::ScopeMax;
2220 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2221 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2222 scope_type = spv::ScopeSubgroup;
2223 } else {
2224 // "All <id> used for Scope <id> must be of an OpConstant"
2225 auto scope_id = module->get_def(insn.word(3));
2226 scope_type = scope_id.word(3);
2227 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002228
sfricke-samsung94167ca2021-02-26 04:14:59 -08002229 if (scope_type == spv::ScopeSubgroup) {
2230 // "Group operations with subgroup scope" must have stage support
2231 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2232 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002233 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002234 }
2235
2236 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2237 auto type = module->get_def(insn.word(1));
2238
2239 if (type.opcode() == spv::OpTypeVector) {
2240 // Get the element type
2241 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002242 }
2243
sfricke-samsung94167ca2021-02-26 04:14:59 -08002244 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002245 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2246 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002247
sfricke-samsung0065ce02020-12-03 22:46:37 -08002248 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2249 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2250 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2251 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2252 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002253 }
2254 }
2255 }
Jeff Bolzee743412019-06-20 22:24:32 -05002256 }
2257
2258 return skip;
2259}
2260
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002261bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002262 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002263 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2264 pStage->stage == VK_SHADER_STAGE_ALL) {
2265 return false;
2266 }
2267
2268 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002269 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002270
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002271 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002272 struct Variable {
2273 uint32_t baseTypePtrID;
2274 uint32_t ID;
2275 uint32_t storageClass;
2276 };
2277 std::vector<Variable> variables;
2278
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002279 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002280 bool is_iso_lines = false;
2281 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002282
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002283 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002284
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002285 for (auto insn : *src) {
2286 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002287 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002288 case spv::OpDecorate:
2289 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002290 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002291 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002292 break;
2293 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002294 default:
2295 break;
2296 }
2297 break;
2298 // Find all input and output variables
2299 case spv::OpVariable: {
2300 Variable var = {};
2301 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002302 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2303 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002304 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002305 var.baseTypePtrID = insn.word(1);
2306 var.ID = insn.word(2);
2307 variables.push_back(var);
2308 }
2309 break;
2310 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002311 case spv::OpExecutionMode:
2312 if (insn.word(1) == entrypoint.word(2)) {
2313 switch (insn.word(2)) {
2314 default:
2315 break;
2316 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002317 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002318 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002319 case spv::ExecutionModeIsolines:
2320 is_iso_lines = true;
2321 break;
2322 case spv::ExecutionModePointMode:
2323 is_point_mode = true;
2324 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002325 }
2326 }
2327 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002328 default:
2329 break;
2330 }
2331 }
2332
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002333 bool strip_output_array_level =
2334 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2335 bool strip_input_array_level =
2336 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2337 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2338
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002339 uint32_t num_comp_in = 0, num_comp_out = 0;
2340 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002341
2342 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2343 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2344
2345 // Find max component location used for input variables.
2346 for (auto &var : inputs) {
2347 int location = var.first.first;
2348 int component = var.first.second;
2349 interface_var &iv = var.second;
2350
2351 // Only need to look at the first location, since we use the type's whole size
2352 if (iv.offset != 0) {
2353 continue;
2354 }
2355
2356 if (iv.is_patch) {
2357 continue;
2358 }
2359
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002360 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2361 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002362 }
2363
2364 // Find max component location used for output variables.
2365 for (auto &var : outputs) {
2366 int location = var.first.first;
2367 int component = var.first.second;
2368 interface_var &iv = var.second;
2369
2370 // Only need to look at the first location, since we use the type's whole size
2371 if (iv.offset != 0) {
2372 continue;
2373 }
2374
2375 if (iv.is_patch) {
2376 continue;
2377 }
2378
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002379 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2380 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002381 }
2382
2383 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2384 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002385 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002386 // Check if the variable is a patch. Patches can also be members of blocks,
2387 // but if they are then the top-level arrayness has already been stripped
2388 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002389 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002390
2391 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002392 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002393 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002394 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002395 }
2396 }
2397
2398 switch (pStage->stage) {
2399 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002400 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002401 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2402 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2403 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2404 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002405 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002406 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002407 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002408 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2409 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2410 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2411 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002412 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002413 break;
2414
2415 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002416 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002417 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2418 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2419 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2420 "components by %u components",
2421 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002422 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002423 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002424 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002425 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002426 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2427 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2428 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2429 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002430 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002431 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002432 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2433 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2434 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2435 "components by %u components",
2436 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002437 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002438 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002439 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002440 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002441 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2442 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2443 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2444 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002445 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002446 break;
2447
2448 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002449 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002450 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2451 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2452 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2453 "components by %u components",
2454 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002455 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002456 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002457 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002458 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002459 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2460 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2461 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2462 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002463 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002464 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002465 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2466 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2467 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2468 "components by %u components",
2469 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002470 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002471 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002472 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002473 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002474 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2475 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2476 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2477 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002478 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002479 // Portability validation
2480 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2481 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2482 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2483 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2484 " is using abstract patch type IsoLines, but this is not supported on this platform");
2485 }
2486 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2487 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2488 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2489 " is using abstract patch type PointMode, but this is not supported on this platform");
2490 }
2491 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002492 break;
2493
2494 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002495 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002496 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2497 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2498 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2499 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002500 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002501 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002502 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002503 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2504 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2505 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2506 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002507 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002508 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002509 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2510 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2511 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2512 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002513 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002514 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002515 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002516 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2517 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2518 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2519 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002520 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002521 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002522 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2523 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2524 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2525 "components by %u components",
2526 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002527 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002528 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002529 break;
2530
2531 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002532 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002533 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2534 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2535 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2536 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002537 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002538 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002539 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002540 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2541 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2542 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2543 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002544 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002545 break;
2546
Jeff Bolz148d94e2018-12-13 21:25:56 -06002547 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2548 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2549 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2550 case VK_SHADER_STAGE_MISS_BIT_NV:
2551 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2552 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2553 case VK_SHADER_STAGE_TASK_BIT_NV:
2554 case VK_SHADER_STAGE_MESH_BIT_NV:
2555 break;
2556
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002557 default:
2558 assert(false); // This should never happen
2559 }
2560 return skip;
2561}
2562
sfricke-samsungdc96f302020-03-18 20:42:10 -07002563bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2564 bool skip = false;
2565 uint32_t total_resources = 0;
2566
2567 // Only currently testing for graphics and compute pipelines
2568 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2569 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2570 return false;
2571 }
2572
2573 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2574 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2575 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2576 }
2577
2578 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2579 // input from CreatePipeline and CreatePipelineLayout level
2580 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2581 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2582 continue;
2583 }
2584
2585 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2586 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2587 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2588 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2589 // Check only descriptor types listed in maxPerStageResources description in spec
2590 switch (binding->descriptorType) {
2591 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2592 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2593 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2594 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2595 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2596 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2597 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2598 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2599 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2600 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2601 total_resources += binding->descriptorCount;
2602 break;
2603 default:
2604 break;
2605 }
2606 }
2607 }
2608 }
2609
2610 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2611 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2612 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2613 skip |= LogError(pipeline->pipeline, vuid,
2614 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2615 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2616 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2617 }
2618
2619 return skip;
2620}
2621
Jeff Bolze4356752019-03-07 11:23:46 -06002622// copy the specialization constant value into buf, if it is present
2623void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2624 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2625
2626 if (spec && spec_id < spec->mapEntryCount) {
2627 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2628 }
2629}
2630
2631// Fill in value with the constant or specialization constant value, if available.
2632// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002633static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002634 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2635 auto type_id = src->get_def(insn.word(1));
2636 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2637 return false;
2638 }
2639 switch (insn.opcode()) {
2640 case spv::OpSpecConstant:
2641 *value = insn.word(3);
2642 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2643 return true;
2644 case spv::OpConstant:
2645 *value = insn.word(3);
2646 return true;
2647 default:
2648 return false;
2649 }
2650}
2651
2652// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002653VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002654 switch (insn.opcode()) {
2655 case spv::OpTypeInt:
2656 switch (insn.word(2)) {
2657 case 8:
2658 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2659 case 16:
2660 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2661 case 32:
2662 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2663 case 64:
2664 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2665 default:
2666 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2667 }
2668 case spv::OpTypeFloat:
2669 switch (insn.word(2)) {
2670 case 16:
2671 return VK_COMPONENT_TYPE_FLOAT16_NV;
2672 case 32:
2673 return VK_COMPONENT_TYPE_FLOAT32_NV;
2674 case 64:
2675 return VK_COMPONENT_TYPE_FLOAT64_NV;
2676 default:
2677 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2678 }
2679 default:
2680 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2681 }
2682}
2683
2684// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2685// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002686bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002687 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002688 bool skip = false;
2689
2690 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2691 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2692 // Map SPIR-V result ID to the ID of its type.
2693 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2694
2695 struct CoopMatType {
2696 uint32_t scope, rows, cols;
2697 VkComponentTypeNV component_type;
2698 bool all_constant;
2699
2700 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2701
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002702 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002703 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2704 spirv_inst_iter insn = src->get_def(id);
2705 uint32_t component_type_id = insn.word(2);
2706 uint32_t scope_id = insn.word(3);
2707 uint32_t rows_id = insn.word(4);
2708 uint32_t cols_id = insn.word(5);
2709 auto component_type_iter = src->get_def(component_type_id);
2710 auto scope_iter = src->get_def(scope_id);
2711 auto rows_iter = src->get_def(rows_id);
2712 auto cols_iter = src->get_def(cols_id);
2713
2714 all_constant = true;
2715 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2716 all_constant = false;
2717 }
2718 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2719 all_constant = false;
2720 }
2721 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2722 all_constant = false;
2723 }
2724 component_type = GetComponentType(component_type_iter, src);
2725 }
2726 };
2727
2728 bool seen_coopmat_capability = false;
2729
2730 for (auto insn : *src) {
2731 // Whitelist instructions whose result can be a cooperative matrix type, and
2732 // keep track of their types. It would be nice if SPIRV-Headers generated code
2733 // to identify which instructions have a result type and result id. Lacking that,
2734 // this whitelist is based on the set of instructions that
2735 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2736 switch (insn.opcode()) {
2737 case spv::OpLoad:
2738 case spv::OpCooperativeMatrixLoadNV:
2739 case spv::OpCooperativeMatrixMulAddNV:
2740 case spv::OpSNegate:
2741 case spv::OpFNegate:
2742 case spv::OpIAdd:
2743 case spv::OpFAdd:
2744 case spv::OpISub:
2745 case spv::OpFSub:
2746 case spv::OpFDiv:
2747 case spv::OpSDiv:
2748 case spv::OpUDiv:
2749 case spv::OpMatrixTimesScalar:
2750 case spv::OpConstantComposite:
2751 case spv::OpCompositeConstruct:
2752 case spv::OpConvertFToU:
2753 case spv::OpConvertFToS:
2754 case spv::OpConvertSToF:
2755 case spv::OpConvertUToF:
2756 case spv::OpUConvert:
2757 case spv::OpSConvert:
2758 case spv::OpFConvert:
2759 id_to_type_id[insn.word(2)] = insn.word(1);
2760 break;
2761 default:
2762 break;
2763 }
2764
2765 switch (insn.opcode()) {
2766 case spv::OpDecorate:
2767 if (insn.word(2) == spv::DecorationSpecId) {
2768 id_to_spec_id[insn.word(1)] = insn.word(3);
2769 }
2770 break;
2771 case spv::OpCapability:
2772 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2773 seen_coopmat_capability = true;
2774
2775 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002776 skip |= LogError(
2777 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2778 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2779 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002780 }
2781 }
2782 break;
2783 case spv::OpMemoryModel:
2784 // If the capability isn't enabled, don't bother with the rest of this function.
2785 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2786 if (!seen_coopmat_capability) {
2787 return skip;
2788 }
2789 break;
2790 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002791 CoopMatType m;
2792 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002793
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002794 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002795 // Validate that the type parameters are all supported for one of the
2796 // operands of a cooperative matrix property.
2797 bool valid = false;
2798 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002799 if (cooperative_matrix_properties[i].AType == m.component_type &&
2800 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2801 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002802 valid = true;
2803 break;
2804 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002805 if (cooperative_matrix_properties[i].BType == m.component_type &&
2806 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2807 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002808 valid = true;
2809 break;
2810 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002811 if (cooperative_matrix_properties[i].CType == m.component_type &&
2812 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2813 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002814 valid = true;
2815 break;
2816 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002817 if (cooperative_matrix_properties[i].DType == m.component_type &&
2818 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2819 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002820 valid = true;
2821 break;
2822 }
2823 }
2824 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002825 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2826 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2827 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002828 }
2829 }
2830 break;
2831 }
2832 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002833 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002834 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2835 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2836 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2837 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002838 // Couldn't find type of matrix
2839 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002840 break;
2841 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002842 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2843 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2844 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2845 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002846
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002847 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002848 // Validate that the type parameters are all supported for the same
2849 // cooperative matrix property.
2850 bool valid = false;
2851 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002852 if (cooperative_matrix_properties[i].AType == a.component_type &&
2853 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2854 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002855
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002856 cooperative_matrix_properties[i].BType == b.component_type &&
2857 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2858 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002859
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002860 cooperative_matrix_properties[i].CType == c.component_type &&
2861 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2862 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002863
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002864 cooperative_matrix_properties[i].DType == d.component_type &&
2865 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2866 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002867 valid = true;
2868 break;
2869 }
2870 }
2871 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002872 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2873 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2874 "VkCooperativeMatrixPropertiesNV",
2875 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002876 }
2877 }
2878 break;
2879 }
2880 default:
2881 break;
2882 }
2883 }
2884
2885 return skip;
2886}
2887
John Zulaufac4c6e12019-07-01 16:05:58 -06002888bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002889 auto entrypoint_id = entrypoint.word(2);
2890
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002891 // The first denorm execution mode encountered, along with its bit width.
2892 // Used to check if SeparateDenormSettings is respected.
2893 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002894
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002895 // The first rounding mode encountered, along with its bit width.
2896 // Used to check if SeparateRoundingModeSettings is respected.
2897 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002898
2899 bool skip = false;
2900
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002901 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002902 uint32_t invocations = 0;
2903
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002904 for (auto insn : *src) {
2905 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
2906 auto mode = insn.word(2);
2907 switch (mode) {
2908 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2909 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002910 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2911 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2912 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002913 skip |= LogError(
2914 device, kVUID_Core_Shader_FeatureNotEnabled,
2915 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2916 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002917 }
2918 break;
2919 }
2920
2921 case spv::ExecutionModeDenormPreserve: {
2922 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002923 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2924 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2925 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002926 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2927 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2928 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002929 }
2930
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002931 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2932 // Register the first denorm execution mode found
2933 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002934 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002935 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002936 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002937 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002938 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2939 "Shader uses different denorm execution modes for 16 and 64-bit but "
2940 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002941 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002942 }
2943 break;
2944
Mike Schuchardt2df08912020-12-15 16:28:09 -08002945 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002946 break;
2947
Mike Schuchardt2df08912020-12-15 16:28:09 -08002948 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002949 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2950 "Shader uses different denorm execution modes for different bit widths but "
2951 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002952 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002953 break;
2954
2955 default:
2956 break;
2957 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002958 }
2959 break;
2960 }
2961
2962 case spv::ExecutionModeDenormFlushToZero: {
2963 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002964 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2965 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2966 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002967 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2968 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2969 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002970 }
2971
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002972 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2973 // Register the first denorm execution mode found
2974 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002975 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002976 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002977 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002978 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002979 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2980 "Shader uses different denorm execution modes for 16 and 64-bit but "
2981 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002982 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002983 }
2984 break;
2985
Mike Schuchardt2df08912020-12-15 16:28:09 -08002986 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002987 break;
2988
Mike Schuchardt2df08912020-12-15 16:28:09 -08002989 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002990 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2991 "Shader uses different denorm execution modes for different bit widths but "
2992 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002993 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002994 break;
2995
2996 default:
2997 break;
2998 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002999 }
3000 break;
3001 }
3002
3003 case spv::ExecutionModeRoundingModeRTE: {
3004 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003005 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3006 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3007 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003008 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3009 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3010 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003011 }
3012
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003013 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3014 // Register the first rounding mode found
3015 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003016 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003017 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003018 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003019 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003020 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3021 "Shader uses different rounding modes for 16 and 64-bit but "
3022 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003023 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003024 }
3025 break;
3026
Mike Schuchardt2df08912020-12-15 16:28:09 -08003027 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003028 break;
3029
Mike Schuchardt2df08912020-12-15 16:28:09 -08003030 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003031 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3032 "Shader uses different rounding modes for different bit widths but "
3033 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003034 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003035 break;
3036
3037 default:
3038 break;
3039 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003040 }
3041 break;
3042 }
3043
3044 case spv::ExecutionModeRoundingModeRTZ: {
3045 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003046 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3047 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3048 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003049 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3050 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3051 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003052 }
3053
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003054 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3055 // Register the first rounding mode found
3056 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003057 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003058 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003059 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003060 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003061 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3062 "Shader uses different rounding modes for 16 and 64-bit but "
3063 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003064 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003065 }
3066 break;
3067
Mike Schuchardt2df08912020-12-15 16:28:09 -08003068 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003069 break;
3070
Mike Schuchardt2df08912020-12-15 16:28:09 -08003071 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003072 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3073 "Shader uses different rounding modes for different bit widths but "
3074 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003075 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003076 break;
3077
3078 default:
3079 break;
3080 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003081 }
3082 break;
3083 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003084
3085 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003086 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003087 break;
3088 }
3089
3090 case spv::ExecutionModeInvocations: {
3091 invocations = insn.word(3);
3092 break;
3093 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003094 }
3095 }
3096 }
3097
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003098 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003099 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003100 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3101 "Geometry shader entry point must have an OpExecutionMode instruction that "
3102 "specifies a maximum output vertex count that is greater than 0 and less "
3103 "than or equal to maxGeometryOutputVertices. "
3104 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003105 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003106 }
3107
3108 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003109 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3110 "Geometry shader entry point must have an OpExecutionMode instruction that "
3111 "specifies an invocation count that is greater than 0 and less "
3112 "than or equal to maxGeometryShaderInvocations. "
3113 "Invocations=%d, maxGeometryShaderInvocations=%d",
3114 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003115 }
3116 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003117 return skip;
3118}
3119
locke-lunargd9a069d2019-09-17 01:50:19 -06003120uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003121 auto type = module->get_def(type_id);
3122
3123 while (true) {
3124 switch (type.opcode()) {
3125 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003126 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003127 case spv::OpTypeSampledImage:
3128 type = module->get_def(type.word(2));
3129 break;
3130 case spv::OpTypePointer:
3131 type = module->get_def(type.word(3));
3132 break;
3133 case spv::OpTypeImage: {
3134 auto dim = type.word(3);
3135 auto arrayed = type.word(5);
3136 auto msaa = type.word(6);
3137
Chris Forbes74ba2232018-08-27 15:19:27 -07003138 uint32_t bits = 0;
3139 switch (GetFundamentalType(module, type.word(2))) {
3140 case FORMAT_TYPE_FLOAT:
3141 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3142 break;
3143 case FORMAT_TYPE_UINT:
3144 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3145 break;
3146 case FORMAT_TYPE_SINT:
3147 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3148 break;
3149 default:
3150 break;
3151 }
3152
Chris Forbes47567b72017-06-09 12:09:45 -07003153 switch (dim) {
3154 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003155 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3156 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003157 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003158 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3159 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3160 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003161 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003162 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3163 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003164 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003165 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3166 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003167 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003168 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3169 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003170 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003171 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003172 }
3173 }
3174 default:
3175 return 0;
3176 }
3177 }
3178}
3179
3180// For given pipelineLayout verify that the set_layout_node at slot.first
3181// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003182static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003183 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003184 if (!pipelineLayout) return nullptr;
3185
3186 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3187
3188 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3189}
3190
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003191int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3192 if (module == nullptr) return -1;
3193
3194 auto type = module->get_def(resource.type_id);
3195 while (true) {
3196 switch (type.opcode()) {
3197 case spv::OpTypeSampledImage:
3198 type = module->get_def(type.word(2));
3199 break;
3200 case spv::OpTypePointer:
3201 type = module->get_def(type.word(3));
3202 break;
3203 case spv::OpTypeImage:
3204 return type.word(3);
3205 default:
3206 return -1;
3207 }
3208 }
3209}
3210
3211bool 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 -06003212 for (auto insn : *src) {
3213 if (insn.opcode() == spv::OpEntryPoint) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003214 auto execution_model = insn.word(1);
3215 auto entrypoint_stage_bits = ExecutionModelToShaderStageFlagBits(execution_model);
3216 if (entrypoint_stage_bits == VK_SHADER_STAGE_COMPUTE_BIT) {
Locke1ec6d952019-04-02 11:57:21 -06003217 auto entrypoint_id = insn.word(2);
3218 for (auto insn1 : *src) {
3219 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3220 insn1.word(2) == spv::ExecutionModeLocalSize) {
3221 local_size_x = insn1.word(3);
3222 local_size_y = insn1.word(4);
3223 local_size_z = insn1.word(5);
3224 return true;
3225 }
3226 }
3227 }
3228 }
3229 }
3230 return false;
3231}
3232
locke-lunargd9a069d2019-09-17 01:50:19 -06003233void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003234 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003235 bool is_point_mode = false;
3236
3237 for (auto insn : *src) {
3238 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3239 switch (insn.word(2)) {
3240 case spv::ExecutionModePointMode:
3241 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3242 is_point_mode = true;
3243 break;
3244
3245 case spv::ExecutionModeOutputPoints:
3246 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3247 break;
3248
3249 case spv::ExecutionModeIsolines:
3250 case spv::ExecutionModeOutputLineStrip:
3251 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3252 break;
3253
3254 case spv::ExecutionModeTriangles:
3255 case spv::ExecutionModeQuads:
3256 case spv::ExecutionModeOutputTriangleStrip:
3257 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3258 break;
3259 }
3260 }
3261 }
3262
3263 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3264}
3265
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003266// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3267// o If there is only a vertex shader : gl_PointSize must be written when using points
3268// o If there is a geometry or tessellation shader:
3269// - If shaderTessellationAndGeometryPointSize feature is enabled:
3270// * gl_PointSize must be written in the final geometry stage
3271// - If shaderTessellationAndGeometryPointSize feature is disabled:
3272// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003273bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003274 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003275 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3276 return false;
3277 }
3278
3279 bool pointsize_written = false;
3280 bool skip = false;
3281
3282 // Search for PointSize built-in decorations
3283 std::vector<uint32_t> pointsize_builtin_offsets;
3284 spirv_inst_iter insn = entrypoint;
3285 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3286 if (insn.opcode() == spv::OpMemberDecorate) {
3287 if (insn.word(3) == spv::DecorationBuiltIn) {
3288 if (insn.word(4) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003289 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003290 }
3291 }
3292 } else if (insn.opcode() == spv::OpDecorate) {
3293 if (insn.word(2) == spv::DecorationBuiltIn) {
3294 if (insn.word(3) == spv::BuiltInPointSize) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003295 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003296 }
3297 }
3298 }
3299
3300 insn++;
3301 }
3302
3303 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003304 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003305 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003306 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3307 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3308 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003309 }
3310 } else if (!pointsize_written) {
3311 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003312 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3313 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3314 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003315 }
3316 return skip;
3317}
John Zulauf14c355b2019-06-27 16:09:37 -06003318
Tobias Hector6663c9b2020-11-05 10:18:02 +00003319bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3320 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3321 bool primitiverate_written = false;
3322 bool viewportindex_written = false;
3323 bool viewportmask_written = false;
3324 bool skip = false;
3325
3326 // Check if the primitive shading rate is written
3327 spirv_inst_iter insn = entrypoint;
3328 while (!(primitiverate_written && viewportindex_written && viewportmask_written) && insn.opcode() != spv::OpFunction) {
3329 if (insn.opcode() == spv::OpMemberDecorate) {
3330 if (insn.word(3) == spv::DecorationBuiltIn) {
3331 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3332 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3333 } else if (insn.word(4) == spv::BuiltInViewportIndex) {
3334 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3335 } else if (insn.word(4) == spv::BuiltInViewportMaskNV) {
3336 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3337 }
3338 }
3339 } else if (insn.opcode() == spv::OpDecorate) {
3340 if (insn.word(2) == spv::DecorationBuiltIn) {
3341 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3342 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3343 } else if (insn.word(3) == spv::BuiltInViewportIndex) {
3344 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3345 } else if (insn.word(3) == spv::BuiltInViewportMaskNV) {
3346 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
3347 }
3348 }
3349 }
3350
3351 insn++;
3352 }
3353
Tony-LunarGd44844c2021-01-22 13:24:37 -07003354 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3355 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003356 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3357 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003358 skip |= LogError(pipeline->pipeline,
3359 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3360 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3361 "multiple viewports "
3362 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3363 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003364 }
3365
3366 if (primitiverate_written && viewportindex_written) {
3367 skip |= LogError(pipeline->pipeline,
3368 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3369 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3370 "ViewportIndex built-ins,"
3371 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3372 string_VkShaderStageFlagBits(stage));
3373 }
3374
3375 if (primitiverate_written && viewportmask_written) {
3376 skip |= LogError(pipeline->pipeline,
3377 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3378 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3379 "ViewportMaskNV built-ins,"
3380 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3381 string_VkShaderStageFlagBits(stage));
3382 }
3383 }
3384 return skip;
3385}
3386
sfricke-samsung486a51e2021-01-02 00:10:15 -08003387// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003388bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003389 bool skip = false;
3390
sfricke-samsung94167ca2021-02-26 04:14:59 -08003391 switch (insn.opcode()) {
3392 case spv::OpReadClockKHR: {
3393 auto scope_id = module->get_def(insn.word(3));
3394 auto scope_type = scope_id.word(3);
3395 // if scope isn't Subgroup or Device, spirv-val will catch
3396 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3397 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3398 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3399 report_data->FormatHandle(module->vk_shader_module).c_str());
3400 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3401 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3402 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3403 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003404 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003405 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003406 }
3407 }
3408 return skip;
3409}
3410
John Zulauf14c355b2019-06-27 16:09:37 -06003411bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3412 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003413 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003414 bool skip = false;
3415
3416 // Check the module
3417 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003418 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3419 "%s does not contain valid spirv for stage %s.",
3420 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003421 }
3422
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003423 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3424 // specializations should be applied and validated.
3425 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3426 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3427 // Gather the specialization-constant values.
3428 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003429 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003430 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3431 id_value_map.reserve(specialization_info->mapEntryCount);
3432 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3433 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003434
Jeremy Hayes521221d2020-01-15 16:48:49 -07003435 // Expect only scalar types.
3436 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3437 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3438 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003439 }
3440
3441 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003442 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003443 spvtools::Optimizer optimizer(spirv_environment);
3444 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3445 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003446 skip |= LogError(
3447 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003448 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3449 };
3450 optimizer.SetMessageConsumer(consumer);
3451 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3452 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3453 std::vector<uint32_t> specialized_spirv;
3454 auto const optimized =
3455 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3456 assert(optimized == true);
3457
3458 if (optimized) {
3459 spv_context ctx = spvContextCreate(spirv_environment);
3460 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3461 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003462 spvtools::ValidatorOptions options;
3463 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003464 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3465 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003466 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003467 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3468 report_data->FormatHandle(module->vk_shader_module).c_str(),
3469 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003470 }
3471
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003472 spvDiagnosticDestroy(diag);
3473 spvContextDestroy(ctx);
3474 }
3475 }
3476
John Zulauf14c355b2019-06-27 16:09:37 -06003477 // Check the entrypoint
3478 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003479 skip |=
3480 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3481 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003482 }
3483 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3484
3485 // Mark accessible ids
3486 auto &accessible_ids = stage_state.accessible_ids;
3487
Chris Forbes47567b72017-06-09 12:09:45 -07003488 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003489 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3490 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003491
sfricke-samsung94167ca2021-02-26 04:14:59 -08003492 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3493 // and mainly only checking the instruction in detail for a single operation
3494 for (auto insn : *module) {
3495 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3496 skip |= ValidatePropertiesAndFeatures(module, insn);
3497 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3498 }
3499
locke-lunarg63e4daf2020-08-17 17:53:25 -06003500 skip |=
3501 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003502 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003503 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003504 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003505 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003506 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003507 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003508 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003509 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003510 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
Jeff Bolze4356752019-03-07 11:23:46 -06003511 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003512 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3513 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3514 }
Chris Forbes47567b72017-06-09 12:09:45 -07003515
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003516 std::string vuid_layout_mismatch;
3517 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3518 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3519 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3520 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3521 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3522 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3523 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3524 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3525 }
3526
Chris Forbes47567b72017-06-09 12:09:45 -07003527 // Validate descriptor use
3528 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003529 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003530 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003531 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003532 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3533 std::set<uint32_t> descriptor_types =
3534 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003535
3536 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003537 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003538 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3539 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003540 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003541 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003542 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3543 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003544 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003545 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003546 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3547 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3548 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003549 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003550 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003551 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3552 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003553 }
3554 }
3555
3556 // Validate use of input attachments against subpass structure
3557 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003558 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003559
Petr Krause91f7a12017-12-14 20:57:36 +01003560 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003561 auto subpass = pipeline->graphicsPipelineCI.subpass;
3562
3563 for (auto use : input_attachment_uses) {
3564 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3565 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003566 ? input_attachments[use.first].attachment
3567 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003568
3569 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003570 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3571 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003572 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003573 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003574 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3575 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3576 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003577 }
3578 }
3579 }
Lockeaa8fdc02019-04-02 11:59:20 -06003580 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3581 skip |= ValidateComputeWorkGroupSizes(module);
3582 }
Chris Forbes47567b72017-06-09 12:09:45 -07003583 return skip;
3584}
3585
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003586bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3587 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3588 spirv_inst_iter consumer_entrypoint,
3589 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003590 bool skip = false;
3591
3592 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003593 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3594 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003595
3596 auto a_it = outputs.begin();
3597 auto b_it = inputs.begin();
3598
3599 // Maps sorted by key (location); walk them together to find mismatches
3600 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3601 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3602 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3603 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3604 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3605
3606 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003607 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3608 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3609 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003610 a_it++;
3611 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003612 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3613 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3614 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003615 b_it++;
3616 } else {
3617 // subtleties of arrayed interfaces:
3618 // - if is_patch, then the member is not arrayed, even though the interface may be.
3619 // - if is_block_member, then the extra array level of an arrayed interface is not
3620 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003621 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3622 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3623 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003624 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3625 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3626 DescribeType(producer, a_it->second.type_id).c_str(),
3627 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003628 }
3629 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003630 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3631 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3632 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3633 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003634 }
3635 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003636 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3637 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3638 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003639 }
3640 a_it++;
3641 b_it++;
3642 }
3643 }
3644
Ari Suonpaa696b3432019-03-11 14:02:57 +02003645 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3646 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3647 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3648
3649 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3650 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003651 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3652 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003653 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3654 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003655 } else {
3656 auto it_producer = builtins_producer.begin();
3657 auto it_consumer = builtins_consumer.begin();
3658 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3659 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003660 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3661 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3662 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003663 break;
3664 }
3665 it_producer++;
3666 it_consumer++;
3667 }
3668 }
3669 }
3670 }
3671
Chris Forbes47567b72017-06-09 12:09:45 -07003672 return skip;
3673}
3674
John Zulauf14c355b2019-06-27 16:09:37 -06003675static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003676 uint32_t stage_mask = 0;
3677 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3678 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3679 stage_mask |= pCreateInfo->pStages[i].stage;
3680 }
3681 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003682 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3683 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3684 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003685 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3686 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3687 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3688 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3689 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003690 }
3691 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003692 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003693}
3694
Chris Forbes47567b72017-06-09 12:09:45 -07003695// Validate that the shaders used by the given pipeline and store the active_slots
3696// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003697bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003698 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003699 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3700 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003701
John Zulauf14c355b2019-06-27 16:09:37 -06003702 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003703 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003704 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003705 bool skip = false;
3706
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003707 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003708
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003709 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3710 auto stage = &create_info->pStages[i];
3711 auto stage_id = GetShaderStageId(stage->stage);
3712 shaders[stage_id] = GetShaderModuleState(stage->module);
3713 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3714 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3715 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003716 }
3717
3718 // if the shader stages are no good individually, cross-stage validation is pointless.
3719 if (skip) return true;
3720
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003721 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003722
3723 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003724 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003725 }
3726
3727 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003728 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003729 }
3730
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003731 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3732 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003733
3734 while (!shaders[producer] && producer != fragment_stage) {
3735 producer++;
3736 consumer++;
3737 }
3738
3739 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3740 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003741 if (shaders[consumer]) {
3742 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003743 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3744 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003745 }
Chris Forbes47567b72017-06-09 12:09:45 -07003746
3747 producer = consumer;
3748 }
3749 }
3750
3751 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003752 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003753 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003754 }
3755
3756 return skip;
3757}
3758
Tony-LunarGb2ded512021-02-02 16:03:30 -07003759void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3760 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3761
3762 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3763 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3764 return;
3765 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003766
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003767 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3768 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003769 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003770
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003771 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3772 auto stage = &create_info->pStages[i];
3773 auto stage_id = GetShaderStageId(stage->stage);
3774 shaders[stage_id] = GetShaderModuleState(stage->module);
3775 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003776
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003777 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3778 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003779 spirv_inst_iter insn = entrypoints[stage_id];
3780 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003781
Tony-LunarGb2ded512021-02-02 16:03:30 -07003782 while (!primitiverate_written && (insn.opcode() != spv::OpFunction)) {
3783 if (insn.opcode() == spv::OpMemberDecorate) {
3784 if (insn.word(3) == spv::DecorationBuiltIn) {
3785 if (insn.word(4) == spv::BuiltInPrimitiveShadingRateKHR) {
3786 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003787 }
3788 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003789 } else if (insn.opcode() == spv::OpDecorate) {
3790 if (insn.word(2) == spv::DecorationBuiltIn) {
3791 if (insn.word(3) == spv::BuiltInPrimitiveShadingRateKHR) {
3792 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
3793 }
3794 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003795 }
3796
Tony-LunarGb2ded512021-02-02 16:03:30 -07003797 insn++;
3798 }
3799 if (primitiverate_written) {
3800 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3801 }
3802 }
3803 }
3804}
3805
3806bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3807 const char *caller, const DrawDispatchVuid &vuid) const {
3808 auto create_info = pipeline->graphicsPipelineCI.ptr();
3809 bool skip = false;
3810
3811 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3812 auto stage = &create_info->pStages[i];
3813 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3814 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3815 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3816 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3817 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003818 skip |=
3819 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3820 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3821 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3822 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003823 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003824 }
3825 }
3826 }
3827 }
3828
3829 return skip;
3830}
3831
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003832bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003833 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003834
John Zulauf14c355b2019-06-27 16:09:37 -06003835 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3836 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003837
John Zulauf14c355b2019-06-27 16:09:37 -06003838 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003839}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003840
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003841uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3842 uint32_t total = 0;
3843
3844 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3845 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3846 if (stages[stage_index].stage == stageBit) {
3847 total++;
3848 }
3849 }
3850
3851 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3852 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3853 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3854 total += CalcShaderStageCount(library_pipeline, stageBit);
3855 }
3856 }
3857
3858 return total;
3859}
3860
sourav parmarcd5fb182020-07-17 12:58:44 -07003861bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003862 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003863
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003864 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003865 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3866 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3867 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3868 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3869 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3870 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3871 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003872 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003873 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3874 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003875 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003876 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003877 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003878 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3879 skip |= LogError(
3880 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3881 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3882 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003883 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003884 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3885 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003886 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3887 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003888 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003889 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003890 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3891 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3892 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3893 "member must have been created with values of the maxPipelineRayPayloadSize and "
3894 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3895 }
3896 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003897 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003898 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3899 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3900 "vkCreateRayTracingPipelinesKHR: If flags includes "
3901 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3902 "the pLibraries member of libraries must have been created with the "
3903 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3904 }
sourav parmar83c31b12020-05-06 12:30:54 -07003905 }
3906 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003907 } else {
3908 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003909 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3910 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3911 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003912 pipeline->raytracingPipelineCI.maxRecursionDepth,
3913 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3914 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003915 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003916 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3917 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3918
John Zulaufe4474e72019-07-01 17:28:27 -06003919 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003920 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003921
John Zulaufe4474e72019-07-01 17:28:27 -06003922 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3923 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003924
John Zulaufe4474e72019-07-01 17:28:27 -06003925 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003926 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003927
3928 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3929 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3930 if (raygen_stages_count == 0) {
3931 skip |= LogError(
3932 device,
3933 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3934 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3935 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003936 }
3937
3938 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3939 const auto &group = groups[group_index];
3940
3941 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3942 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3943 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3944 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3945 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003946 skip |= LogError(device,
3947 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3948 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3949 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003950 }
3951 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3952 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003953 skip |= LogError(device,
3954 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3955 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3956 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003957 }
3958 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3959 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3960 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003961 skip |= LogError(device,
3962 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3963 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3964 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003965 }
3966 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3967 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003968 skip |= LogError(device,
3969 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3970 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3971 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003972 }
3973 }
3974
3975 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3976 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3977 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3978 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003979 skip |= LogError(device,
3980 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3981 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3982 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003983 }
3984 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3985 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3986 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003987 skip |= LogError(device,
3988 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3989 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3990 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003991 }
3992 }
John Zulaufe4474e72019-07-01 17:28:27 -06003993 }
3994 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003995}
3996
Dave Houltona9df0ce2018-02-07 10:51:23 -07003997uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003998
Dave Houltona9df0ce2018-02-07 10:51:23 -07003999static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07004000 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06004001 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06004002 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07004003 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004004 return nullptr;
4005}
4006
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07004007bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004008 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004009 bool skip = false;
4010 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004011
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06004012 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07004013 return false;
4014 }
4015
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06004016 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004017
4018 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004019 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
4020 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
4021 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004022 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004023 auto cache = GetValidationCacheInfo(pCreateInfo);
4024 uint32_t hash = 0;
4025 if (cache) {
4026 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004027 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004028 }
4029
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004030 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4031 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004032 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004033 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004034 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004035 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004036 spvtools::ValidatorOptions options;
4037 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004038 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004039 if (spv_valid != SPV_SUCCESS) {
4040 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004041 if (spv_valid == SPV_WARNING) {
4042 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4043 diag && diag->error ? diag->error : "(no error text)");
4044 } else {
4045 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4046 diag && diag->error ? diag->error : "(no error text)");
4047 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004048 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004049 } else {
4050 if (cache) {
4051 cache->Insert(hash);
4052 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004053 }
4054
4055 spvDiagnosticDestroy(diag);
4056 spvContextDestroy(ctx);
4057 }
4058
Chris Forbes4ae55b32017-06-09 14:42:56 -07004059 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004060}
4061
John Zulaufac4c6e12019-07-01 16:05:58 -06004062bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004063 bool skip = false;
4064 uint32_t local_size_x = 0;
4065 uint32_t local_size_y = 0;
4066 uint32_t local_size_z = 0;
4067 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
4068 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004069 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4070 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4071 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4072 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004073 }
4074 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004075 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4076 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4077 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4078 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004079 }
4080 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004081 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4082 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4083 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4084 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004085 }
4086
4087 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4088 uint64_t invocations = local_size_x * local_size_y;
4089 // Prevent overflow.
4090 bool fail = false;
4091 if (invocations > UINT32_MAX || invocations > limit) {
4092 fail = true;
4093 }
4094 if (!fail) {
4095 invocations *= local_size_z;
4096 if (invocations > UINT32_MAX || invocations > limit) {
4097 fail = true;
4098 }
4099 }
4100 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004101 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4102 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4103 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4104 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4105 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004106 }
4107 }
4108 return skip;
4109}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004110
4111spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4112 if (api_version >= VK_API_VERSION_1_2) {
4113 return SPV_ENV_VULKAN_1_2;
4114 } else if (api_version >= VK_API_VERSION_1_1) {
4115 if (spirv_1_4) {
4116 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4117 } else {
4118 return SPV_ENV_VULKAN_1_1;
4119 }
4120 }
4121 return SPV_ENV_VULKAN_1_0;
4122}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004123
4124void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4125 spvtools::ValidatorOptions &options) {
4126 if (device_extensions.vk_khr_relaxed_block_layout) {
4127 options.SetRelaxBlockLayout(true);
4128 }
4129 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4130 options.SetUniformBufferStandardLayout(true);
4131 }
4132 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4133 options.SetScalarBlockLayout(true);
4134 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004135 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4136 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4137 options.SetWorkgroupScalarBlockLayout(true);
4138 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004139}