blob: 4e2e1508917e943c37f5d7bb9024eef24a1807e9 [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>
Chris Forbes47567b72017-06-09 12:09:45 -070030#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020031#include <string>
Petr Kraus25810d02019-08-27 17:41:15 +020032#include <vector>
33
Mark Lobodzinski102687e2020-04-28 11:03:28 -060034#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070035#include "vk_loader_platform.h"
36#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_layer_data.h"
38#include "vk_layer_extension_utils.h"
39#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070040#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070041#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020042
Chris Forbes4ae55b32017-06-09 14:42:56 -070043#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070044#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070045
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080046void decoration_set::add(uint32_t decoration, uint32_t value) {
47 switch (decoration) {
48 case spv::DecorationLocation:
49 flags |= location_bit;
50 location = value;
51 break;
52 case spv::DecorationPatch:
53 flags |= patch_bit;
54 break;
55 case spv::DecorationRelaxedPrecision:
56 flags |= relaxed_precision_bit;
57 break;
58 case spv::DecorationBlock:
59 flags |= block_bit;
60 break;
61 case spv::DecorationBufferBlock:
62 flags |= buffer_block_bit;
63 break;
64 case spv::DecorationComponent:
65 flags |= component_bit;
66 component = value;
67 break;
68 case spv::DecorationInputAttachmentIndex:
69 flags |= input_attachment_index_bit;
70 input_attachment_index = value;
71 break;
72 case spv::DecorationDescriptorSet:
73 flags |= descriptor_set_bit;
74 descriptor_set = value;
75 break;
76 case spv::DecorationBinding:
77 flags |= binding_bit;
78 binding = value;
79 break;
80 case spv::DecorationNonWritable:
81 flags |= nonwritable_bit;
82 break;
83 case spv::DecorationBuiltIn:
84 flags |= builtin_bit;
85 builtin = value;
86 break;
87 }
88}
89
Chris Forbes47567b72017-06-09 12:09:45 -070090enum FORMAT_TYPE {
91 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
92 FORMAT_TYPE_SINT = 2,
93 FORMAT_TYPE_UINT = 4,
94};
95
96typedef std::pair<unsigned, unsigned> location_t;
97
Chris Forbes47567b72017-06-09 12:09:45 -070098static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +020099 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
100 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
101 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
102 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
103 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700104};
105
John Zulauf14c355b2019-06-27 16:09:37 -0600106unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
107
Chris Forbes47567b72017-06-09 12:09:45 -0700108// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600109void SHADER_MODULE_STATE::BuildDefIndex() {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600110 function_set func_set = {};
111 EntryPoint *entry_point = nullptr;
112
Chris Forbes47567b72017-06-09 12:09:45 -0700113 for (auto insn : *this) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600114 // offset is not 0, it means it's updated and the offset is in a Function.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700115 if (func_set.offset) {
Jeremy Gebbenfc6f8152021-03-18 16:58:55 -0600116 func_set.op_lists.emplace(insn.opcode(), insn.offset());
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 } else if (entry_point) {
Jeremy Gebbenfc6f8152021-03-18 16:58:55 -0600118 entry_point->decorate_list.emplace(insn.opcode(), insn.offset());
locke-lunargde3f0fa2020-09-10 11:55:31 -0600119 }
120
Chris Forbes47567b72017-06-09 12:09:45 -0700121 switch (insn.opcode()) {
122 // Types
123 case spv::OpTypeVoid:
124 case spv::OpTypeBool:
125 case spv::OpTypeInt:
126 case spv::OpTypeFloat:
127 case spv::OpTypeVector:
128 case spv::OpTypeMatrix:
129 case spv::OpTypeImage:
130 case spv::OpTypeSampler:
131 case spv::OpTypeSampledImage:
132 case spv::OpTypeArray:
133 case spv::OpTypeRuntimeArray:
134 case spv::OpTypeStruct:
135 case spv::OpTypeOpaque:
136 case spv::OpTypePointer:
137 case spv::OpTypeFunction:
138 case spv::OpTypeEvent:
139 case spv::OpTypeDeviceEvent:
140 case spv::OpTypeReserveId:
141 case spv::OpTypeQueue:
142 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600143 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600144 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700145 def_index[insn.word(1)] = insn.offset();
146 break;
147
148 // Fixed constants
149 case spv::OpConstantTrue:
150 case spv::OpConstantFalse:
151 case spv::OpConstant:
152 case spv::OpConstantComposite:
153 case spv::OpConstantSampler:
154 case spv::OpConstantNull:
155 def_index[insn.word(2)] = insn.offset();
156 break;
157
158 // Specialization constants
159 case spv::OpSpecConstantTrue:
160 case spv::OpSpecConstantFalse:
161 case spv::OpSpecConstant:
162 case spv::OpSpecConstantComposite:
163 case spv::OpSpecConstantOp:
164 def_index[insn.word(2)] = insn.offset();
165 break;
166
167 // Variables
168 case spv::OpVariable:
169 def_index[insn.word(2)] = insn.offset();
170 break;
171
172 // Functions
173 case spv::OpFunction:
174 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600175 func_set.id = insn.word(2);
176 func_set.offset = insn.offset();
177 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700178 break;
179
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800180 // Decorations
181 case spv::OpDecorate: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700182 auto target_id = insn.word(1);
183 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
sfricke-samsung94d71a52021-02-26 05:25:43 -0800184 decoration_inst.push_back(insn);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800185 if (insn.word(2) == spv::DecorationBuiltIn) {
186 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(3)));
187 }
188
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800189 } break;
190 case spv::OpGroupDecorate: {
191 auto const &src = decorations[insn.word(1)];
192 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
193 } break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800194 case spv::OpMemberDecorate: {
195 member_decoration_inst.push_back(insn);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800196 if (insn.word(3) == spv::DecorationBuiltIn) {
197 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(4)));
198 }
sfricke-samsung94d71a52021-02-26 05:25:43 -0800199 } break;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800200
John Zulauf14c355b2019-06-27 16:09:37 -0600201 // Entry points ... add to the entrypoint table
202 case spv::OpEntryPoint: {
sfricke-samsung5c65b372021-03-25 05:39:57 -0700203 if (entry_point != nullptr) {
204 multiple_entry_points = true;
205 }
206
John Zulauf14c355b2019-06-27 16:09:37 -0600207 // 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 -0700208 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600209 auto execution_model = insn.word(1);
210 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600211 entry_points.emplace(entrypoint_name,
212 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
213
214 auto range = entry_points.equal_range(entrypoint_name);
215 for (auto it = range.first; it != range.second; ++it) {
216 if (it->second.offset == insn.offset()) {
217 entry_point = &(it->second);
218 break;
219 }
220 }
221 assert(entry_point != nullptr);
222 break;
223 }
224 case spv::OpFunctionEnd: {
225 assert(entry_point != nullptr);
226 func_set.length = insn.offset() - func_set.offset;
227 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600228 break;
229 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800230
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700231 // Copy operations
232 case spv::OpCopyLogical:
233 case spv::OpCopyObject: {
234 def_index[insn.word(2)] = insn.offset();
235 break;
236 }
237
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800238 // Execution Mode
239 case spv::OpExecutionMode: {
240 execution_mode_inst[insn.word(1)].push_back(insn);
241 } break;
242
Chris Forbes47567b72017-06-09 12:09:45 -0700243 default:
244 // We don't care about any other defs for now.
245 break;
246 }
247 }
248}
249
Jeff Bolz105d6492018-09-29 15:46:44 -0500250unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
251 switch (mode) {
252 case spv::ExecutionModelVertex:
253 return VK_SHADER_STAGE_VERTEX_BIT;
254 case spv::ExecutionModelTessellationControl:
255 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
256 case spv::ExecutionModelTessellationEvaluation:
257 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
258 case spv::ExecutionModelGeometry:
259 return VK_SHADER_STAGE_GEOMETRY_BIT;
260 case spv::ExecutionModelFragment:
261 return VK_SHADER_STAGE_FRAGMENT_BIT;
262 case spv::ExecutionModelGLCompute:
263 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600264 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700265 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600266 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700267 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600268 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700269 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600270 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700271 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600272 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700273 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600274 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700275 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500276 case spv::ExecutionModelTaskNV:
277 return VK_SHADER_STAGE_TASK_BIT_NV;
278 case spv::ExecutionModelMeshNV:
279 return VK_SHADER_STAGE_MESH_BIT_NV;
280 default:
281 return 0;
282 }
283}
284
locke-lunargde3f0fa2020-09-10 11:55:31 -0600285const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
286 VkShaderStageFlagBits stageBits) {
287 auto range = src->entry_points.equal_range(name);
288 for (auto it = range.first; it != range.second; ++it) {
289 if (it->second.stage == stageBits) {
290 return &(it->second);
291 }
292 }
293 return nullptr;
294}
295
locke-lunargd9a069d2019-09-17 01:50:19 -0600296spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600297 auto range = src->entry_points.equal_range(name);
298 for (auto it = range.first; it != range.second; ++it) {
299 if (it->second.stage == stageBits) {
300 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700301 }
302 }
Chris Forbes47567b72017-06-09 12:09:45 -0700303 return src->end();
304}
305
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600306static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700307 switch (sc) {
308 case spv::StorageClassInput:
309 return "input";
310 case spv::StorageClassOutput:
311 return "output";
312 case spv::StorageClassUniformConstant:
313 return "const uniform";
314 case spv::StorageClassUniform:
315 return "uniform";
316 case spv::StorageClassWorkgroup:
317 return "workgroup local";
318 case spv::StorageClassCrossWorkgroup:
319 return "workgroup global";
320 case spv::StorageClassPrivate:
321 return "private global";
322 case spv::StorageClassFunction:
323 return "function";
324 case spv::StorageClassGeneric:
325 return "generic";
326 case spv::StorageClassAtomicCounter:
327 return "atomic counter";
328 case spv::StorageClassImage:
329 return "image";
330 case spv::StorageClassPushConstant:
331 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800332 case spv::StorageClassStorageBuffer:
333 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700334 default:
335 return "unknown";
336 }
337}
338
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700339// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
340// Otherwise, returns src->end().
341spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700342 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700343
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700344 // If id is a copy, see where it was copied from
345 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
346 id = value.word(3);
347 value = src->get_def(id);
348 }
349
350 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
351 return value;
352 }
353 return src->end();
354}
355
356// Assumes itr points to an OpConstant instruction
357uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
358
359// Either returns the constant value described by the instruction at id, or 1
360uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
361 auto value = GetConstantDef(src, id);
362
363 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700364 // TODO: Either ensure that the specialization transform is already performed on a module we're
365 // considering here, OR -- specialize on the fly now.
366 return 1;
367 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700368 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700369}
370
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600371static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700372 auto insn = src->get_def(type);
373 assert(insn != src->end());
374
375 switch (insn.opcode()) {
376 case spv::OpTypeBool:
377 ss << "bool";
378 break;
379 case spv::OpTypeInt:
380 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
381 break;
382 case spv::OpTypeFloat:
383 ss << "float" << insn.word(2);
384 break;
385 case spv::OpTypeVector:
386 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600387 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700388 break;
389 case spv::OpTypeMatrix:
390 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600391 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700392 break;
393 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600394 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
395 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700396 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700397 case spv::OpTypeRuntimeArray:
398 ss << "runtime arr[] of ";
399 DescribeTypeInner(ss, src, insn.word(2));
400 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700401 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600402 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
403 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700404 break;
405 case spv::OpTypeStruct: {
406 ss << "struct of (";
407 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600408 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700409 if (i == insn.len() - 1) {
410 ss << ")";
411 } else {
412 ss << ", ";
413 }
414 }
415 break;
416 }
417 case spv::OpTypeSampler:
418 ss << "sampler";
419 break;
420 case spv::OpTypeSampledImage:
421 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600422 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700423 break;
424 case spv::OpTypeImage:
425 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
426 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600427 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500428 ss << "accelerationStruture";
429 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700430 default:
431 ss << "oddtype";
432 break;
433 }
434}
435
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600436static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700437 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600438 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700439 return ss.str();
440}
441
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600442static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700443 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
444 return type.word(2) < 64;
445}
446
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600447static 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 -0600448 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700449 // Walk two type trees together, and complain about differences
450 auto a_insn = a->get_def(a_type);
451 auto b_insn = b->get_def(b_type);
452 assert(a_insn != a->end());
453 assert(b_insn != b->end());
454
Chris Forbes062f1222018-08-21 15:34:15 -0700455 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
456
Chris Forbes47567b72017-06-09 12:09:45 -0700457 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600458 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700459 }
460
461 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
462 // 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 -0600463 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700464 }
465
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600466 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
467 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700468 }
469
470 if (a_insn.opcode() != b_insn.opcode()) {
471 return false;
472 }
473
474 if (a_insn.opcode() == spv::OpTypePointer) {
475 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600476 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700477 }
478
479 if (a_arrayed || b_arrayed) {
480 // If we havent resolved array-of-verts by here, we're not going to.
481 return false;
482 }
483
484 switch (a_insn.opcode()) {
485 case spv::OpTypeBool:
486 return true;
487 case spv::OpTypeInt:
488 // Match on width, signedness
489 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
490 case spv::OpTypeFloat:
491 // Match on width
492 return a_insn.word(2) == b_insn.word(2);
493 case spv::OpTypeVector:
494 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600495 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
496 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700497 return a_insn.word(3) >= b_insn.word(3);
498 } else {
499 return a_insn.word(3) == b_insn.word(3);
500 }
501 case spv::OpTypeMatrix:
502 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600503 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700504 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700505 case spv::OpTypeArray:
506 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
507 // 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 -0600508 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
509 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700510 case spv::OpTypeStruct:
511 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700512 {
513 if (a_insn.len() != b_insn.len()) {
514 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700515 }
Chris Forbes47567b72017-06-09 12:09:45 -0700516
Dave Houltona9df0ce2018-02-07 10:51:23 -0700517 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600518 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700519 return false;
520 }
521 }
522
523 return true;
524 }
Chris Forbes47567b72017-06-09 12:09:45 -0700525 default:
526 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
527 return false;
528 }
529}
530
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600531static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700532 auto insn = src->get_def(type);
533 assert(insn != src->end());
534
535 switch (insn.opcode()) {
536 case spv::OpTypePointer:
537 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
538 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600539 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700540 case spv::OpTypeArray:
541 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600542 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700543 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600544 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700545 }
546 case spv::OpTypeMatrix:
547 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600548 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700549 case spv::OpTypeVector: {
550 auto scalar_type = src->get_def(insn.word(2));
551 auto bit_width =
552 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
553
554 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
555 return (bit_width * insn.word(3) + 127) / 128;
556 }
557 default:
558 // Everything else is just 1.
559 return 1;
560
561 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
562 }
563}
564
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600565static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200566 auto insn = src->get_def(type);
567 assert(insn != src->end());
568
569 switch (insn.opcode()) {
570 case spv::OpTypePointer:
571 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
572 // pointers around.
573 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
574 case spv::OpTypeStruct: {
575 uint32_t sum = 0;
576 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
577 sum += GetComponentsConsumedByType(src, insn.word(i), false);
578 }
579 return sum;
580 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500581 case spv::OpTypeArray:
582 if (strip_array_level) {
583 return GetComponentsConsumedByType(src, insn.word(2), false);
584 } else {
585 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200586 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200587 case spv::OpTypeMatrix:
588 // Num locations is the dimension * element size
589 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
590 case spv::OpTypeVector: {
591 auto scalar_type = src->get_def(insn.word(2));
592 auto bit_width =
593 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
594 // One component is 32-bit
595 return (bit_width * insn.word(3) + 31) / 32;
596 }
597 case spv::OpTypeFloat: {
598 auto bit_width = insn.word(2);
599 return (bit_width + 31) / 32;
600 }
601 case spv::OpTypeInt: {
602 auto bit_width = insn.word(2);
603 return (bit_width + 31) / 32;
604 }
605 case spv::OpConstant:
606 return GetComponentsConsumedByType(src, insn.word(1), false);
607 default:
608 return 0;
609 }
610}
611
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600612static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700613 switch (format) {
614 case VK_FORMAT_R64G64B64A64_SFLOAT:
615 case VK_FORMAT_R64G64B64A64_SINT:
616 case VK_FORMAT_R64G64B64A64_UINT:
617 case VK_FORMAT_R64G64B64_SFLOAT:
618 case VK_FORMAT_R64G64B64_SINT:
619 case VK_FORMAT_R64G64B64_UINT:
620 return 2;
621 default:
622 return 1;
623 }
624}
625
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600626static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700627 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
628 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
629 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
630 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700631 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
632 return FORMAT_TYPE_FLOAT;
633}
634
635// 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 -0700636// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600637static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700638 auto insn = src->get_def(type);
639 assert(insn != src->end());
640
641 switch (insn.opcode()) {
642 case spv::OpTypeInt:
643 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
644 case spv::OpTypeFloat:
645 return FORMAT_TYPE_FLOAT;
646 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700647 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700648 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700649 case spv::OpTypeRuntimeArray:
650 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600651 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700652 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600653 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700654
655 default:
656 return 0;
657 }
658}
659
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600660static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700661 uint32_t bit_pos = uint32_t(u_ffs(stage));
662 return bit_pos - 1;
663}
664
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600665static 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 -0700666 while (true) {
667 if (def.opcode() == spv::OpTypePointer) {
668 def = src->get_def(def.word(3));
669 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
670 def = src->get_def(def.word(2));
671 is_array_of_verts = false;
672 } else if (def.opcode() == spv::OpTypeStruct) {
673 return def;
674 } else {
675 return src->end();
676 }
677 }
678}
679
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600680static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800681 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
682 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700683 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600684 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800685 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700686 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700687 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700688 }
689
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700690 layer_data::unordered_map<unsigned, unsigned> member_components;
691 layer_data::unordered_map<unsigned, unsigned> member_relaxed_precision;
692 layer_data::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700693
694 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800695 for (auto insn : src->member_decoration_inst) {
696 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700697 unsigned member_index = insn.word(2);
698
699 if (insn.word(3) == spv::DecorationComponent) {
700 unsigned component = insn.word(4);
701 member_components[member_index] = component;
702 }
703
704 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
705 member_relaxed_precision[member_index] = 1;
706 }
Chris Forbesa313d772017-06-13 13:59:41 -0700707
708 if (insn.word(3) == spv::DecorationPatch) {
709 member_patch[member_index] = 1;
710 }
Chris Forbes47567b72017-06-09 12:09:45 -0700711 }
712 }
713
Chris Forbesa313d772017-06-13 13:59:41 -0700714 // TODO: correctly handle location assignment from outside
715
Chris Forbes47567b72017-06-09 12:09:45 -0700716 // Second pass -- produce the output, from Location decorations
sfricke-samsung94d71a52021-02-26 05:25:43 -0800717 for (auto insn : src->member_decoration_inst) {
718 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700719 unsigned member_index = insn.word(2);
720 unsigned member_type_id = type.word(2 + member_index);
721
722 if (insn.word(3) == spv::DecorationLocation) {
723 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600724 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700725 auto component_it = member_components.find(member_index);
726 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
727 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700728 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700729
730 for (unsigned int offset = 0; offset < num_locations; offset++) {
731 interface_var v = {};
732 v.id = id;
733 // TODO: member index in interface_var too?
734 v.type_id = member_type_id;
735 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700736 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700737 v.is_block_member = true;
738 v.is_relaxed_precision = is_relaxed_precision;
739 (*out)[std::make_pair(location + offset, component)] = v;
740 }
741 }
742 }
743 }
Chris Forbesa313d772017-06-13 13:59:41 -0700744
745 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700746}
747
Ari Suonpaa696b3432019-03-11 14:02:57 +0200748static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800749 assert(entrypoint.opcode() == spv::OpEntryPoint);
750
Ari Suonpaa696b3432019-03-11 14:02:57 +0200751 std::vector<uint32_t> interfaces;
752 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
753 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
754 uint32_t word = 3;
755 while (entrypoint.word(word) & 0xff000000u) {
756 ++word;
757 }
758 ++word;
759
760 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
761
762 return interfaces;
763}
764
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600765static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600766 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700767 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
768
Chris Forbes47567b72017-06-09 12:09:45 -0700769 std::map<location_t, interface_var> out;
770
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800771 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
772 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700773 assert(insn != src->end());
774 assert(insn.opcode() == spv::OpVariable);
775
776 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800777 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700778 unsigned id = insn.word(2);
779 unsigned type = insn.word(1);
780
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800781 int location = d.location;
782 int builtin = d.builtin;
783 unsigned component = d.component;
784 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
785 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700786
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700787 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700788 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700789 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700790 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
791 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600792 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700793 for (unsigned int offset = 0; offset < num_locations; offset++) {
794 interface_var v = {};
795 v.id = id;
796 v.type_id = type;
797 v.offset = offset;
798 v.is_patch = is_patch;
799 v.is_relaxed_precision = is_relaxed_precision;
800 out[std::make_pair(location + offset, component)] = v;
801 }
Chris Forbes47567b72017-06-09 12:09:45 -0700802 }
803 }
804 }
805
806 return out;
807}
808
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600809static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200810 uint32_t storageClass) {
811 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700812 std::vector<uint32_t> builtin_struct_members;
813 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200814
sfricke-samsung94d71a52021-02-26 05:25:43 -0800815 for (auto insn : src->member_decoration_inst) {
816 if (insn.word(3) == spv::DecorationBuiltIn) {
817 builtin_struct_members.push_back(insn.word(1));
818 }
819 }
820 for (auto insn : src->decoration_inst) {
821 switch (insn.word(2)) {
822 case spv::DecorationBlock: {
823 uint32_t block_id = insn.word(1);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800824 for (auto builtin_block_id : builtin_struct_members) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800825 // Check if one of the members of the block are built-in -> the block is built-in
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800826 if (block_id == builtin_block_id) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800827 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200828 break;
829 }
Ari Suonpaa696b3432019-03-11 14:02:57 +0200830 }
831 break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800832 }
833 case spv::DecorationBuiltIn:
834 builtin_decorations.push_back(insn.word(1));
835 break;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200836 default:
837 break;
838 }
839 }
840
841 // Find all interface variables belonging to the entrypoint and matching the storage class
842 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
843 auto def = src->get_def(id);
844 assert(def != src->end());
845 assert(def.opcode() == spv::OpVariable);
846
847 if (def.word(3) == storageClass) variables.push_back(def.word(1));
848 }
849
850 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700851 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200852 for (auto &var : variables) {
853 auto def = src->get_def(src->get_def(var).word(3));
854
855 // It could be an array of IO blocks. The element type should be the struct defining the block contents
856 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
857
858 // Now find all members belonging to the struct defining the IO block
859 if (def.opcode() == spv::OpTypeStruct) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800860 for (auto builtin_id : builtin_decorations) {
861 if (builtin_id == def.word(1)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700862 for (int i = 2; i < static_cast<int>(def.len()); i++) {
863 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
864 }
865 // These shouldn't be left after replacing.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800866 for (auto insn : src->member_decoration_inst) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800867 if (insn.word(1) == builtin_id && insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700868 auto struct_index = insn.word(2);
869 assert(struct_index < builtin_block_members.size());
870 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200871 }
872 }
873 }
874 }
875 }
876 }
877
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700878 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200879}
880
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600881static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700882 SHADER_MODULE_STATE const *src, layer_data::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700883 std::vector<std::pair<uint32_t, interface_var>> out;
884
sfricke-samsung94d71a52021-02-26 05:25:43 -0800885 for (auto insn : src->decoration_inst) {
886 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
887 auto attachment_index = insn.word(3);
888 auto id = insn.word(1);
Chris Forbes47567b72017-06-09 12:09:45 -0700889
sfricke-samsung94d71a52021-02-26 05:25:43 -0800890 if (accessible_ids.count(id)) {
891 auto def = src->get_def(id);
892 assert(def != src->end());
893 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
894 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
895 for (unsigned int offset = 0; offset < num_locations; offset++) {
896 interface_var v = {};
897 v.id = id;
898 v.type_id = def.word(1);
899 v.offset = offset;
900 out.emplace_back(attachment_index + offset, v);
Chris Forbes47567b72017-06-09 12:09:45 -0700901 }
902 }
903 }
904 }
905 }
906
907 return out;
908}
909
locke-lunarg25b6c352020-08-06 17:44:18 -0600910static bool AtomicOperation(uint32_t opcode) {
911 switch (opcode) {
912 case spv::OpAtomicLoad:
913 case spv::OpAtomicStore:
914 case spv::OpAtomicExchange:
915 case spv::OpAtomicCompareExchange:
916 case spv::OpAtomicCompareExchangeWeak:
917 case spv::OpAtomicIIncrement:
918 case spv::OpAtomicIDecrement:
919 case spv::OpAtomicIAdd:
920 case spv::OpAtomicISub:
921 case spv::OpAtomicSMin:
922 case spv::OpAtomicUMin:
923 case spv::OpAtomicSMax:
924 case spv::OpAtomicUMax:
925 case spv::OpAtomicAnd:
926 case spv::OpAtomicOr:
927 case spv::OpAtomicXor:
928 case spv::OpAtomicFAddEXT:
929 return true;
930 default:
931 return false;
932 }
933 return false;
934}
935
sfricke-samsung0065ce02020-12-03 22:46:37 -0800936// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
937// covered with VUID 01090
938static bool GroupOperation(uint32_t opcode) {
939 switch (opcode) {
940 case spv::OpGroupNonUniformElect:
941 case spv::OpGroupNonUniformAll:
942 case spv::OpGroupNonUniformAny:
943 case spv::OpGroupNonUniformAllEqual:
944 case spv::OpGroupNonUniformBroadcast:
945 case spv::OpGroupNonUniformBroadcastFirst:
946 case spv::OpGroupNonUniformBallot:
947 case spv::OpGroupNonUniformInverseBallot:
948 case spv::OpGroupNonUniformBallotBitExtract:
949 case spv::OpGroupNonUniformBallotBitCount:
950 case spv::OpGroupNonUniformBallotFindLSB:
951 case spv::OpGroupNonUniformBallotFindMSB:
952 case spv::OpGroupNonUniformShuffle:
953 case spv::OpGroupNonUniformShuffleXor:
954 case spv::OpGroupNonUniformShuffleUp:
955 case spv::OpGroupNonUniformShuffleDown:
956 case spv::OpGroupNonUniformIAdd:
957 case spv::OpGroupNonUniformFAdd:
958 case spv::OpGroupNonUniformIMul:
959 case spv::OpGroupNonUniformFMul:
960 case spv::OpGroupNonUniformSMin:
961 case spv::OpGroupNonUniformUMin:
962 case spv::OpGroupNonUniformFMin:
963 case spv::OpGroupNonUniformSMax:
964 case spv::OpGroupNonUniformUMax:
965 case spv::OpGroupNonUniformFMax:
966 case spv::OpGroupNonUniformBitwiseAnd:
967 case spv::OpGroupNonUniformBitwiseOr:
968 case spv::OpGroupNonUniformBitwiseXor:
969 case spv::OpGroupNonUniformLogicalAnd:
970 case spv::OpGroupNonUniformLogicalOr:
971 case spv::OpGroupNonUniformLogicalXor:
972 case spv::OpGroupNonUniformQuadBroadcast:
973 case spv::OpGroupNonUniformQuadSwap:
974 case spv::OpGroupNonUniformPartitionNV:
975 return true;
976 default:
977 return false;
978 }
979 return false;
980}
981
locke-lunarg12d20992020-09-21 12:46:49 -0600982bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700983 const layer_data::unordered_map<unsigned, unsigned> &load_members,
984 const layer_data::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
locke-lunarg12d20992020-09-21 12:46:49 -0600985 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600986 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600987 auto load_it = load_members.find(load_id);
988 if (load_it == load_members.end()) {
989 continue;
990 }
991 if (load_it->second == object_id) {
992 return true;
993 }
994
995 auto accesschain_it = accesschain_members.find(load_it->second);
996 if (accesschain_it == accesschain_members.end()) {
997 continue;
998 }
999 if (accesschain_it->second.first == object_id) {
1000 return true;
1001 }
1002 }
1003 return false;
1004}
1005
locke-lunargae2a43c2020-09-22 17:21:57 -06001006bool CheckImageOperandsBiasOffset(uint32_t type) {
1007 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1008 spv::ImageOperandsConstOffsetsMask)
1009 ? true
1010 : false;
1011}
1012
locke-lunargd3da0422020-09-23 01:02:11 -06001013struct shader_module_used_operators {
1014 bool updated;
1015 std::vector<unsigned> imagwrite_members;
1016 std::vector<unsigned> atomic_members;
1017 std::vector<unsigned> store_members;
1018 std::vector<unsigned> atomic_store_members;
1019 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1020 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001021 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001022 layer_data::unordered_map<unsigned, unsigned> load_members;
1023 layer_data::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1024 layer_data::unordered_map<unsigned, unsigned> image_texel_pointer_members;
locke-lunargd3da0422020-09-23 01:02:11 -06001025
1026 shader_module_used_operators() : updated(false) {}
1027
1028 void update(SHADER_MODULE_STATE const *module) {
1029 if (updated) return;
1030 updated = true;
1031
1032 for (auto insn : *module) {
1033 switch (insn.opcode()) {
1034 case spv::OpImageSampleImplicitLod:
1035 case spv::OpImageSampleProjImplicitLod:
1036 case spv::OpImageSampleProjExplicitLod:
1037 case spv::OpImageSparseSampleImplicitLod:
1038 case spv::OpImageSparseSampleProjImplicitLod:
1039 case spv::OpImageSparseSampleProjExplicitLod: {
1040 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1041 // ImageOperands in index: 5
1042 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1043 sampler_bias_offset_members.emplace_back(insn.word(3));
1044 }
1045 break;
1046 }
1047 case spv::OpImageSampleDrefImplicitLod:
1048 case spv::OpImageSampleDrefExplicitLod:
1049 case spv::OpImageSampleProjDrefImplicitLod:
1050 case spv::OpImageSampleProjDrefExplicitLod:
1051 case spv::OpImageSparseSampleDrefImplicitLod:
1052 case spv::OpImageSparseSampleDrefExplicitLod:
1053 case spv::OpImageSparseSampleProjDrefImplicitLod:
1054 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1055 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1056 // ImageOperands in index: 6
1057 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1058 sampler_bias_offset_members.emplace_back(insn.word(3));
1059 }
1060 break;
1061 }
1062 case spv::OpImageSampleExplicitLod:
1063 case spv::OpImageSparseSampleExplicitLod: {
1064 // ImageOperands in index: 5
1065 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1066 sampler_bias_offset_members.emplace_back(insn.word(3));
1067 }
1068 break;
1069 }
1070 case spv::OpStore: {
1071 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1072 break;
1073 }
1074 case spv::OpImageWrite: {
1075 imagwrite_members.emplace_back(insn.word(1)); // Load id
1076 break;
1077 }
1078 case spv::OpSampledImage: {
1079 // 3: image load id, 4: sampler load id
1080 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1081 break;
1082 }
1083 case spv::OpLoad: {
1084 // 2: Load id, 3: object id or AccessChain id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001085 load_members.emplace(insn.word(2), insn.word(3));
locke-lunargd3da0422020-09-23 01:02:11 -06001086 break;
1087 }
1088 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001089 if (insn.len() == 4) {
1090 // If it is for struct, the length is only 4.
1091 // 2: AccessChain id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001092 accesschain_members.emplace(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0));
locke-lunarg025daa72020-10-13 11:07:51 -06001093 } else {
1094 // 2: AccessChain id, 3: object id, 4: object id of array index
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001095 accesschain_members.emplace(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
locke-lunarg025daa72020-10-13 11:07:51 -06001096 }
locke-lunargd3da0422020-09-23 01:02:11 -06001097 break;
1098 }
1099 case spv::OpImageTexelPointer: {
1100 // 2: ImageTexelPointer id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001101 image_texel_pointer_members.emplace(insn.word(2), insn.word(3));
locke-lunargd3da0422020-09-23 01:02:11 -06001102 break;
1103 }
1104 default: {
1105 if (AtomicOperation(insn.opcode())) {
1106 if (insn.opcode() == spv::OpAtomicStore) {
1107 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1108 } else {
1109 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1110 }
1111 }
1112 break;
1113 }
1114 }
1115 }
1116 }
1117};
1118
sfricke-samsung691299b2021-01-01 20:48:48 -08001119// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1120// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001121static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001122 bool is_check_writable, interface_var &out_interface_var,
1123 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001124 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001125 unsigned int id = id_it.word(2);
1126
Chris Forbes8af24522018-03-07 11:37:45 -08001127 auto type = module->get_def(type_id);
1128
1129 // 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 -06001130 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1131 type.opcode() == spv::OpTypeSampledImage) {
1132 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1133 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001134 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001135 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001136 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001137 }
1138 }
Chris Forbes8af24522018-03-07 11:37:45 -08001139 switch (type.opcode()) {
1140 case spv::OpTypeImage: {
1141 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001142 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001143 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001144
locke-lunargd3da0422020-09-23 01:02:11 -06001145 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1146 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001147 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001148 }
1149 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1150 used_operators.accesschain_members)) {
1151 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001152 }
locke-lunargd3da0422020-09-23 01:02:11 -06001153 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1154 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001155 out_interface_var.is_sampler_bias_offset = true;
1156 }
locke-lunargd3da0422020-09-23 01:02:11 -06001157 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1158 used_operators.accesschain_members) ||
1159 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1160 used_operators.accesschain_members)) {
1161 out_interface_var.is_atomic_operation = true;
1162 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001163
locke-lunargd3da0422020-09-23 01:02:11 -06001164 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001165 // Find if image id match.
1166 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001167 auto load_it = used_operators.load_members.find(itp_id.first);
1168 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001169 continue;
1170 } else {
1171 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001172 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1173 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001174 continue;
1175 } else {
1176 if (accesschain_it->second.first != id) {
1177 continue;
1178 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001179
1180 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1181 if (const_itr == module->end()) {
1182 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001183 break;
1184 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001185 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001186 }
1187 }
1188 }
1189 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001190 load_it = used_operators.load_members.find(itp_id.second);
1191 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001192 continue;
1193 } else {
1194 uint32_t sampler_id = load_it->second;
1195 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001196 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001197
locke-lunargd3da0422020-09-23 01:02:11 -06001198 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001199 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1200 if (const_itr == module->end()) {
1201 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001202 break;
1203 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001204 sampler_id = const_itr.offset();
1205 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001206 }
1207 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001208 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1209 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1210 }
1211 out_interface_var.samplers_used_by_image[image_index].emplace(
1212 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001213 }
1214 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001215 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001216 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001217 }
1218
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001219 case spv::OpTypeStruct: {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001220 layer_data::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001221 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
sfricke-samsung94d71a52021-02-26 05:25:43 -08001222 for (auto insn : module->member_decoration_inst) {
1223 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001224 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001225 }
1226 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001227
1228 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1229 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001230 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001231 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001232
locke-lunargd3da0422020-09-23 01:02:11 -06001233 for (auto oid : used_operators.store_members) {
1234 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001235 out_interface_var.is_writable = true;
1236 return;
1237 }
locke-lunargd3da0422020-09-23 01:02:11 -06001238 auto accesschain_it = used_operators.accesschain_members.find(oid);
1239 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001240 continue;
1241 }
locke-lunargd3da0422020-09-23 01:02:11 -06001242 if (accesschain_it->second.first == id) {
1243 out_interface_var.is_writable = true;
1244 return;
1245 }
1246 }
1247 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1248 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001249 out_interface_var.is_writable = true;
1250 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001251 }
1252 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001253 }
Chris Forbes8af24522018-03-07 11:37:45 -08001254 }
Chris Forbes8af24522018-03-07 11:37:45 -08001255}
1256
locke-lunargd9a069d2019-09-17 01:50:19 -06001257std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001258 SHADER_MODULE_STATE const *src, layer_data::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
locke-lunarg63e4daf2020-08-17 17:53:25 -06001259 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001260 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001261 shader_module_used_operators operators;
1262
Chris Forbes47567b72017-06-09 12:09:45 -07001263 for (auto id : accessible_ids) {
1264 auto insn = src->get_def(id);
1265 assert(insn != src->end());
1266
1267 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001268 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1269 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001270 auto d = src->get_decorations(insn.word(2));
1271 unsigned set = d.descriptor_set;
1272 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001273
1274 interface_var v = {};
1275 v.id = insn.word(2);
1276 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001277
locke-lunarg25b6c352020-08-06 17:44:18 -06001278 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001279 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001280 if (v.is_writable) *has_writable_descriptor = true;
1281 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001282 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001283 }
1284 }
1285
1286 return out;
1287}
1288
locke-lunargde3f0fa2020-09-10 11:55:31 -06001289void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1290 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1291 const auto struct_it = GetStructType(&src, it, false);
1292 assert(struct_it != src.end());
1293 data.size = 0;
1294
1295 shader_struct_member data1;
1296 uint32_t i = 2;
1297 uint32_t local_offset = 0;
1298 std::vector<uint32_t> offsets;
1299 offsets.resize(struct_it.len() - i);
1300
1301 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1302 for (const auto offset : memberDecorate_offsets) {
1303 const auto member_decorate = src.at(offset);
1304 if (member_decorate.word(1) != struct_it.word(1)) {
1305 continue;
1306 }
1307
1308 offsets[member_decorate.word(2)] = member_decorate.word(4);
1309 }
1310
1311 for (const auto offset : offsets) {
1312 local_offset = offset;
1313 data1 = {};
1314 data1.root = data.root;
1315 data1.offset = local_offset;
1316 auto def_member = src.get_def(struct_it.word(i));
1317
1318 // Array could be multi-dimensional
1319 while (def_member.opcode() == spv::OpTypeArray) {
1320 const auto len_id = def_member.word(3);
1321 const auto def_len = src.get_def(len_id);
1322 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1323 def_member = src.get_def(def_member.word(2));
1324 }
1325
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001326 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001327 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001328 } else if (def_member.opcode() == spv::OpTypePointer) {
1329 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1330 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1331 // that "points to something."
1332 data1.size = 8;
1333 } else {
1334 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1335 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1336 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001337 } else {
1338 if (def_member.opcode() == spv::OpTypeMatrix) {
1339 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1340 def_member = src.get_def(def_member.word(2));
1341 }
1342
1343 if (def_member.opcode() == spv::OpTypeVector) {
1344 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1345 def_member = src.get_def(def_member.word(2));
1346 }
1347
1348 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1349 data1.size = (def_member.word(2) / 8);
1350 }
1351 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1352 if (array_length_hierarchy_szie > 0) {
1353 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1354
1355 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1356 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1357 }
1358 }
1359 data.struct_members.emplace_back(data1);
1360 ++i;
1361 }
1362 uint32_t total_array_length = 1;
1363 for (const auto length : data1.array_length_hierarchy) {
1364 total_array_length *= length;
1365 }
1366 data.size = local_offset + data1.size * total_array_length;
1367}
1368
1369uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1370 int array_indices_size = static_cast<int>(array_indices.size());
1371 if (array_indices_size) {
1372 uint32_t array_index = 0;
1373 uint32_t i = 0;
1374 for (const auto index : array_indices) {
1375 array_index += (data.array_block_size[i] * index);
1376 ++i;
1377 }
1378 offset += (array_index * data.size);
1379 }
1380 return offset;
1381}
1382
1383void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1384 int array_indices_size = static_cast<int>(array_indices.size());
1385 uint32_t block_memory_size = data.size;
1386 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1387 block_memory_size *= data.array_length_hierarchy[i];
1388 }
1389
1390 offset = UpdateOffset(offset, array_indices, data);
1391
1392 uint32_t end = offset + block_memory_size;
1393 auto used_bytes = data.GetUsedbytes();
1394 if (used_bytes->size() < end) {
1395 used_bytes->resize(end, 0);
1396 }
1397 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1398}
1399
1400void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1401 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1402 if (access_chain_word_index < access_chain_it.len()) {
1403 if (data.array_length_hierarchy.size() > array_indices.size()) {
1404 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1405 ++access_chain_word_index;
1406
1407 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1408 array_indices.emplace_back(def_it.word(3));
1409 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1410 } else {
1411 // If it is a variable, set the all array is used.
1412 if (access_chain_word_index < access_chain_it.len()) {
1413 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1414 for (uint32_t i = 0; i < array_length; ++i) {
1415 auto array_indices2 = array_indices;
1416 array_indices2.emplace_back(i);
1417 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1418 }
1419 } else {
1420 SetUsedBytes(offset, array_indices, data);
1421 }
1422 }
1423 } else {
1424 offset = UpdateOffset(offset, array_indices, data);
1425 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1426 }
1427 } else {
1428 SetUsedBytes(offset, array_indices, data);
1429 }
1430}
1431
1432void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1433 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1434 std::vector<uint32_t> array_indices_emptry;
1435
1436 if (access_chain_word_index < access_chain_it.len()) {
1437 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1438 ++access_chain_word_index;
1439
1440 auto data1 = data.struct_members[strcut_member_index];
1441 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1442 }
1443}
1444
1445void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1446 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1447 for (const auto &func_set : function_set_list) {
1448 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1449 for (auto it = range.first; it != range.second; ++it) {
1450 auto access_chain = src.at(it->second);
1451 if (access_chain.word(3) == variable_id) {
1452 RunUsedStruct(src, 0, 4, access_chain, data);
1453 }
1454 }
1455 }
1456}
1457
1458void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1459 for (auto &entrypoint : src.entry_points) {
1460 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1461 for (auto it = range.first; it != range.second; ++it) {
1462 const auto def_insn = src.at(it->second);
1463
1464 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1465 spirv_inst_iter type = src.get_def(def_insn.word(1));
1466 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1467 std::vector<uint32_t> offsets;
1468
1469 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1470 auto member_decorate = src.at(it2->second);
1471 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1472 offsets.emplace_back(member_decorate.offset());
1473 }
1474 }
1475 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1476 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1477 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1478 entrypoint.second.push_constant_used_in_shader);
1479 }
1480 }
1481 }
1482}
1483
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001484layer_data::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
locke-lunarg96dc9632020-06-10 17:22:18 -06001485 const VkPipelineShaderStageCreateInfo &stage_info) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001486 layer_data::unordered_set<uint32_t> location_list;
locke-lunarg96dc9632020-06-10 17:22:18 -06001487 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1488 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1489 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001490 layer_data::unordered_set<unsigned> store_members;
1491 layer_data::unordered_map<unsigned, unsigned> accesschain_members;
locke-lunarg96dc9632020-06-10 17:22:18 -06001492
1493 for (auto insn : module) {
1494 switch (insn.opcode()) {
1495 case spv::OpStore:
1496 case spv::OpAtomicStore: {
1497 store_members.insert(insn.word(1)); // object id or AccessChain id
1498 break;
1499 }
1500 case spv::OpAccessChain: {
1501 // 2: AccessChain id, 3: object id
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001502 if (insn.word(3)) accesschain_members.emplace(insn.word(2), insn.word(3));
locke-lunarg96dc9632020-06-10 17:22:18 -06001503 break;
1504 }
1505 default:
1506 break;
1507 }
1508 }
1509 if (store_members.empty()) {
1510 return location_list;
1511 }
1512 for (auto output : outputs) {
1513 auto store_it = store_members.find(output.second.id);
1514 if (store_it != store_members.end()) {
1515 location_list.insert(output.first.first);
1516 store_members.erase(store_it);
1517 continue;
1518 }
1519 store_it = store_members.begin();
1520 while (store_it != store_members.end()) {
1521 auto accesschain_it = accesschain_members.find(*store_it);
1522 if (accesschain_it == accesschain_members.end()) {
1523 ++store_it;
1524 continue;
1525 }
1526 if (accesschain_it->second == output.second.id) {
1527 location_list.insert(output.first.first);
1528 store_members.erase(store_it);
1529 accesschain_members.erase(accesschain_it);
1530 break;
1531 }
1532 ++store_it;
1533 }
1534 }
1535 return location_list;
1536}
1537
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001538bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001539 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1540 // be specified only once.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001541 layer_data::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
Chris Forbes47567b72017-06-09 12:09:45 -07001542 bool skip = false;
1543
1544 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1545 auto desc = &vi->pVertexBindingDescriptions[i];
1546 auto &binding = bindings[desc->binding];
1547 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001548 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001549 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1550 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001551 } else {
1552 binding = desc;
1553 }
1554 }
1555
1556 return skip;
1557}
1558
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001559bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1560 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001561 bool skip = false;
1562
Petr Kraus25810d02019-08-27 17:41:15 +02001563 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001564
1565 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001566 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001567 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001568 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1569 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1570 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001571 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1572 }
1573 }
1574 }
1575
Petr Kraus25810d02019-08-27 17:41:15 +02001576 struct AttribInputPair {
1577 const VkVertexInputAttributeDescription *attrib = nullptr;
1578 const interface_var *input = nullptr;
1579 };
1580 std::map<uint32_t, AttribInputPair> location_map;
1581 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1582 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001583
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001584 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001585 const auto location = location_it.first;
1586 const auto attrib = location_it.second.attrib;
1587 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001588
Petr Kraus25810d02019-08-27 17:41:15 +02001589 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001590 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1591 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001592 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001593 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1594 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001595 } else if (attrib && input) {
1596 const auto attrib_type = GetFormatType(attrib->format);
1597 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001598
1599 // Type checking
1600 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001601 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1602 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1603 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001604 }
Petr Kraus25810d02019-08-27 17:41:15 +02001605 } else { // !attrib && !input
1606 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001607 }
1608 }
1609
1610 return skip;
1611}
1612
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001613bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1614 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001615 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001616
Petr Kraus25810d02019-08-27 17:41:15 +02001617 const auto rpci = pipeline->rp_state->createInfo.ptr();
1618
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001619 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001620 const VkAttachmentReference2 *reference = nullptr;
1621 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001622 const interface_var *output = nullptr;
1623 };
1624 std::map<uint32_t, Attachment> location_map;
1625
Petr Kraus25810d02019-08-27 17:41:15 +02001626 const auto subpass = rpci->pSubpasses[subpass_index];
1627 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001628 auto const &reference = subpass.pColorAttachments[i];
1629 location_map[i].reference = &reference;
1630 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1631 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1632 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001633 }
1634 }
1635
Chris Forbes47567b72017-06-09 12:09:45 -07001636 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1637
Petr Kraus25810d02019-08-27 17:41:15 +02001638 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001639 for (const auto &output_it : outputs) {
1640 auto const location = output_it.first.first;
1641 location_map[location].output = &output_it.second;
1642 }
Chris Forbes47567b72017-06-09 12:09:45 -07001643
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001644 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1645 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001646
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001647 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001648 const auto reference = location_it.second.reference;
1649 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1650 continue;
1651 }
1652
Petr Kraus25810d02019-08-27 17:41:15 +02001653 const auto location = location_it.first;
1654 const auto attachment = location_it.second.attachment;
1655 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001656 if (attachment && !output) {
1657 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001658 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1659 "Attachment %" PRIu32
1660 " not written by fragment shader; undefined values will be written to attachment",
1661 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001662 }
1663 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001664 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001665 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1666 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001667 }
Petr Kraus25810d02019-08-27 17:41:15 +02001668 } else if (attachment && output) {
1669 const auto attachment_type = GetFormatType(attachment->format);
1670 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001671
1672 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001673 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001674 skip |=
1675 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1676 "Attachment %" PRIu32
1677 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1678 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001679 }
Petr Kraus25810d02019-08-27 17:41:15 +02001680 } else { // !attachment && !output
1681 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001682 }
1683 }
1684
Petr Kraus25810d02019-08-27 17:41:15 +02001685 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001686 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1687 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1688 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001689 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1690 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001691 }
1692
Chris Forbes47567b72017-06-09 12:09:45 -07001693 return skip;
1694}
1695
Tobias Hector6663c9b2020-11-05 10:18:02 +00001696// 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 -06001697// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001698static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001699 auto type = builtin_instr.opcode();
1700 uint32_t target_id = builtin_instr.word(1);
1701 bool init_complete = false;
1702
1703 if (type == spv::OpMemberDecorate) {
1704 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1705 auto insn = entrypoint;
1706 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1707 switch (insn.opcode()) {
1708 case spv::OpTypePointer:
1709 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1710 target_id = insn.word(1);
1711 }
1712 break;
1713 case spv::OpVariable:
1714 if (insn.word(1) == target_id) {
1715 target_id = insn.word(2);
1716 init_complete = true;
1717 }
1718 break;
1719 }
1720 insn++;
1721 }
1722 }
1723
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001724 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1725
1726 bool found_write = false;
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001727 layer_data::unordered_set<uint32_t> worklist;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001728 worklist.insert(entrypoint.word(2));
1729
1730 // Follow instructions in call graph looking for writes to target
1731 while (!worklist.empty() && !found_write) {
1732 auto id_iter = worklist.begin();
1733 auto id = *id_iter;
1734 worklist.erase(id_iter);
1735
1736 auto insn = src->get_def(id);
1737 if (insn == src->end()) {
1738 continue;
1739 }
1740
1741 if (insn.opcode() == spv::OpFunction) {
1742 // Scan body of function looking for other function calls or items in our ID chain
1743 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1744 switch (insn.opcode()) {
1745 case spv::OpAccessChain:
1746 if (insn.word(3) == target_id) {
1747 if (type == spv::OpMemberDecorate) {
1748 auto value = GetConstantValue(src, insn.word(4));
1749 if (value == builtin_instr.word(2)) {
1750 target_id = insn.word(2);
1751 }
1752 } else {
1753 target_id = insn.word(2);
1754 }
1755 }
1756 break;
1757 case spv::OpStore:
1758 if (insn.word(1) == target_id) {
1759 found_write = true;
1760 }
1761 break;
1762 case spv::OpFunctionCall:
1763 worklist.insert(insn.word(3));
1764 break;
1765 }
1766 }
1767 }
1768 }
1769 return found_write;
1770}
1771
Chris Forbes47567b72017-06-09 12:09:45 -07001772// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1773// important for identifying the set of shader resources actually used by an entrypoint, for example.
1774// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1775// - NOT the shader input/output interfaces.
1776//
1777// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1778// converting parts of this to be generated from the machine-readable spec instead.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001779layer_data::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
1780 layer_data::unordered_set<uint32_t> ids;
1781 layer_data::unordered_set<uint32_t> worklist;
Chris Forbes47567b72017-06-09 12:09:45 -07001782 worklist.insert(entrypoint.word(2));
1783
1784 while (!worklist.empty()) {
1785 auto id_iter = worklist.begin();
1786 auto id = *id_iter;
1787 worklist.erase(id_iter);
1788
1789 auto insn = src->get_def(id);
1790 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001791 // 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 -07001792 // that we may not care about.
1793 continue;
1794 }
1795
1796 // Try to add to the output set
1797 if (!ids.insert(id).second) {
1798 continue; // If we already saw this id, we don't want to walk it again.
1799 }
1800
1801 switch (insn.opcode()) {
1802 case spv::OpFunction:
1803 // Scan whole body of the function, enlisting anything interesting
1804 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1805 switch (insn.opcode()) {
1806 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001807 worklist.insert(insn.word(3)); // ptr
1808 break;
1809 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001810 worklist.insert(insn.word(1)); // ptr
1811 break;
1812 case spv::OpAccessChain:
1813 case spv::OpInBoundsAccessChain:
1814 worklist.insert(insn.word(3)); // base ptr
1815 break;
1816 case spv::OpSampledImage:
1817 case spv::OpImageSampleImplicitLod:
1818 case spv::OpImageSampleExplicitLod:
1819 case spv::OpImageSampleDrefImplicitLod:
1820 case spv::OpImageSampleDrefExplicitLod:
1821 case spv::OpImageSampleProjImplicitLod:
1822 case spv::OpImageSampleProjExplicitLod:
1823 case spv::OpImageSampleProjDrefImplicitLod:
1824 case spv::OpImageSampleProjDrefExplicitLod:
1825 case spv::OpImageFetch:
1826 case spv::OpImageGather:
1827 case spv::OpImageDrefGather:
1828 case spv::OpImageRead:
1829 case spv::OpImage:
1830 case spv::OpImageQueryFormat:
1831 case spv::OpImageQueryOrder:
1832 case spv::OpImageQuerySizeLod:
1833 case spv::OpImageQuerySize:
1834 case spv::OpImageQueryLod:
1835 case spv::OpImageQueryLevels:
1836 case spv::OpImageQuerySamples:
1837 case spv::OpImageSparseSampleImplicitLod:
1838 case spv::OpImageSparseSampleExplicitLod:
1839 case spv::OpImageSparseSampleDrefImplicitLod:
1840 case spv::OpImageSparseSampleDrefExplicitLod:
1841 case spv::OpImageSparseSampleProjImplicitLod:
1842 case spv::OpImageSparseSampleProjExplicitLod:
1843 case spv::OpImageSparseSampleProjDrefImplicitLod:
1844 case spv::OpImageSparseSampleProjDrefExplicitLod:
1845 case spv::OpImageSparseFetch:
1846 case spv::OpImageSparseGather:
1847 case spv::OpImageSparseDrefGather:
1848 case spv::OpImageTexelPointer:
1849 worklist.insert(insn.word(3)); // Image or sampled image
1850 break;
1851 case spv::OpImageWrite:
1852 worklist.insert(insn.word(1)); // Image -- different operand order to above
1853 break;
1854 case spv::OpFunctionCall:
1855 for (uint32_t i = 3; i < insn.len(); i++) {
1856 worklist.insert(insn.word(i)); // fn itself, and all args
1857 }
1858 break;
1859
1860 case spv::OpExtInst:
1861 for (uint32_t i = 5; i < insn.len(); i++) {
1862 worklist.insert(insn.word(i)); // Operands to ext inst
1863 }
1864 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001865
1866 default: {
1867 if (AtomicOperation(insn.opcode())) {
1868 if (insn.opcode() == spv::OpAtomicStore) {
1869 worklist.insert(insn.word(1)); // ptr
1870 } else {
1871 worklist.insert(insn.word(3)); // ptr
1872 }
1873 }
1874 break;
1875 }
Chris Forbes47567b72017-06-09 12:09:45 -07001876 }
1877 }
1878 break;
1879 }
1880 }
1881
1882 return ids;
1883}
1884
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001885PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1886 const shader_struct_member &push_constant_used_in_shader,
1887 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001888 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001889 const auto used_bytes_size = used_bytes->size();
1890 if (used_bytes_size == 0) return PC_Byte_Updated;
1891
1892 const auto push_constant_data_update_size = push_constant_data_update.size();
1893 const auto *data = push_constant_data_update.data();
1894 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1895 if (used_bytes_size <= push_constant_data_update_size) {
1896 return PC_Byte_Updated;
1897 }
1898 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1899
1900 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1901 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1902 return PC_Byte_Updated;
1903 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001904 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001905
locke-lunargde3f0fa2020-09-10 11:55:31 -06001906 uint32_t i = 0;
1907 for (const auto used : *used_bytes) {
1908 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001909 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001910 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001911 return PC_Byte_Not_Set;
1912 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001913 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001914 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001915 }
1916 }
1917 ++i;
1918 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001919 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001920}
1921
1922bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1923 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001924 bool skip = false;
sfricke-samsung5c65b372021-03-25 05:39:57 -07001925 // Temp workaround to prevent false positive errors
1926 // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/2450
1927 if (src->multiple_entry_points) {
1928 return skip;
1929 }
1930
Chris Forbes47567b72017-06-09 12:09:45 -07001931 // 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 -06001932 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1933 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1934 return skip;
1935 }
1936 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001937
locke-lunargde3f0fa2020-09-10 11:55:31 -06001938 bool found_stage = false;
1939 for (auto const &range : *push_constant_ranges) {
1940 if (range.stageFlags & pStage->stage) {
1941 found_stage = true;
1942 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001943 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001944 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001945 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001946 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001947 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001948 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001949 const auto ret =
1950 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001951
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001952 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001953 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1954 LogObjectList objlist(src->vk_shader_module);
1955 objlist.add(pipeline.pipeline_layout->layout);
1956 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1957 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1958 string_VkShaderStageFlags(pStage->stage).c_str(),
1959 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1960 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001961 }
1962 }
1963 }
1964
locke-lunargde3f0fa2020-09-10 11:55:31 -06001965 if (!found_stage) {
1966 LogObjectList objlist(src->vk_shader_module);
1967 objlist.add(pipeline.pipeline_layout->layout);
1968 skip |= LogError(
1969 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1970 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1971 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001972 }
Chris Forbes47567b72017-06-09 12:09:45 -07001973 return skip;
1974}
1975
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001976bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const layer_data::unordered_set<uint32_t> &accessible_ids,
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001977 VkShaderStageFlagBits stage) const {
1978 bool skip = false;
1979
1980 // Currently all builtin tested are only found in fragment shaders
1981 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1982 return skip;
1983 }
1984
1985 for (const auto id : accessible_ids) {
1986 auto insn = src->get_def(id);
1987 const decoration_set decorations = src->get_decorations(insn.word(2));
1988
1989 // Built-ins are obtained from OpVariable
1990 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1991 auto type_pointer = src->get_def(insn.word(1));
1992 assert(type_pointer.opcode() == spv::OpTypePointer);
1993
1994 auto type = src->get_def(type_pointer.word(3));
1995 if (type.opcode() == spv::OpTypeArray) {
1996 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1997
1998 switch (decorations.builtin) {
1999 case spv::BuiltInSampleMask:
2000 // Handles both the input and output sampleMask
2001 if (length > phys_dev_props.limits.maxSampleMaskWords) {
2002 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
2003 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
2004 "maxSampleMaskWords of %u in %s.",
2005 length, phys_dev_props.limits.maxSampleMaskWords,
2006 report_data->FormatHandle(src->vk_shader_module).c_str());
2007 }
2008 break;
2009 }
2010 }
2011 }
2012 }
2013
2014 return skip;
2015}
2016
Chris Forbes47567b72017-06-09 12:09:45 -07002017// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002018bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002019 bool skip = false;
2020
2021 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2022
2023 if (spec) {
2024 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002025 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002026 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
2027 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2028 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2029 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2030 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002031
2032 continue;
2033 }
Chris Forbes47567b72017-06-09 12:09:45 -07002034 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002035 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2036 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2037 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2038 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2039 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002040 }
2041 }
2042 }
2043
2044 return skip;
2045}
2046
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002047// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002048static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2049 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002050 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002051 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002052 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002053 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002054
2055 // 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 -05002056 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2057 if (type.opcode() == spv::OpTypeRuntimeArray) {
2058 descriptor_count = 0;
2059 type = module->get_def(type.word(2));
2060 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002061 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002062 type = module->get_def(type.word(2));
2063 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002064 if (type.word(2) == spv::StorageClassStorageBuffer) {
2065 is_storage_buffer = true;
2066 }
Chris Forbes47567b72017-06-09 12:09:45 -07002067 type = module->get_def(type.word(3));
2068 }
2069 }
2070
2071 switch (type.opcode()) {
2072 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -08002073 for (auto insn : module->decoration_inst) {
2074 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002075 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002076 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002077 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2078 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2079 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002080 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002081 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2082 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2083 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2084 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002085 }
Chris Forbes47567b72017-06-09 12:09:45 -07002086 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002087 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2088 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2089 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002090 }
2091 }
2092 }
2093
2094 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002095 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002096 }
2097
2098 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002099 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2100 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2101 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002102
Chris Forbes73c00bf2018-06-22 16:28:06 -07002103 case spv::OpTypeSampledImage: {
2104 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2105 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2106 auto image_type = module->get_def(type.word(2));
2107 auto dim = image_type.word(3);
2108 auto sampled = image_type.word(7);
2109 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002110 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2111 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002112 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002113 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002114 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2115 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002116
2117 case spv::OpTypeImage: {
2118 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2119 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2120 auto dim = type.word(3);
2121 auto sampled = type.word(7);
2122
2123 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002124 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2125 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002126 } else if (dim == spv::DimBuffer) {
2127 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002128 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2129 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002130 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002131 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2132 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002133 }
2134 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002135 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2136 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2137 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002138 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002139 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2140 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002141 }
2142 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002143 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002144 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2145 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002146 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002147
2148 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2149 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002150 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002151 }
2152}
2153
Jeff Bolze54ae892018-09-08 12:16:29 -05002154static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002155 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002156 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2157 if (ss.tellp()) ss << ", ";
2158 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002159 }
2160 return ss.str();
2161}
2162
sfricke-samsung0065ce02020-12-03 22:46:37 -08002163bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002164 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002165 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 -05002166 return true;
2167 }
2168 }
2169
2170 return false;
2171}
2172
sfricke-samsung0065ce02020-12-03 22:46:37 -08002173bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002174 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002175 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002176 return true;
2177 }
2178 }
2179
2180 return false;
2181}
2182
locke-lunarg63e4daf2020-08-17 17:53:25 -06002183bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2184 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002185 bool skip = false;
2186
locke-lunarg63e4daf2020-08-17 17:53:25 -06002187 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002188 switch (stage) {
2189 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002190 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2191 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2192 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2193 case VK_SHADER_STAGE_MISS_BIT_NV:
2194 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2195 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2196 case VK_SHADER_STAGE_TASK_BIT_NV:
2197 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002198 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002199 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002200 break;
2201 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002202 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2203 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002204 break;
2205 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002206 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2207 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002208 break;
2209 }
2210 }
2211
Chris Forbes47567b72017-06-09 12:09:45 -07002212 return skip;
2213}
2214
sfricke-samsung94167ca2021-02-26 04:14:59 -08002215bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2216 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002217 bool skip = false;
2218
sfricke-samsung94167ca2021-02-26 04:14:59 -08002219 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2220 if (GroupOperation(insn.opcode()) == true) {
2221 // Check the quad operations.
2222 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2223 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2224 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2225 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2226 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002227 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002228 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002229
sfricke-samsung94167ca2021-02-26 04:14:59 -08002230 uint32_t scope_type = spv::ScopeMax;
2231 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2232 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2233 scope_type = spv::ScopeSubgroup;
2234 } else {
2235 // "All <id> used for Scope <id> must be of an OpConstant"
2236 auto scope_id = module->get_def(insn.word(3));
2237 scope_type = scope_id.word(3);
2238 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002239
sfricke-samsung94167ca2021-02-26 04:14:59 -08002240 if (scope_type == spv::ScopeSubgroup) {
2241 // "Group operations with subgroup scope" must have stage support
2242 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2243 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002244 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002245 }
2246
2247 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2248 auto type = module->get_def(insn.word(1));
2249
2250 if (type.opcode() == spv::OpTypeVector) {
2251 // Get the element type
2252 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002253 }
2254
sfricke-samsung94167ca2021-02-26 04:14:59 -08002255 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002256 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2257 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002258
sfricke-samsung0065ce02020-12-03 22:46:37 -08002259 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2260 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2261 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2262 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2263 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002264 }
2265 }
2266 }
Jeff Bolzee743412019-06-20 22:24:32 -05002267 }
2268
2269 return skip;
2270}
2271
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002272bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002273 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002274 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2275 pStage->stage == VK_SHADER_STAGE_ALL) {
2276 return false;
2277 }
2278
2279 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002280 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002281
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002282 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002283 struct Variable {
2284 uint32_t baseTypePtrID;
2285 uint32_t ID;
2286 uint32_t storageClass;
2287 };
2288 std::vector<Variable> variables;
2289
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002290 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002291 bool is_iso_lines = false;
2292 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002293
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002294 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002295
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002296 for (auto insn : *src) {
2297 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002298 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002299 case spv::OpDecorate:
2300 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002301 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002302 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002303 break;
2304 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002305 default:
2306 break;
2307 }
2308 break;
2309 // Find all input and output variables
2310 case spv::OpVariable: {
2311 Variable var = {};
2312 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002313 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2314 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002315 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002316 var.baseTypePtrID = insn.word(1);
2317 var.ID = insn.word(2);
2318 variables.push_back(var);
2319 }
2320 break;
2321 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002322 case spv::OpExecutionMode:
2323 if (insn.word(1) == entrypoint.word(2)) {
2324 switch (insn.word(2)) {
2325 default:
2326 break;
2327 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002328 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002329 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002330 case spv::ExecutionModeIsolines:
2331 is_iso_lines = true;
2332 break;
2333 case spv::ExecutionModePointMode:
2334 is_point_mode = true;
2335 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002336 }
2337 }
2338 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002339 default:
2340 break;
2341 }
2342 }
2343
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002344 bool strip_output_array_level =
2345 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2346 bool strip_input_array_level =
2347 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2348 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2349
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002350 uint32_t num_comp_in = 0, num_comp_out = 0;
2351 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002352
2353 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2354 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2355
2356 // Find max component location used for input variables.
2357 for (auto &var : inputs) {
2358 int location = var.first.first;
2359 int component = var.first.second;
2360 interface_var &iv = var.second;
2361
2362 // Only need to look at the first location, since we use the type's whole size
2363 if (iv.offset != 0) {
2364 continue;
2365 }
2366
2367 if (iv.is_patch) {
2368 continue;
2369 }
2370
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002371 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2372 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002373 }
2374
2375 // Find max component location used for output variables.
2376 for (auto &var : outputs) {
2377 int location = var.first.first;
2378 int component = var.first.second;
2379 interface_var &iv = var.second;
2380
2381 // Only need to look at the first location, since we use the type's whole size
2382 if (iv.offset != 0) {
2383 continue;
2384 }
2385
2386 if (iv.is_patch) {
2387 continue;
2388 }
2389
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002390 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2391 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002392 }
2393
2394 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2395 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002396 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002397 // Check if the variable is a patch. Patches can also be members of blocks,
2398 // but if they are then the top-level arrayness has already been stripped
2399 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002400 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002401
2402 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002403 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002404 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002405 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002406 }
2407 }
2408
2409 switch (pStage->stage) {
2410 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002411 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002412 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2413 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2414 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2415 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002416 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002417 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002418 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002419 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2420 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2421 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2422 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002423 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002424 break;
2425
2426 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002427 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002428 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2429 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2430 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2431 "components by %u components",
2432 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002433 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002434 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002435 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002436 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002437 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2438 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2439 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2440 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002441 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002442 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002443 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2444 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2445 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2446 "components by %u components",
2447 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002448 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002449 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002450 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002451 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002452 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2453 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2454 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2455 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002456 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002457 break;
2458
2459 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002460 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002461 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2462 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2463 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2464 "components by %u components",
2465 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002466 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002467 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002468 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002469 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002470 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2471 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2472 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2473 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002474 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002475 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002476 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2477 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2478 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2479 "components by %u components",
2480 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002481 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002482 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002483 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002484 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002485 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2486 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2487 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2488 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002489 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002490 // Portability validation
2491 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2492 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2493 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2494 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2495 " is using abstract patch type IsoLines, but this is not supported on this platform");
2496 }
2497 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2498 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2499 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2500 " is using abstract patch type PointMode, but this is not supported on this platform");
2501 }
2502 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002503 break;
2504
2505 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002506 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002507 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2508 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2509 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2510 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002511 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002512 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002513 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002514 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2515 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2516 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2517 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002518 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002519 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002520 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2521 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2522 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2523 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002524 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002525 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002526 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002527 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2528 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2529 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2530 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002531 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002532 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002533 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2534 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2535 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2536 "components by %u components",
2537 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002538 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002539 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002540 break;
2541
2542 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002543 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002544 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2545 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2546 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2547 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002548 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002549 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002550 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002551 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2552 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2553 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2554 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002555 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002556 break;
2557
Jeff Bolz148d94e2018-12-13 21:25:56 -06002558 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2559 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2560 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2561 case VK_SHADER_STAGE_MISS_BIT_NV:
2562 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2563 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2564 case VK_SHADER_STAGE_TASK_BIT_NV:
2565 case VK_SHADER_STAGE_MESH_BIT_NV:
2566 break;
2567
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002568 default:
2569 assert(false); // This should never happen
2570 }
2571 return skip;
2572}
2573
sfricke-samsungdc96f302020-03-18 20:42:10 -07002574bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2575 bool skip = false;
2576 uint32_t total_resources = 0;
2577
2578 // Only currently testing for graphics and compute pipelines
2579 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2580 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2581 return false;
2582 }
2583
2584 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2585 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2586 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2587 }
2588
2589 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2590 // input from CreatePipeline and CreatePipelineLayout level
2591 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2592 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2593 continue;
2594 }
2595
2596 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2597 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2598 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2599 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2600 // Check only descriptor types listed in maxPerStageResources description in spec
2601 switch (binding->descriptorType) {
2602 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2603 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2604 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2605 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2606 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2607 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2608 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2609 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2610 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2611 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2612 total_resources += binding->descriptorCount;
2613 break;
2614 default:
2615 break;
2616 }
2617 }
2618 }
2619 }
2620
2621 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2622 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2623 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2624 skip |= LogError(pipeline->pipeline, vuid,
2625 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2626 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2627 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2628 }
2629
2630 return skip;
2631}
2632
Jeff Bolze4356752019-03-07 11:23:46 -06002633// copy the specialization constant value into buf, if it is present
2634void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2635 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2636
2637 if (spec && spec_id < spec->mapEntryCount) {
2638 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2639 }
2640}
2641
2642// Fill in value with the constant or specialization constant value, if available.
2643// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002644static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002645 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
Jeff Bolze4356752019-03-07 11:23:46 -06002646 auto type_id = src->get_def(insn.word(1));
2647 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2648 return false;
2649 }
2650 switch (insn.opcode()) {
2651 case spv::OpSpecConstant:
2652 *value = insn.word(3);
2653 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2654 return true;
2655 case spv::OpConstant:
2656 *value = insn.word(3);
2657 return true;
2658 default:
2659 return false;
2660 }
2661}
2662
2663// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002664VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002665 switch (insn.opcode()) {
2666 case spv::OpTypeInt:
2667 switch (insn.word(2)) {
2668 case 8:
2669 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2670 case 16:
2671 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2672 case 32:
2673 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2674 case 64:
2675 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2676 default:
2677 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2678 }
2679 case spv::OpTypeFloat:
2680 switch (insn.word(2)) {
2681 case 16:
2682 return VK_COMPONENT_TYPE_FLOAT16_NV;
2683 case 32:
2684 return VK_COMPONENT_TYPE_FLOAT32_NV;
2685 case 64:
2686 return VK_COMPONENT_TYPE_FLOAT64_NV;
2687 default:
2688 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2689 }
2690 default:
2691 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2692 }
2693}
2694
2695// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2696// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002697bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002698 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002699 bool skip = false;
2700
2701 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002702 layer_data::unordered_map<uint32_t, uint32_t> id_to_spec_id;
Jeff Bolze4356752019-03-07 11:23:46 -06002703 // Map SPIR-V result ID to the ID of its type.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002704 layer_data::unordered_map<uint32_t, uint32_t> id_to_type_id;
Jeff Bolze4356752019-03-07 11:23:46 -06002705
2706 struct CoopMatType {
2707 uint32_t scope, rows, cols;
2708 VkComponentTypeNV component_type;
2709 bool all_constant;
2710
2711 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2712
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002713 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002714 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
Jeff Bolze4356752019-03-07 11:23:46 -06002715 spirv_inst_iter insn = src->get_def(id);
2716 uint32_t component_type_id = insn.word(2);
2717 uint32_t scope_id = insn.word(3);
2718 uint32_t rows_id = insn.word(4);
2719 uint32_t cols_id = insn.word(5);
2720 auto component_type_iter = src->get_def(component_type_id);
2721 auto scope_iter = src->get_def(scope_id);
2722 auto rows_iter = src->get_def(rows_id);
2723 auto cols_iter = src->get_def(cols_id);
2724
2725 all_constant = true;
2726 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2727 all_constant = false;
2728 }
2729 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2730 all_constant = false;
2731 }
2732 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2733 all_constant = false;
2734 }
2735 component_type = GetComponentType(component_type_iter, src);
2736 }
2737 };
2738
2739 bool seen_coopmat_capability = false;
2740
2741 for (auto insn : *src) {
2742 // Whitelist instructions whose result can be a cooperative matrix type, and
2743 // keep track of their types. It would be nice if SPIRV-Headers generated code
2744 // to identify which instructions have a result type and result id. Lacking that,
2745 // this whitelist is based on the set of instructions that
2746 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2747 switch (insn.opcode()) {
2748 case spv::OpLoad:
2749 case spv::OpCooperativeMatrixLoadNV:
2750 case spv::OpCooperativeMatrixMulAddNV:
2751 case spv::OpSNegate:
2752 case spv::OpFNegate:
2753 case spv::OpIAdd:
2754 case spv::OpFAdd:
2755 case spv::OpISub:
2756 case spv::OpFSub:
2757 case spv::OpFDiv:
2758 case spv::OpSDiv:
2759 case spv::OpUDiv:
2760 case spv::OpMatrixTimesScalar:
2761 case spv::OpConstantComposite:
2762 case spv::OpCompositeConstruct:
2763 case spv::OpConvertFToU:
2764 case spv::OpConvertFToS:
2765 case spv::OpConvertSToF:
2766 case spv::OpConvertUToF:
2767 case spv::OpUConvert:
2768 case spv::OpSConvert:
2769 case spv::OpFConvert:
2770 id_to_type_id[insn.word(2)] = insn.word(1);
2771 break;
2772 default:
2773 break;
2774 }
2775
2776 switch (insn.opcode()) {
2777 case spv::OpDecorate:
2778 if (insn.word(2) == spv::DecorationSpecId) {
2779 id_to_spec_id[insn.word(1)] = insn.word(3);
2780 }
2781 break;
2782 case spv::OpCapability:
2783 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2784 seen_coopmat_capability = true;
2785
2786 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002787 skip |= LogError(
2788 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2789 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2790 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002791 }
2792 }
2793 break;
2794 case spv::OpMemoryModel:
2795 // If the capability isn't enabled, don't bother with the rest of this function.
2796 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2797 if (!seen_coopmat_capability) {
2798 return skip;
2799 }
2800 break;
2801 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002802 CoopMatType m;
2803 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002804
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002805 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002806 // Validate that the type parameters are all supported for one of the
2807 // operands of a cooperative matrix property.
2808 bool valid = false;
2809 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002810 if (cooperative_matrix_properties[i].AType == m.component_type &&
2811 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2812 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002813 valid = true;
2814 break;
2815 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002816 if (cooperative_matrix_properties[i].BType == m.component_type &&
2817 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2818 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002819 valid = true;
2820 break;
2821 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002822 if (cooperative_matrix_properties[i].CType == m.component_type &&
2823 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2824 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002825 valid = true;
2826 break;
2827 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002828 if (cooperative_matrix_properties[i].DType == m.component_type &&
2829 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2830 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002831 valid = true;
2832 break;
2833 }
2834 }
2835 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002836 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2837 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2838 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002839 }
2840 }
2841 break;
2842 }
2843 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002844 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002845 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2846 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2847 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2848 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002849 // Couldn't find type of matrix
2850 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002851 break;
2852 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002853 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2854 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2855 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2856 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002857
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002858 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002859 // Validate that the type parameters are all supported for the same
2860 // cooperative matrix property.
2861 bool valid = false;
2862 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002863 if (cooperative_matrix_properties[i].AType == a.component_type &&
2864 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2865 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002866
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002867 cooperative_matrix_properties[i].BType == b.component_type &&
2868 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2869 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002870
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002871 cooperative_matrix_properties[i].CType == c.component_type &&
2872 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2873 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002874
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002875 cooperative_matrix_properties[i].DType == d.component_type &&
2876 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2877 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002878 valid = true;
2879 break;
2880 }
2881 }
2882 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002883 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2884 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2885 "VkCooperativeMatrixPropertiesNV",
2886 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002887 }
2888 }
2889 break;
2890 }
2891 default:
2892 break;
2893 }
2894 }
2895
2896 return skip;
2897}
2898
John Zulaufac4c6e12019-07-01 16:05:58 -06002899bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002900 auto entrypoint_id = entrypoint.word(2);
2901
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002902 // The first denorm execution mode encountered, along with its bit width.
2903 // Used to check if SeparateDenormSettings is respected.
2904 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002905
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002906 // The first rounding mode encountered, along with its bit width.
2907 // Used to check if SeparateRoundingModeSettings is respected.
2908 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002909
2910 bool skip = false;
2911
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002912 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002913 uint32_t invocations = 0;
2914
sfricke-samsung8a7341a2021-02-28 07:30:21 -08002915 auto it = src->execution_mode_inst.find(entrypoint_id);
2916 if (it != src->execution_mode_inst.end()) {
2917 for (auto insn : it->second) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002918 auto mode = insn.word(2);
2919 switch (mode) {
2920 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2921 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002922 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2923 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2924 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002925 skip |= LogError(
2926 device, kVUID_Core_Shader_FeatureNotEnabled,
2927 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2928 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002929 }
2930 break;
2931 }
2932
2933 case spv::ExecutionModeDenormPreserve: {
2934 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002935 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2936 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2937 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002938 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2939 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2940 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002941 }
2942
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002943 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2944 // Register the first denorm execution mode found
2945 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002946 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002947 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002948 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002949 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002950 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2951 "Shader uses different denorm execution modes for 16 and 64-bit but "
2952 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002953 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002954 }
2955 break;
2956
Mike Schuchardt2df08912020-12-15 16:28:09 -08002957 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002958 break;
2959
Mike Schuchardt2df08912020-12-15 16:28:09 -08002960 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002961 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2962 "Shader uses different denorm execution modes for different bit widths but "
2963 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002964 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002965 break;
2966
2967 default:
2968 break;
2969 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002970 }
2971 break;
2972 }
2973
2974 case spv::ExecutionModeDenormFlushToZero: {
2975 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002976 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2977 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2978 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002979 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2980 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2981 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002982 }
2983
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002984 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2985 // Register the first denorm execution mode found
2986 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002987 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002988 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002989 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002990 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002991 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2992 "Shader uses different denorm execution modes for 16 and 64-bit but "
2993 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002994 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002995 }
2996 break;
2997
Mike Schuchardt2df08912020-12-15 16:28:09 -08002998 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002999 break;
3000
Mike Schuchardt2df08912020-12-15 16:28:09 -08003001 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003002 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3003 "Shader uses different denorm execution modes for different bit widths but "
3004 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003005 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003006 break;
3007
3008 default:
3009 break;
3010 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003011 }
3012 break;
3013 }
3014
3015 case spv::ExecutionModeRoundingModeRTE: {
3016 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003017 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3018 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3019 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003020 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3021 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3022 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003023 }
3024
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003025 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3026 // Register the first rounding mode found
3027 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003028 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003029 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003030 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003031 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003032 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3033 "Shader uses different rounding modes for 16 and 64-bit but "
3034 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003035 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003036 }
3037 break;
3038
Mike Schuchardt2df08912020-12-15 16:28:09 -08003039 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003040 break;
3041
Mike Schuchardt2df08912020-12-15 16:28:09 -08003042 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003043 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3044 "Shader uses different rounding modes for different bit widths but "
3045 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003046 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003047 break;
3048
3049 default:
3050 break;
3051 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003052 }
3053 break;
3054 }
3055
3056 case spv::ExecutionModeRoundingModeRTZ: {
3057 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003058 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3059 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3060 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003061 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3062 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3063 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003064 }
3065
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003066 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3067 // Register the first rounding mode found
3068 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003069 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003070 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003071 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003072 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003073 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3074 "Shader uses different rounding modes for 16 and 64-bit but "
3075 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003076 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003077 }
3078 break;
3079
Mike Schuchardt2df08912020-12-15 16:28:09 -08003080 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003081 break;
3082
Mike Schuchardt2df08912020-12-15 16:28:09 -08003083 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003084 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3085 "Shader uses different rounding modes for different bit widths but "
3086 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003087 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003088 break;
3089
3090 default:
3091 break;
3092 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003093 }
3094 break;
3095 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003096
3097 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003098 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003099 break;
3100 }
3101
3102 case spv::ExecutionModeInvocations: {
3103 invocations = insn.word(3);
3104 break;
3105 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003106 }
3107 }
3108 }
3109
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003110 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003111 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003112 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3113 "Geometry shader entry point must have an OpExecutionMode instruction that "
3114 "specifies a maximum output vertex count that is greater than 0 and less "
3115 "than or equal to maxGeometryOutputVertices. "
3116 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003117 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003118 }
3119
3120 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003121 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3122 "Geometry shader entry point must have an OpExecutionMode instruction that "
3123 "specifies an invocation count that is greater than 0 and less "
3124 "than or equal to maxGeometryShaderInvocations. "
3125 "Invocations=%d, maxGeometryShaderInvocations=%d",
3126 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003127 }
3128 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003129 return skip;
3130}
3131
locke-lunargd9a069d2019-09-17 01:50:19 -06003132uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003133 auto type = module->get_def(type_id);
3134
3135 while (true) {
3136 switch (type.opcode()) {
3137 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003138 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003139 case spv::OpTypeSampledImage:
3140 type = module->get_def(type.word(2));
3141 break;
3142 case spv::OpTypePointer:
3143 type = module->get_def(type.word(3));
3144 break;
3145 case spv::OpTypeImage: {
3146 auto dim = type.word(3);
3147 auto arrayed = type.word(5);
3148 auto msaa = type.word(6);
3149
Chris Forbes74ba2232018-08-27 15:19:27 -07003150 uint32_t bits = 0;
3151 switch (GetFundamentalType(module, type.word(2))) {
3152 case FORMAT_TYPE_FLOAT:
3153 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3154 break;
3155 case FORMAT_TYPE_UINT:
3156 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3157 break;
3158 case FORMAT_TYPE_SINT:
3159 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3160 break;
3161 default:
3162 break;
3163 }
3164
Chris Forbes47567b72017-06-09 12:09:45 -07003165 switch (dim) {
3166 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003167 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3168 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003169 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003170 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3171 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3172 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003173 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003174 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3175 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003176 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003177 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3178 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003179 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003180 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3181 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003182 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003183 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003184 }
3185 }
3186 default:
3187 return 0;
3188 }
3189 }
3190}
3191
3192// For given pipelineLayout verify that the set_layout_node at slot.first
3193// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003194static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003195 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003196 if (!pipelineLayout) return nullptr;
3197
3198 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3199
3200 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3201}
3202
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003203int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3204 if (module == nullptr) return -1;
3205
3206 auto type = module->get_def(resource.type_id);
3207 while (true) {
3208 switch (type.opcode()) {
3209 case spv::OpTypeSampledImage:
3210 type = module->get_def(type.word(2));
3211 break;
3212 case spv::OpTypePointer:
3213 type = module->get_def(type.word(3));
3214 break;
3215 case spv::OpTypeImage:
3216 return type.word(3);
3217 default:
3218 return -1;
3219 }
3220 }
3221}
3222
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003223// Because the following is legal, need the entry point
3224// OpEntryPoint GLCompute %main "name_a"
3225// OpEntryPoint GLCompute %main "name_b"
3226bool FindLocalSize(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, uint32_t &local_size_x,
3227 uint32_t &local_size_y, uint32_t &local_size_z) {
3228 auto entrypoint_id = entrypoint.word(2);
3229 auto it = src->execution_mode_inst.find(entrypoint_id);
3230 if (it != src->execution_mode_inst.end()) {
3231 for (auto insn : it->second) {
3232 // Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
3233 // In the future if something like LocalSizeId is supported, the <id> will need to be checked also
3234 assert(insn.opcode() == spv::OpExecutionMode);
3235 if (insn.word(2) == spv::ExecutionModeLocalSize) {
3236 local_size_x = insn.word(3);
3237 local_size_y = insn.word(4);
3238 local_size_z = insn.word(5);
3239 return true;
Locke1ec6d952019-04-02 11:57:21 -06003240 }
3241 }
3242 }
3243 return false;
3244}
3245
locke-lunargd9a069d2019-09-17 01:50:19 -06003246void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003247 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003248 bool is_point_mode = false;
3249
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003250 auto it = src->execution_mode_inst.find(entrypoint_id);
3251 if (it != src->execution_mode_inst.end()) {
3252 for (auto insn : it->second) {
Chris Forbes0771b672018-03-22 21:13:46 -07003253 switch (insn.word(2)) {
3254 case spv::ExecutionModePointMode:
3255 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3256 is_point_mode = true;
3257 break;
3258
3259 case spv::ExecutionModeOutputPoints:
3260 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3261 break;
3262
3263 case spv::ExecutionModeIsolines:
3264 case spv::ExecutionModeOutputLineStrip:
3265 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3266 break;
3267
3268 case spv::ExecutionModeTriangles:
3269 case spv::ExecutionModeQuads:
3270 case spv::ExecutionModeOutputTriangleStrip:
3271 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3272 break;
3273 }
3274 }
3275 }
3276
3277 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3278}
3279
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003280// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3281// o If there is only a vertex shader : gl_PointSize must be written when using points
3282// o If there is a geometry or tessellation shader:
3283// - If shaderTessellationAndGeometryPointSize feature is enabled:
3284// * gl_PointSize must be written in the final geometry stage
3285// - If shaderTessellationAndGeometryPointSize feature is disabled:
3286// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003287bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003288 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003289 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3290 return false;
3291 }
3292
3293 bool pointsize_written = false;
3294 bool skip = false;
3295
3296 // Search for PointSize built-in decorations
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003297 for (auto set : src->builtin_decoration_list) {
3298 auto insn = src->at(set.offset);
3299 if (set.builtin == spv::BuiltInPointSize) {
3300 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
3301 if (pointsize_written) {
3302 break;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003303 }
3304 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003305 }
3306
3307 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003308 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003309 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003310 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3311 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3312 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003313 }
3314 } else if (!pointsize_written) {
3315 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003316 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3317 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3318 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003319 }
3320 return skip;
3321}
John Zulauf14c355b2019-06-27 16:09:37 -06003322
Tobias Hector6663c9b2020-11-05 10:18:02 +00003323bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3324 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3325 bool primitiverate_written = false;
3326 bool viewportindex_written = false;
3327 bool viewportmask_written = false;
3328 bool skip = false;
3329
3330 // Check if the primitive shading rate is written
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003331 for (auto set : src->builtin_decoration_list) {
3332 auto insn = src->at(set.offset);
3333 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3334 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3335 } else if (set.builtin == spv::BuiltInViewportIndex) {
3336 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3337 } else if (set.builtin == spv::BuiltInViewportMaskNV) {
3338 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003339 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003340 if (primitiverate_written && viewportindex_written && viewportmask_written) {
3341 break;
3342 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003343 }
3344
Tony-LunarGd44844c2021-01-22 13:24:37 -07003345 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3346 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003347 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3348 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003349 skip |= LogError(pipeline->pipeline,
3350 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3351 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3352 "multiple viewports "
3353 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3354 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003355 }
3356
3357 if (primitiverate_written && viewportindex_written) {
3358 skip |= LogError(pipeline->pipeline,
3359 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3360 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3361 "ViewportIndex built-ins,"
3362 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3363 string_VkShaderStageFlagBits(stage));
3364 }
3365
3366 if (primitiverate_written && viewportmask_written) {
3367 skip |= LogError(pipeline->pipeline,
3368 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3369 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3370 "ViewportMaskNV built-ins,"
3371 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3372 string_VkShaderStageFlagBits(stage));
3373 }
3374 }
3375 return skip;
3376}
3377
sfricke-samsung486a51e2021-01-02 00:10:15 -08003378// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003379bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003380 bool skip = false;
3381
sfricke-samsung94167ca2021-02-26 04:14:59 -08003382 switch (insn.opcode()) {
3383 case spv::OpReadClockKHR: {
3384 auto scope_id = module->get_def(insn.word(3));
3385 auto scope_type = scope_id.word(3);
3386 // if scope isn't Subgroup or Device, spirv-val will catch
3387 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3388 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3389 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3390 report_data->FormatHandle(module->vk_shader_module).c_str());
3391 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3392 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3393 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3394 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003395 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003396 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003397 }
3398 }
3399 return skip;
3400}
3401
John Zulauf14c355b2019-06-27 16:09:37 -06003402bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3403 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003404 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003405 bool skip = false;
3406
3407 // Check the module
3408 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003409 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3410 "%s does not contain valid spirv for stage %s.",
3411 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003412 }
3413
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003414 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3415 // specializations should be applied and validated.
3416 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3417 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3418 // Gather the specialization-constant values.
3419 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003420 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07003421 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map; // note: this must be std:: to work with spvtools
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003422 id_value_map.reserve(specialization_info->mapEntryCount);
3423 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3424 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003425
Jeremy Hayes521221d2020-01-15 16:48:49 -07003426 // Expect only scalar types.
3427 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3428 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3429 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003430 }
3431
3432 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003433 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003434 spvtools::Optimizer optimizer(spirv_environment);
3435 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3436 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003437 skip |= LogError(
3438 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003439 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3440 };
3441 optimizer.SetMessageConsumer(consumer);
3442 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3443 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3444 std::vector<uint32_t> specialized_spirv;
3445 auto const optimized =
3446 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3447 assert(optimized == true);
3448
3449 if (optimized) {
3450 spv_context ctx = spvContextCreate(spirv_environment);
3451 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3452 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003453 spvtools::ValidatorOptions options;
3454 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003455 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3456 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003457 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003458 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3459 report_data->FormatHandle(module->vk_shader_module).c_str(),
3460 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003461 }
3462
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003463 spvDiagnosticDestroy(diag);
3464 spvContextDestroy(ctx);
3465 }
3466 }
3467
John Zulauf14c355b2019-06-27 16:09:37 -06003468 // Check the entrypoint
3469 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003470 skip |=
3471 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3472 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003473 }
3474 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3475
3476 // Mark accessible ids
3477 auto &accessible_ids = stage_state.accessible_ids;
3478
Chris Forbes47567b72017-06-09 12:09:45 -07003479 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003480 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3481 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003482
sfricke-samsung94167ca2021-02-26 04:14:59 -08003483 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3484 // and mainly only checking the instruction in detail for a single operation
3485 for (auto insn : *module) {
3486 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3487 skip |= ValidatePropertiesAndFeatures(module, insn);
3488 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3489 }
3490
locke-lunarg63e4daf2020-08-17 17:53:25 -06003491 skip |=
3492 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003493 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003494 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003495 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003496 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003497 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003498 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003499 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003500 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003501 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
sfricke-samsungd093e522021-02-26 04:17:45 -08003502 if (enabled_features.cooperative_matrix_features.cooperativeMatrix) {
3503 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
3504 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003505 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3506 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3507 }
Chris Forbes47567b72017-06-09 12:09:45 -07003508
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003509 std::string vuid_layout_mismatch;
3510 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3511 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3512 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3513 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3514 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3515 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3516 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3517 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3518 }
3519
Chris Forbes47567b72017-06-09 12:09:45 -07003520 // Validate descriptor use
3521 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003522 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003523 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003524 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003525 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3526 std::set<uint32_t> descriptor_types =
3527 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003528
3529 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003530 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003531 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3532 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003533 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003534 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003535 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3536 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Tony-LunarGf563b362021-03-18 16:13:18 -06003537 } else if ((binding->descriptorType != VK_DESCRIPTOR_TYPE_MUTABLE_VALVE) &&
3538 (descriptor_types.find(binding->descriptorType) == descriptor_types.end())) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003539 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003540 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3541 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3542 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003543 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003544 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003545 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3546 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003547 }
3548 }
3549
3550 // Validate use of input attachments against subpass structure
3551 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003552 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003553
Petr Krause91f7a12017-12-14 20:57:36 +01003554 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003555 auto subpass = pipeline->graphicsPipelineCI.subpass;
3556
3557 for (auto use : input_attachment_uses) {
3558 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3559 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003560 ? input_attachments[use.first].attachment
3561 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003562
3563 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003564 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3565 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003566 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003567 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003568 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3569 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3570 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003571 }
3572 }
3573 }
Lockeaa8fdc02019-04-02 11:59:20 -06003574 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003575 skip |= ValidateComputeWorkGroupSizes(module, entrypoint);
Lockeaa8fdc02019-04-02 11:59:20 -06003576 }
Chris Forbes47567b72017-06-09 12:09:45 -07003577 return skip;
3578}
3579
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003580bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3581 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3582 spirv_inst_iter consumer_entrypoint,
3583 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003584 bool skip = false;
3585
3586 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003587 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3588 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003589
3590 auto a_it = outputs.begin();
3591 auto b_it = inputs.begin();
3592
3593 // Maps sorted by key (location); walk them together to find mismatches
3594 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3595 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3596 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3597 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3598 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3599
3600 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003601 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3602 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3603 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003604 a_it++;
3605 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003606 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3607 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3608 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003609 b_it++;
3610 } else {
3611 // subtleties of arrayed interfaces:
3612 // - if is_patch, then the member is not arrayed, even though the interface may be.
3613 // - if is_block_member, then the extra array level of an arrayed interface is not
3614 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003615 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3616 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3617 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003618 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3619 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3620 DescribeType(producer, a_it->second.type_id).c_str(),
3621 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003622 }
3623 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003624 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3625 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3626 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3627 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003628 }
3629 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
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: %s and %s stages differ in precision", a_first.first,
3632 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003633 }
3634 a_it++;
3635 b_it++;
3636 }
3637 }
3638
Ari Suonpaa696b3432019-03-11 14:02:57 +02003639 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3640 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3641 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3642
3643 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3644 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003645 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3646 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003647 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3648 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003649 } else {
3650 auto it_producer = builtins_producer.begin();
3651 auto it_consumer = builtins_consumer.begin();
3652 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3653 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003654 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3655 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3656 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003657 break;
3658 }
3659 it_producer++;
3660 it_consumer++;
3661 }
3662 }
3663 }
3664 }
3665
Chris Forbes47567b72017-06-09 12:09:45 -07003666 return skip;
3667}
3668
John Zulauf14c355b2019-06-27 16:09:37 -06003669static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003670 uint32_t stage_mask = 0;
3671 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3672 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3673 stage_mask |= pCreateInfo->pStages[i].stage;
3674 }
3675 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003676 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3677 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3678 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003679 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3680 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3681 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3682 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3683 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003684 }
3685 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003686 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003687}
3688
Chris Forbes47567b72017-06-09 12:09:45 -07003689// Validate that the shaders used by the given pipeline and store the active_slots
3690// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003691bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003692 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003693 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3694 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003695
John Zulauf14c355b2019-06-27 16:09:37 -06003696 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003697 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003698 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003699 bool skip = false;
3700
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003701 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003702
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003703 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3704 auto stage = &create_info->pStages[i];
3705 auto stage_id = GetShaderStageId(stage->stage);
3706 shaders[stage_id] = GetShaderModuleState(stage->module);
3707 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3708 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3709 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003710 }
3711
3712 // if the shader stages are no good individually, cross-stage validation is pointless.
3713 if (skip) return true;
3714
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003715 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003716
3717 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003718 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003719 }
3720
3721 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003722 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003723 }
3724
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003725 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3726 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003727
3728 while (!shaders[producer] && producer != fragment_stage) {
3729 producer++;
3730 consumer++;
3731 }
3732
3733 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3734 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003735 if (shaders[consumer]) {
3736 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003737 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3738 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003739 }
Chris Forbes47567b72017-06-09 12:09:45 -07003740
3741 producer = consumer;
3742 }
3743 }
3744
3745 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003746 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003747 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003748 }
3749
3750 return skip;
3751}
3752
Tony-LunarGb2ded512021-02-02 16:03:30 -07003753void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3754 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3755
3756 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3757 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3758 return;
3759 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003760
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003761 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3762 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003763 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003764
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003765 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3766 auto stage = &create_info->pStages[i];
3767 auto stage_id = GetShaderStageId(stage->stage);
3768 shaders[stage_id] = GetShaderModuleState(stage->module);
3769 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003770
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003771 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3772 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003773 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003774
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003775 for (auto set : shaders[stage_id]->builtin_decoration_list) {
3776 auto insn = shaders[stage_id]->at(set.offset);
3777 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3778 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003779 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003780 if (primitiverate_written) {
3781 break;
3782 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003783 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003784
Tony-LunarGb2ded512021-02-02 16:03:30 -07003785 if (primitiverate_written) {
3786 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3787 }
3788 }
3789 }
3790}
3791
3792bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3793 const char *caller, const DrawDispatchVuid &vuid) const {
3794 auto create_info = pipeline->graphicsPipelineCI.ptr();
3795 bool skip = false;
3796
3797 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3798 auto stage = &create_info->pStages[i];
3799 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3800 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3801 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3802 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3803 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003804 skip |=
3805 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3806 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3807 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3808 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003809 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003810 }
3811 }
3812 }
3813 }
3814
3815 return skip;
3816}
3817
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003818bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003819 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003820
John Zulauf14c355b2019-06-27 16:09:37 -06003821 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3822 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003823
John Zulauf14c355b2019-06-27 16:09:37 -06003824 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003825}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003826
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003827uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3828 uint32_t total = 0;
3829
3830 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3831 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3832 if (stages[stage_index].stage == stageBit) {
3833 total++;
3834 }
3835 }
3836
3837 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3838 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3839 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3840 total += CalcShaderStageCount(library_pipeline, stageBit);
3841 }
3842 }
3843
3844 return total;
3845}
3846
sourav parmarcd5fb182020-07-17 12:58:44 -07003847bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003848 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003849
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003850 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003851 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3852 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3853 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3854 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3855 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3856 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3857 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003858 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003859 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3860 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003861 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003862 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003863 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003864 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3865 skip |= LogError(
3866 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3867 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3868 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003869 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003870 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3871 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003872 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3873 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003874 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003875 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003876 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3877 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3878 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3879 "member must have been created with values of the maxPipelineRayPayloadSize and "
3880 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3881 }
3882 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003883 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003884 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3885 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3886 "vkCreateRayTracingPipelinesKHR: If flags includes "
3887 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3888 "the pLibraries member of libraries must have been created with the "
3889 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3890 }
sourav parmar83c31b12020-05-06 12:30:54 -07003891 }
3892 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003893 } else {
3894 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003895 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3896 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3897 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003898 pipeline->raytracingPipelineCI.maxRecursionDepth,
3899 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3900 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003901 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003902 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3903 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3904
John Zulaufe4474e72019-07-01 17:28:27 -06003905 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003906 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003907
John Zulaufe4474e72019-07-01 17:28:27 -06003908 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3909 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003910
John Zulaufe4474e72019-07-01 17:28:27 -06003911 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003912 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003913
3914 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3915 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3916 if (raygen_stages_count == 0) {
3917 skip |= LogError(
3918 device,
3919 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3920 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3921 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003922 }
3923
3924 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3925 const auto &group = groups[group_index];
3926
3927 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3928 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3929 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3930 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3931 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003932 skip |= LogError(device,
3933 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3934 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3935 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003936 }
3937 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3938 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003939 skip |= LogError(device,
3940 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3941 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3942 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003943 }
3944 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3945 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3946 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003947 skip |= LogError(device,
3948 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3949 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3950 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003951 }
3952 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3953 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003954 skip |= LogError(device,
3955 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3956 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3957 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003958 }
3959 }
3960
3961 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3962 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3963 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3964 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003965 skip |= LogError(device,
3966 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3967 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3968 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003969 }
3970 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3971 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3972 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003973 skip |= LogError(device,
3974 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3975 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3976 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003977 }
3978 }
John Zulaufe4474e72019-07-01 17:28:27 -06003979 }
3980 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003981}
3982
Dave Houltona9df0ce2018-02-07 10:51:23 -07003983uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003984
Dave Houltona9df0ce2018-02-07 10:51:23 -07003985static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003986 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003987 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003988 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003989 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003990 return nullptr;
3991}
3992
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003993bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003994 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003995 bool skip = false;
3996 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003997
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003998 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003999 return false;
4000 }
4001
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06004002 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07004003
4004 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004005 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
4006 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
4007 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004008 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004009 auto cache = GetValidationCacheInfo(pCreateInfo);
4010 uint32_t hash = 0;
4011 if (cache) {
4012 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004013 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004014 }
4015
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004016 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4017 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004018 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004019 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004020 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004021 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004022 spvtools::ValidatorOptions options;
4023 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004024 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004025 if (spv_valid != SPV_SUCCESS) {
4026 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004027 if (spv_valid == SPV_WARNING) {
4028 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4029 diag && diag->error ? diag->error : "(no error text)");
4030 } else {
4031 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4032 diag && diag->error ? diag->error : "(no error text)");
4033 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004034 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004035 } else {
4036 if (cache) {
4037 cache->Insert(hash);
4038 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004039 }
4040
4041 spvDiagnosticDestroy(diag);
4042 spvContextDestroy(ctx);
4043 }
4044
Chris Forbes4ae55b32017-06-09 14:42:56 -07004045 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004046}
4047
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004048bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader, const spirv_inst_iter &entrypoint) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004049 bool skip = false;
4050 uint32_t local_size_x = 0;
4051 uint32_t local_size_y = 0;
4052 uint32_t local_size_z = 0;
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004053 if (FindLocalSize(shader, entrypoint, local_size_x, local_size_y, local_size_z)) {
Lockeaa8fdc02019-04-02 11:59:20 -06004054 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004055 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4056 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4057 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4058 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004059 }
4060 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004061 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4062 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4063 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4064 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004065 }
4066 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004067 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4068 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4069 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4070 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004071 }
4072
4073 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4074 uint64_t invocations = local_size_x * local_size_y;
4075 // Prevent overflow.
4076 bool fail = false;
4077 if (invocations > UINT32_MAX || invocations > limit) {
4078 fail = true;
4079 }
4080 if (!fail) {
4081 invocations *= local_size_z;
4082 if (invocations > UINT32_MAX || invocations > limit) {
4083 fail = true;
4084 }
4085 }
4086 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004087 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4088 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4089 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4090 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4091 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004092 }
4093 }
4094 return skip;
4095}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004096
4097spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4098 if (api_version >= VK_API_VERSION_1_2) {
4099 return SPV_ENV_VULKAN_1_2;
4100 } else if (api_version >= VK_API_VERSION_1_1) {
4101 if (spirv_1_4) {
4102 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4103 } else {
4104 return SPV_ENV_VULKAN_1_1;
4105 }
4106 }
4107 return SPV_ENV_VULKAN_1_0;
4108}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004109
4110void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4111 spvtools::ValidatorOptions &options) {
4112 if (device_extensions.vk_khr_relaxed_block_layout) {
4113 options.SetRelaxBlockLayout(true);
4114 }
4115 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4116 options.SetUniformBufferStandardLayout(true);
4117 }
4118 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4119 options.SetScalarBlockLayout(true);
4120 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004121 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4122 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4123 options.SetWorkgroupScalarBlockLayout(true);
4124 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004125}