blob: 06eea8f9e55433554469f063e7e8f85e2e37fd25 [file] [log] [blame]
sfricke-samsung691299b2021-01-01 20:48:48 -08001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
4 * Copyright (C) 2015-2021 Google Inc.
Tobias Hector6663c9b2020-11-05 10:18:02 +00005 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Chris Forbes47567b72017-06-09 12:09:45 -07006 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * Author: Chris Forbes <chrisf@ijw.co.nz>
Dave Houlton51653902018-06-22 17:32:13 -060020 * Author: Dave Houlton <daveh@lunarg.com>
Tobias Hector6663c9b2020-11-05 10:18:02 +000021 * Author: Tobias Hector <tobias.hector@amd.com>
Chris Forbes47567b72017-06-09 12:09:45 -070022 */
23
Petr Kraus25810d02019-08-27 17:41:15 +020024#include "shader_validation.h"
25
Chris Forbes47567b72017-06-09 12:09:45 -070026#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020027#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020028#include <cinttypes>
Jeff Bolzf234bf82019-11-04 14:07:15 -060029#include <cmath>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070031#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020032#include <string>
33#include <unordered_map>
34#include <vector>
35
Mark Lobodzinski102687e2020-04-28 11:03:28 -060036#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070037#include "vk_loader_platform.h"
38#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070039#include "vk_layer_data.h"
40#include "vk_layer_extension_utils.h"
41#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070042#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070043#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020044
Chris Forbes4ae55b32017-06-09 14:42:56 -070045#include "spirv-tools/libspirv.h"
Chris Forbes9a61e082017-07-24 15:35:29 -070046#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070047
Chris Forbes8a6d8cb2019-02-14 14:33:08 -080048void decoration_set::add(uint32_t decoration, uint32_t value) {
49 switch (decoration) {
50 case spv::DecorationLocation:
51 flags |= location_bit;
52 location = value;
53 break;
54 case spv::DecorationPatch:
55 flags |= patch_bit;
56 break;
57 case spv::DecorationRelaxedPrecision:
58 flags |= relaxed_precision_bit;
59 break;
60 case spv::DecorationBlock:
61 flags |= block_bit;
62 break;
63 case spv::DecorationBufferBlock:
64 flags |= buffer_block_bit;
65 break;
66 case spv::DecorationComponent:
67 flags |= component_bit;
68 component = value;
69 break;
70 case spv::DecorationInputAttachmentIndex:
71 flags |= input_attachment_index_bit;
72 input_attachment_index = value;
73 break;
74 case spv::DecorationDescriptorSet:
75 flags |= descriptor_set_bit;
76 descriptor_set = value;
77 break;
78 case spv::DecorationBinding:
79 flags |= binding_bit;
80 binding = value;
81 break;
82 case spv::DecorationNonWritable:
83 flags |= nonwritable_bit;
84 break;
85 case spv::DecorationBuiltIn:
86 flags |= builtin_bit;
87 builtin = value;
88 break;
89 }
90}
91
Chris Forbes47567b72017-06-09 12:09:45 -070092enum FORMAT_TYPE {
93 FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
94 FORMAT_TYPE_SINT = 2,
95 FORMAT_TYPE_UINT = 4,
96};
97
98typedef std::pair<unsigned, unsigned> location_t;
99
Chris Forbes47567b72017-06-09 12:09:45 -0700100static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +0200101 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
102 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
103 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
104 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
105 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -0700106};
107
John Zulauf14c355b2019-06-27 16:09:37 -0600108unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
109
Chris Forbes47567b72017-06-09 12:09:45 -0700110// SPIRV utility functions
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600111void SHADER_MODULE_STATE::BuildDefIndex() {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600112 function_set func_set = {};
113 EntryPoint *entry_point = nullptr;
114
Chris Forbes47567b72017-06-09 12:09:45 -0700115 for (auto insn : *this) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600116 // offset is not 0, it means it's updated and the offset is in a Function.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700117 if (func_set.offset) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600118 func_set.op_lists.insert({insn.opcode(), insn.offset()});
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700119 } else if (entry_point) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600120 entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
121 }
122
Chris Forbes47567b72017-06-09 12:09:45 -0700123 switch (insn.opcode()) {
124 // Types
125 case spv::OpTypeVoid:
126 case spv::OpTypeBool:
127 case spv::OpTypeInt:
128 case spv::OpTypeFloat:
129 case spv::OpTypeVector:
130 case spv::OpTypeMatrix:
131 case spv::OpTypeImage:
132 case spv::OpTypeSampler:
133 case spv::OpTypeSampledImage:
134 case spv::OpTypeArray:
135 case spv::OpTypeRuntimeArray:
136 case spv::OpTypeStruct:
137 case spv::OpTypeOpaque:
138 case spv::OpTypePointer:
139 case spv::OpTypeFunction:
140 case spv::OpTypeEvent:
141 case spv::OpTypeDeviceEvent:
142 case spv::OpTypeReserveId:
143 case spv::OpTypeQueue:
144 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600145 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600146 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700147 def_index[insn.word(1)] = insn.offset();
148 break;
149
150 // Fixed constants
151 case spv::OpConstantTrue:
152 case spv::OpConstantFalse:
153 case spv::OpConstant:
154 case spv::OpConstantComposite:
155 case spv::OpConstantSampler:
156 case spv::OpConstantNull:
157 def_index[insn.word(2)] = insn.offset();
158 break;
159
160 // Specialization constants
161 case spv::OpSpecConstantTrue:
162 case spv::OpSpecConstantFalse:
163 case spv::OpSpecConstant:
164 case spv::OpSpecConstantComposite:
165 case spv::OpSpecConstantOp:
166 def_index[insn.word(2)] = insn.offset();
167 break;
168
169 // Variables
170 case spv::OpVariable:
171 def_index[insn.word(2)] = insn.offset();
172 break;
173
174 // Functions
175 case spv::OpFunction:
176 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600177 func_set.id = insn.word(2);
178 func_set.offset = insn.offset();
179 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700180 break;
181
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800182 // Decorations
183 case spv::OpDecorate: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700184 auto target_id = insn.word(1);
185 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
sfricke-samsung94d71a52021-02-26 05:25:43 -0800186 decoration_inst.push_back(insn);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800187 if (insn.word(2) == spv::DecorationBuiltIn) {
188 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(3)));
189 }
190
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800191 } break;
192 case spv::OpGroupDecorate: {
193 auto const &src = decorations[insn.word(1)];
194 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
195 } break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800196 case spv::OpMemberDecorate: {
197 member_decoration_inst.push_back(insn);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800198 if (insn.word(3) == spv::DecorationBuiltIn) {
199 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(4)));
200 }
sfricke-samsung94d71a52021-02-26 05:25:43 -0800201 } break;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800202
John Zulauf14c355b2019-06-27 16:09:37 -0600203 // Entry points ... add to the entrypoint table
204 case spv::OpEntryPoint: {
205 // 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 -0700206 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
John Zulauf14c355b2019-06-27 16:09:37 -0600207 auto execution_model = insn.word(1);
208 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600209 entry_points.emplace(entrypoint_name,
210 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
211
212 auto range = entry_points.equal_range(entrypoint_name);
213 for (auto it = range.first; it != range.second; ++it) {
214 if (it->second.offset == insn.offset()) {
215 entry_point = &(it->second);
216 break;
217 }
218 }
219 assert(entry_point != nullptr);
220 break;
221 }
222 case spv::OpFunctionEnd: {
223 assert(entry_point != nullptr);
224 func_set.length = insn.offset() - func_set.offset;
225 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600226 break;
227 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800228
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700229 // Copy operations
230 case spv::OpCopyLogical:
231 case spv::OpCopyObject: {
232 def_index[insn.word(2)] = insn.offset();
233 break;
234 }
235
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800236 // Execution Mode
237 case spv::OpExecutionMode: {
238 execution_mode_inst[insn.word(1)].push_back(insn);
239 } break;
240
Chris Forbes47567b72017-06-09 12:09:45 -0700241 default:
242 // We don't care about any other defs for now.
243 break;
244 }
245 }
246}
247
Jeff Bolz105d6492018-09-29 15:46:44 -0500248unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
249 switch (mode) {
250 case spv::ExecutionModelVertex:
251 return VK_SHADER_STAGE_VERTEX_BIT;
252 case spv::ExecutionModelTessellationControl:
253 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
254 case spv::ExecutionModelTessellationEvaluation:
255 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
256 case spv::ExecutionModelGeometry:
257 return VK_SHADER_STAGE_GEOMETRY_BIT;
258 case spv::ExecutionModelFragment:
259 return VK_SHADER_STAGE_FRAGMENT_BIT;
260 case spv::ExecutionModelGLCompute:
261 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600262 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700263 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600264 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700265 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600266 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700267 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600268 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700269 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600270 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700271 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600272 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700273 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500274 case spv::ExecutionModelTaskNV:
275 return VK_SHADER_STAGE_TASK_BIT_NV;
276 case spv::ExecutionModelMeshNV:
277 return VK_SHADER_STAGE_MESH_BIT_NV;
278 default:
279 return 0;
280 }
281}
282
locke-lunargde3f0fa2020-09-10 11:55:31 -0600283const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
284 VkShaderStageFlagBits stageBits) {
285 auto range = src->entry_points.equal_range(name);
286 for (auto it = range.first; it != range.second; ++it) {
287 if (it->second.stage == stageBits) {
288 return &(it->second);
289 }
290 }
291 return nullptr;
292}
293
locke-lunargd9a069d2019-09-17 01:50:19 -0600294spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600295 auto range = src->entry_points.equal_range(name);
296 for (auto it = range.first; it != range.second; ++it) {
297 if (it->second.stage == stageBits) {
298 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700299 }
300 }
Chris Forbes47567b72017-06-09 12:09:45 -0700301 return src->end();
302}
303
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600304static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700305 switch (sc) {
306 case spv::StorageClassInput:
307 return "input";
308 case spv::StorageClassOutput:
309 return "output";
310 case spv::StorageClassUniformConstant:
311 return "const uniform";
312 case spv::StorageClassUniform:
313 return "uniform";
314 case spv::StorageClassWorkgroup:
315 return "workgroup local";
316 case spv::StorageClassCrossWorkgroup:
317 return "workgroup global";
318 case spv::StorageClassPrivate:
319 return "private global";
320 case spv::StorageClassFunction:
321 return "function";
322 case spv::StorageClassGeneric:
323 return "generic";
324 case spv::StorageClassAtomicCounter:
325 return "atomic counter";
326 case spv::StorageClassImage:
327 return "image";
328 case spv::StorageClassPushConstant:
329 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800330 case spv::StorageClassStorageBuffer:
331 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700332 default:
333 return "unknown";
334 }
335}
336
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700337// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
338// Otherwise, returns src->end().
339spirv_inst_iter GetConstantDef(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700340 auto value = src->get_def(id);
Chris Forbes47567b72017-06-09 12:09:45 -0700341
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700342 // If id is a copy, see where it was copied from
343 if ((src->end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
344 id = value.word(3);
345 value = src->get_def(id);
346 }
347
348 if ((src->end() != value) && (value.opcode() == spv::OpConstant)) {
349 return value;
350 }
351 return src->end();
352}
353
354// Assumes itr points to an OpConstant instruction
355uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
356
357// Either returns the constant value described by the instruction at id, or 1
358uint32_t GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
359 auto value = GetConstantDef(src, id);
360
361 if (src->end() == value) {
Chris Forbes47567b72017-06-09 12:09:45 -0700362 // TODO: Either ensure that the specialization transform is already performed on a module we're
363 // considering here, OR -- specialize on the fly now.
364 return 1;
365 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -0700366 return GetConstantValue(value);
Chris Forbes47567b72017-06-09 12:09:45 -0700367}
368
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600369static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700370 auto insn = src->get_def(type);
371 assert(insn != src->end());
372
373 switch (insn.opcode()) {
374 case spv::OpTypeBool:
375 ss << "bool";
376 break;
377 case spv::OpTypeInt:
378 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
379 break;
380 case spv::OpTypeFloat:
381 ss << "float" << insn.word(2);
382 break;
383 case spv::OpTypeVector:
384 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600385 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700386 break;
387 case spv::OpTypeMatrix:
388 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600389 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700390 break;
391 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600392 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
393 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700394 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700395 case spv::OpTypeRuntimeArray:
396 ss << "runtime arr[] of ";
397 DescribeTypeInner(ss, src, insn.word(2));
398 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700399 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600400 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
401 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700402 break;
403 case spv::OpTypeStruct: {
404 ss << "struct of (";
405 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600406 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700407 if (i == insn.len() - 1) {
408 ss << ")";
409 } else {
410 ss << ", ";
411 }
412 }
413 break;
414 }
415 case spv::OpTypeSampler:
416 ss << "sampler";
417 break;
418 case spv::OpTypeSampledImage:
419 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600420 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700421 break;
422 case spv::OpTypeImage:
423 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
424 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600425 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500426 ss << "accelerationStruture";
427 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700428 default:
429 ss << "oddtype";
430 break;
431 }
432}
433
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600434static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700435 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600436 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700437 return ss.str();
438}
439
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600440static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700441 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
442 return type.word(2) < 64;
443}
444
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600445static 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 -0600446 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700447 // Walk two type trees together, and complain about differences
448 auto a_insn = a->get_def(a_type);
449 auto b_insn = b->get_def(b_type);
450 assert(a_insn != a->end());
451 assert(b_insn != b->end());
452
Chris Forbes062f1222018-08-21 15:34:15 -0700453 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
454
Chris Forbes47567b72017-06-09 12:09:45 -0700455 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600456 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700457 }
458
459 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
460 // 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 -0600461 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700462 }
463
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600464 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
465 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700466 }
467
468 if (a_insn.opcode() != b_insn.opcode()) {
469 return false;
470 }
471
472 if (a_insn.opcode() == spv::OpTypePointer) {
473 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600474 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700475 }
476
477 if (a_arrayed || b_arrayed) {
478 // If we havent resolved array-of-verts by here, we're not going to.
479 return false;
480 }
481
482 switch (a_insn.opcode()) {
483 case spv::OpTypeBool:
484 return true;
485 case spv::OpTypeInt:
486 // Match on width, signedness
487 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
488 case spv::OpTypeFloat:
489 // Match on width
490 return a_insn.word(2) == b_insn.word(2);
491 case spv::OpTypeVector:
492 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600493 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
494 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700495 return a_insn.word(3) >= b_insn.word(3);
496 } else {
497 return a_insn.word(3) == b_insn.word(3);
498 }
499 case spv::OpTypeMatrix:
500 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600501 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700502 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700503 case spv::OpTypeArray:
504 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
505 // 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 -0600506 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
507 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700508 case spv::OpTypeStruct:
509 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700510 {
511 if (a_insn.len() != b_insn.len()) {
512 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700513 }
Chris Forbes47567b72017-06-09 12:09:45 -0700514
Dave Houltona9df0ce2018-02-07 10:51:23 -0700515 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600516 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700517 return false;
518 }
519 }
520
521 return true;
522 }
Chris Forbes47567b72017-06-09 12:09:45 -0700523 default:
524 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
525 return false;
526 }
527}
528
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600529static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700530 auto insn = src->get_def(type);
531 assert(insn != src->end());
532
533 switch (insn.opcode()) {
534 case spv::OpTypePointer:
535 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
536 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600537 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700538 case spv::OpTypeArray:
539 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600540 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700541 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600542 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700543 }
544 case spv::OpTypeMatrix:
545 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600546 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700547 case spv::OpTypeVector: {
548 auto scalar_type = src->get_def(insn.word(2));
549 auto bit_width =
550 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
551
552 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
553 return (bit_width * insn.word(3) + 127) / 128;
554 }
555 default:
556 // Everything else is just 1.
557 return 1;
558
559 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
560 }
561}
562
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600563static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200564 auto insn = src->get_def(type);
565 assert(insn != src->end());
566
567 switch (insn.opcode()) {
568 case spv::OpTypePointer:
569 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
570 // pointers around.
571 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
572 case spv::OpTypeStruct: {
573 uint32_t sum = 0;
574 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
575 sum += GetComponentsConsumedByType(src, insn.word(i), false);
576 }
577 return sum;
578 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500579 case spv::OpTypeArray:
580 if (strip_array_level) {
581 return GetComponentsConsumedByType(src, insn.word(2), false);
582 } else {
583 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200584 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200585 case spv::OpTypeMatrix:
586 // Num locations is the dimension * element size
587 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
588 case spv::OpTypeVector: {
589 auto scalar_type = src->get_def(insn.word(2));
590 auto bit_width =
591 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
592 // One component is 32-bit
593 return (bit_width * insn.word(3) + 31) / 32;
594 }
595 case spv::OpTypeFloat: {
596 auto bit_width = insn.word(2);
597 return (bit_width + 31) / 32;
598 }
599 case spv::OpTypeInt: {
600 auto bit_width = insn.word(2);
601 return (bit_width + 31) / 32;
602 }
603 case spv::OpConstant:
604 return GetComponentsConsumedByType(src, insn.word(1), false);
605 default:
606 return 0;
607 }
608}
609
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600610static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700611 switch (format) {
612 case VK_FORMAT_R64G64B64A64_SFLOAT:
613 case VK_FORMAT_R64G64B64A64_SINT:
614 case VK_FORMAT_R64G64B64A64_UINT:
615 case VK_FORMAT_R64G64B64_SFLOAT:
616 case VK_FORMAT_R64G64B64_SINT:
617 case VK_FORMAT_R64G64B64_UINT:
618 return 2;
619 default:
620 return 1;
621 }
622}
623
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600624static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700625 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
626 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
627 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
628 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700629 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
630 return FORMAT_TYPE_FLOAT;
631}
632
633// 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 -0700634// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600635static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700636 auto insn = src->get_def(type);
637 assert(insn != src->end());
638
639 switch (insn.opcode()) {
640 case spv::OpTypeInt:
641 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
642 case spv::OpTypeFloat:
643 return FORMAT_TYPE_FLOAT;
644 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700645 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700646 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700647 case spv::OpTypeRuntimeArray:
648 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600649 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700650 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600651 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700652
653 default:
654 return 0;
655 }
656}
657
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600658static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700659 uint32_t bit_pos = uint32_t(u_ffs(stage));
660 return bit_pos - 1;
661}
662
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600663static 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 -0700664 while (true) {
665 if (def.opcode() == spv::OpTypePointer) {
666 def = src->get_def(def.word(3));
667 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
668 def = src->get_def(def.word(2));
669 is_array_of_verts = false;
670 } else if (def.opcode() == spv::OpTypeStruct) {
671 return def;
672 } else {
673 return src->end();
674 }
675 }
676}
677
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600678static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800679 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
680 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700681 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600682 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800683 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700684 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700685 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700686 }
687
688 std::unordered_map<unsigned, unsigned> member_components;
689 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700690 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700691
692 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800693 for (auto insn : src->member_decoration_inst) {
694 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700695 unsigned member_index = insn.word(2);
696
697 if (insn.word(3) == spv::DecorationComponent) {
698 unsigned component = insn.word(4);
699 member_components[member_index] = component;
700 }
701
702 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
703 member_relaxed_precision[member_index] = 1;
704 }
Chris Forbesa313d772017-06-13 13:59:41 -0700705
706 if (insn.word(3) == spv::DecorationPatch) {
707 member_patch[member_index] = 1;
708 }
Chris Forbes47567b72017-06-09 12:09:45 -0700709 }
710 }
711
Chris Forbesa313d772017-06-13 13:59:41 -0700712 // TODO: correctly handle location assignment from outside
713
Chris Forbes47567b72017-06-09 12:09:45 -0700714 // Second pass -- produce the output, from Location decorations
sfricke-samsung94d71a52021-02-26 05:25:43 -0800715 for (auto insn : src->member_decoration_inst) {
716 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700717 unsigned member_index = insn.word(2);
718 unsigned member_type_id = type.word(2 + member_index);
719
720 if (insn.word(3) == spv::DecorationLocation) {
721 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600722 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700723 auto component_it = member_components.find(member_index);
724 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
725 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700726 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700727
728 for (unsigned int offset = 0; offset < num_locations; offset++) {
729 interface_var v = {};
730 v.id = id;
731 // TODO: member index in interface_var too?
732 v.type_id = member_type_id;
733 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700734 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700735 v.is_block_member = true;
736 v.is_relaxed_precision = is_relaxed_precision;
737 (*out)[std::make_pair(location + offset, component)] = v;
738 }
739 }
740 }
741 }
Chris Forbesa313d772017-06-13 13:59:41 -0700742
743 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700744}
745
Ari Suonpaa696b3432019-03-11 14:02:57 +0200746static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800747 assert(entrypoint.opcode() == spv::OpEntryPoint);
748
Ari Suonpaa696b3432019-03-11 14:02:57 +0200749 std::vector<uint32_t> interfaces;
750 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
751 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
752 uint32_t word = 3;
753 while (entrypoint.word(word) & 0xff000000u) {
754 ++word;
755 }
756 ++word;
757
758 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
759
760 return interfaces;
761}
762
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600763static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600764 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700765 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
766
Chris Forbes47567b72017-06-09 12:09:45 -0700767 std::map<location_t, interface_var> out;
768
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800769 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
770 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700771 assert(insn != src->end());
772 assert(insn.opcode() == spv::OpVariable);
773
774 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800775 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700776 unsigned id = insn.word(2);
777 unsigned type = insn.word(1);
778
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800779 int location = d.location;
780 int builtin = d.builtin;
781 unsigned component = d.component;
782 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
783 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700784
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700785 if (builtin != -1) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700786 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700787 } else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700788 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
789 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600790 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700791 for (unsigned int offset = 0; offset < num_locations; offset++) {
792 interface_var v = {};
793 v.id = id;
794 v.type_id = type;
795 v.offset = offset;
796 v.is_patch = is_patch;
797 v.is_relaxed_precision = is_relaxed_precision;
798 out[std::make_pair(location + offset, component)] = v;
799 }
Chris Forbes47567b72017-06-09 12:09:45 -0700800 }
801 }
802 }
803
804 return out;
805}
806
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600807static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200808 uint32_t storageClass) {
809 std::vector<uint32_t> variables;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700810 std::vector<uint32_t> builtin_struct_members;
811 std::vector<uint32_t> builtin_decorations;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200812
sfricke-samsung94d71a52021-02-26 05:25:43 -0800813 for (auto insn : src->member_decoration_inst) {
814 if (insn.word(3) == spv::DecorationBuiltIn) {
815 builtin_struct_members.push_back(insn.word(1));
816 }
817 }
818 for (auto insn : src->decoration_inst) {
819 switch (insn.word(2)) {
820 case spv::DecorationBlock: {
821 uint32_t block_id = insn.word(1);
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800822 for (auto builtin_block_id : builtin_struct_members) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800823 // Check if one of the members of the block are built-in -> the block is built-in
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800824 if (block_id == builtin_block_id) {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800825 builtin_decorations.push_back(block_id);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200826 break;
827 }
Ari Suonpaa696b3432019-03-11 14:02:57 +0200828 }
829 break;
sfricke-samsung94d71a52021-02-26 05:25:43 -0800830 }
831 case spv::DecorationBuiltIn:
832 builtin_decorations.push_back(insn.word(1));
833 break;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200834 default:
835 break;
836 }
837 }
838
839 // Find all interface variables belonging to the entrypoint and matching the storage class
840 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
841 auto def = src->get_def(id);
842 assert(def != src->end());
843 assert(def.opcode() == spv::OpVariable);
844
845 if (def.word(3) == storageClass) variables.push_back(def.word(1));
846 }
847
848 // Find all members belonging to the builtin block selected
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700849 std::vector<uint32_t> builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200850 for (auto &var : variables) {
851 auto def = src->get_def(src->get_def(var).word(3));
852
853 // It could be an array of IO blocks. The element type should be the struct defining the block contents
854 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
855
856 // Now find all members belonging to the struct defining the IO block
857 if (def.opcode() == spv::OpTypeStruct) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800858 for (auto builtin_id : builtin_decorations) {
859 if (builtin_id == def.word(1)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700860 for (int i = 2; i < static_cast<int>(def.len()); i++) {
861 builtin_block_members.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
862 }
863 // These shouldn't be left after replacing.
sfricke-samsung94d71a52021-02-26 05:25:43 -0800864 for (auto insn : src->member_decoration_inst) {
sfricke-samsungc0eb5282021-02-28 23:05:55 -0800865 if (insn.word(1) == builtin_id && insn.word(3) == spv::DecorationBuiltIn) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700866 auto struct_index = insn.word(2);
867 assert(struct_index < builtin_block_members.size());
868 builtin_block_members[struct_index] = insn.word(4);
Ari Suonpaa696b3432019-03-11 14:02:57 +0200869 }
870 }
871 }
872 }
873 }
874 }
875
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700876 return builtin_block_members;
Ari Suonpaa696b3432019-03-11 14:02:57 +0200877}
878
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600879static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600880 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700881 std::vector<std::pair<uint32_t, interface_var>> out;
882
sfricke-samsung94d71a52021-02-26 05:25:43 -0800883 for (auto insn : src->decoration_inst) {
884 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
885 auto attachment_index = insn.word(3);
886 auto id = insn.word(1);
Chris Forbes47567b72017-06-09 12:09:45 -0700887
sfricke-samsung94d71a52021-02-26 05:25:43 -0800888 if (accessible_ids.count(id)) {
889 auto def = src->get_def(id);
890 assert(def != src->end());
891 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
892 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
893 for (unsigned int offset = 0; offset < num_locations; offset++) {
894 interface_var v = {};
895 v.id = id;
896 v.type_id = def.word(1);
897 v.offset = offset;
898 out.emplace_back(attachment_index + offset, v);
Chris Forbes47567b72017-06-09 12:09:45 -0700899 }
900 }
901 }
902 }
903 }
904
905 return out;
906}
907
locke-lunarg25b6c352020-08-06 17:44:18 -0600908static bool AtomicOperation(uint32_t opcode) {
909 switch (opcode) {
910 case spv::OpAtomicLoad:
911 case spv::OpAtomicStore:
912 case spv::OpAtomicExchange:
913 case spv::OpAtomicCompareExchange:
914 case spv::OpAtomicCompareExchangeWeak:
915 case spv::OpAtomicIIncrement:
916 case spv::OpAtomicIDecrement:
917 case spv::OpAtomicIAdd:
918 case spv::OpAtomicISub:
919 case spv::OpAtomicSMin:
920 case spv::OpAtomicUMin:
921 case spv::OpAtomicSMax:
922 case spv::OpAtomicUMax:
923 case spv::OpAtomicAnd:
924 case spv::OpAtomicOr:
925 case spv::OpAtomicXor:
926 case spv::OpAtomicFAddEXT:
927 return true;
928 default:
929 return false;
930 }
931 return false;
932}
933
sfricke-samsung0065ce02020-12-03 22:46:37 -0800934// Only includes valid group operations used in Vulkan (for now thats only subgroup ops) and any non supported operation will be
935// covered with VUID 01090
936static bool GroupOperation(uint32_t opcode) {
937 switch (opcode) {
938 case spv::OpGroupNonUniformElect:
939 case spv::OpGroupNonUniformAll:
940 case spv::OpGroupNonUniformAny:
941 case spv::OpGroupNonUniformAllEqual:
942 case spv::OpGroupNonUniformBroadcast:
943 case spv::OpGroupNonUniformBroadcastFirst:
944 case spv::OpGroupNonUniformBallot:
945 case spv::OpGroupNonUniformInverseBallot:
946 case spv::OpGroupNonUniformBallotBitExtract:
947 case spv::OpGroupNonUniformBallotBitCount:
948 case spv::OpGroupNonUniformBallotFindLSB:
949 case spv::OpGroupNonUniformBallotFindMSB:
950 case spv::OpGroupNonUniformShuffle:
951 case spv::OpGroupNonUniformShuffleXor:
952 case spv::OpGroupNonUniformShuffleUp:
953 case spv::OpGroupNonUniformShuffleDown:
954 case spv::OpGroupNonUniformIAdd:
955 case spv::OpGroupNonUniformFAdd:
956 case spv::OpGroupNonUniformIMul:
957 case spv::OpGroupNonUniformFMul:
958 case spv::OpGroupNonUniformSMin:
959 case spv::OpGroupNonUniformUMin:
960 case spv::OpGroupNonUniformFMin:
961 case spv::OpGroupNonUniformSMax:
962 case spv::OpGroupNonUniformUMax:
963 case spv::OpGroupNonUniformFMax:
964 case spv::OpGroupNonUniformBitwiseAnd:
965 case spv::OpGroupNonUniformBitwiseOr:
966 case spv::OpGroupNonUniformBitwiseXor:
967 case spv::OpGroupNonUniformLogicalAnd:
968 case spv::OpGroupNonUniformLogicalOr:
969 case spv::OpGroupNonUniformLogicalXor:
970 case spv::OpGroupNonUniformQuadBroadcast:
971 case spv::OpGroupNonUniformQuadSwap:
972 case spv::OpGroupNonUniformPartitionNV:
973 return true;
974 default:
975 return false;
976 }
977 return false;
978}
979
locke-lunarg12d20992020-09-21 12:46:49 -0600980bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
981 const std::unordered_map<unsigned, unsigned> &load_members,
982 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
983 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600984 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600985 auto load_it = load_members.find(load_id);
986 if (load_it == load_members.end()) {
987 continue;
988 }
989 if (load_it->second == object_id) {
990 return true;
991 }
992
993 auto accesschain_it = accesschain_members.find(load_it->second);
994 if (accesschain_it == accesschain_members.end()) {
995 continue;
996 }
997 if (accesschain_it->second.first == object_id) {
998 return true;
999 }
1000 }
1001 return false;
1002}
1003
locke-lunargae2a43c2020-09-22 17:21:57 -06001004bool CheckImageOperandsBiasOffset(uint32_t type) {
1005 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1006 spv::ImageOperandsConstOffsetsMask)
1007 ? true
1008 : false;
1009}
1010
locke-lunargd3da0422020-09-23 01:02:11 -06001011struct shader_module_used_operators {
1012 bool updated;
1013 std::vector<unsigned> imagwrite_members;
1014 std::vector<unsigned> atomic_members;
1015 std::vector<unsigned> store_members;
1016 std::vector<unsigned> atomic_store_members;
1017 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
1018 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
sfricke-samsung691299b2021-01-01 20:48:48 -08001019 std::vector<std::pair<unsigned, unsigned>> sampledImage_members; // <image,sampler> Load id
locke-lunargd3da0422020-09-23 01:02:11 -06001020 std::unordered_map<unsigned, unsigned> load_members;
1021 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
1022 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
1023
1024 shader_module_used_operators() : updated(false) {}
1025
1026 void update(SHADER_MODULE_STATE const *module) {
1027 if (updated) return;
1028 updated = true;
1029
1030 for (auto insn : *module) {
1031 switch (insn.opcode()) {
1032 case spv::OpImageSampleImplicitLod:
1033 case spv::OpImageSampleProjImplicitLod:
1034 case spv::OpImageSampleProjExplicitLod:
1035 case spv::OpImageSparseSampleImplicitLod:
1036 case spv::OpImageSparseSampleProjImplicitLod:
1037 case spv::OpImageSparseSampleProjExplicitLod: {
1038 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1039 // ImageOperands in index: 5
1040 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1041 sampler_bias_offset_members.emplace_back(insn.word(3));
1042 }
1043 break;
1044 }
1045 case spv::OpImageSampleDrefImplicitLod:
1046 case spv::OpImageSampleDrefExplicitLod:
1047 case spv::OpImageSampleProjDrefImplicitLod:
1048 case spv::OpImageSampleProjDrefExplicitLod:
1049 case spv::OpImageSparseSampleDrefImplicitLod:
1050 case spv::OpImageSparseSampleDrefExplicitLod:
1051 case spv::OpImageSparseSampleProjDrefImplicitLod:
1052 case spv::OpImageSparseSampleProjDrefExplicitLod: {
1053 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
1054 // ImageOperands in index: 6
1055 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
1056 sampler_bias_offset_members.emplace_back(insn.word(3));
1057 }
1058 break;
1059 }
1060 case spv::OpImageSampleExplicitLod:
1061 case spv::OpImageSparseSampleExplicitLod: {
1062 // ImageOperands in index: 5
1063 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
1064 sampler_bias_offset_members.emplace_back(insn.word(3));
1065 }
1066 break;
1067 }
1068 case spv::OpStore: {
1069 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1070 break;
1071 }
1072 case spv::OpImageWrite: {
1073 imagwrite_members.emplace_back(insn.word(1)); // Load id
1074 break;
1075 }
1076 case spv::OpSampledImage: {
1077 // 3: image load id, 4: sampler load id
1078 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1079 break;
1080 }
1081 case spv::OpLoad: {
1082 // 2: Load id, 3: object id or AccessChain id
1083 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1084 break;
1085 }
1086 case spv::OpAccessChain: {
locke-lunarg025daa72020-10-13 11:07:51 -06001087 if (insn.len() == 4) {
1088 // If it is for struct, the length is only 4.
1089 // 2: AccessChain id, 3: object id
1090 accesschain_members.insert(std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), 0)));
1091 } else {
1092 // 2: AccessChain id, 3: object id, 4: object id of array index
1093 accesschain_members.insert(
1094 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
1095 }
locke-lunargd3da0422020-09-23 01:02:11 -06001096 break;
1097 }
1098 case spv::OpImageTexelPointer: {
1099 // 2: ImageTexelPointer id, 3: object id
1100 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1101 break;
1102 }
1103 default: {
1104 if (AtomicOperation(insn.opcode())) {
1105 if (insn.opcode() == spv::OpAtomicStore) {
1106 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1107 } else {
1108 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1109 }
1110 }
1111 break;
1112 }
1113 }
1114 }
1115 }
1116};
1117
sfricke-samsung691299b2021-01-01 20:48:48 -08001118// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1119// atomic operation, matching images to samplers, etc
locke-lunarg25b6c352020-08-06 17:44:18 -06001120static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001121 bool is_check_writable, interface_var &out_interface_var,
1122 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001123 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001124 unsigned int id = id_it.word(2);
1125
Chris Forbes8af24522018-03-07 11:37:45 -08001126 auto type = module->get_def(type_id);
1127
1128 // 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 -06001129 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1130 type.opcode() == spv::OpTypeSampledImage) {
1131 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1132 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001133 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001134 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001135 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001136 }
1137 }
Chris Forbes8af24522018-03-07 11:37:45 -08001138 switch (type.opcode()) {
1139 case spv::OpTypeImage: {
1140 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001141 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001142 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001143
locke-lunargd3da0422020-09-23 01:02:11 -06001144 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1145 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001146 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001147 }
1148 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1149 used_operators.accesschain_members)) {
1150 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001151 }
locke-lunargd3da0422020-09-23 01:02:11 -06001152 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1153 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001154 out_interface_var.is_sampler_bias_offset = true;
1155 }
locke-lunargd3da0422020-09-23 01:02:11 -06001156 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1157 used_operators.accesschain_members) ||
1158 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1159 used_operators.accesschain_members)) {
1160 out_interface_var.is_atomic_operation = true;
1161 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001162
locke-lunargd3da0422020-09-23 01:02:11 -06001163 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001164 // Find if image id match.
1165 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001166 auto load_it = used_operators.load_members.find(itp_id.first);
1167 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001168 continue;
1169 } else {
1170 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001171 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1172 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001173 continue;
1174 } else {
1175 if (accesschain_it->second.first != id) {
1176 continue;
1177 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001178
1179 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1180 if (const_itr == module->end()) {
1181 // access chain index not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001182 break;
1183 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001184 image_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001185 }
1186 }
1187 }
1188 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001189 load_it = used_operators.load_members.find(itp_id.second);
1190 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001191 continue;
1192 } else {
1193 uint32_t sampler_id = load_it->second;
1194 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001195 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001196
locke-lunargd3da0422020-09-23 01:02:11 -06001197 if (accesschain_it != used_operators.accesschain_members.end()) {
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001198 const auto const_itr = GetConstantDef(module, accesschain_it->second.second);
1199 if (const_itr == module->end()) {
1200 // access chain index representing sampler index is not a constant, skip.
locke-lunarg025daa72020-10-13 11:07:51 -06001201 break;
1202 }
Nathaniel Cesario2d3dc2b2021-02-16 19:51:03 -07001203 sampler_id = const_itr.offset();
1204 sampler_index = GetConstantValue(const_itr);
locke-lunarg36045992020-08-20 16:54:37 -06001205 }
1206 auto sampler_dec = module->get_decorations(sampler_id);
locke-lunarg654a9052020-10-13 16:28:42 -06001207 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1208 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1209 }
1210 out_interface_var.samplers_used_by_image[image_index].emplace(
1211 SamplerUsedByImage{descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
locke-lunarg36045992020-08-20 16:54:37 -06001212 }
1213 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001214 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001215 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001216 }
1217
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001218 case spv::OpTypeStruct: {
1219 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001220 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
sfricke-samsung94d71a52021-02-26 05:25:43 -08001221 for (auto insn : module->member_decoration_inst) {
1222 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001223 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001224 }
1225 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001226
1227 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1228 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001229 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001230 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001231
locke-lunargd3da0422020-09-23 01:02:11 -06001232 for (auto oid : used_operators.store_members) {
1233 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001234 out_interface_var.is_writable = true;
1235 return;
1236 }
locke-lunargd3da0422020-09-23 01:02:11 -06001237 auto accesschain_it = used_operators.accesschain_members.find(oid);
1238 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001239 continue;
1240 }
locke-lunargd3da0422020-09-23 01:02:11 -06001241 if (accesschain_it->second.first == id) {
1242 out_interface_var.is_writable = true;
1243 return;
1244 }
1245 }
1246 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1247 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001248 out_interface_var.is_writable = true;
1249 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001250 }
1251 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001252 }
Chris Forbes8af24522018-03-07 11:37:45 -08001253 }
Chris Forbes8af24522018-03-07 11:37:45 -08001254}
1255
locke-lunargd9a069d2019-09-17 01:50:19 -06001256std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001257 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1258 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001259 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001260 shader_module_used_operators operators;
1261
Chris Forbes47567b72017-06-09 12:09:45 -07001262 for (auto id : accessible_ids) {
1263 auto insn = src->get_def(id);
1264 assert(insn != src->end());
1265
1266 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001267 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1268 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001269 auto d = src->get_decorations(insn.word(2));
1270 unsigned set = d.descriptor_set;
1271 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001272
1273 interface_var v = {};
1274 v.id = insn.word(2);
1275 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001276
locke-lunarg25b6c352020-08-06 17:44:18 -06001277 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001278 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001279 if (v.is_writable) *has_writable_descriptor = true;
1280 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg654e3692020-06-04 17:19:15 -06001281 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001282 }
1283 }
1284
1285 return out;
1286}
1287
locke-lunargde3f0fa2020-09-10 11:55:31 -06001288void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1289 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1290 const auto struct_it = GetStructType(&src, it, false);
1291 assert(struct_it != src.end());
1292 data.size = 0;
1293
1294 shader_struct_member data1;
1295 uint32_t i = 2;
1296 uint32_t local_offset = 0;
1297 std::vector<uint32_t> offsets;
1298 offsets.resize(struct_it.len() - i);
1299
1300 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1301 for (const auto offset : memberDecorate_offsets) {
1302 const auto member_decorate = src.at(offset);
1303 if (member_decorate.word(1) != struct_it.word(1)) {
1304 continue;
1305 }
1306
1307 offsets[member_decorate.word(2)] = member_decorate.word(4);
1308 }
1309
1310 for (const auto offset : offsets) {
1311 local_offset = offset;
1312 data1 = {};
1313 data1.root = data.root;
1314 data1.offset = local_offset;
1315 auto def_member = src.get_def(struct_it.word(i));
1316
1317 // Array could be multi-dimensional
1318 while (def_member.opcode() == spv::OpTypeArray) {
1319 const auto len_id = def_member.word(3);
1320 const auto def_len = src.get_def(len_id);
1321 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1322 def_member = src.get_def(def_member.word(2));
1323 }
1324
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001325 if (def_member.opcode() == spv::OpTypeStruct) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001326 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
Nathaniel Cesario85caecf2021-01-14 10:28:05 -07001327 } else if (def_member.opcode() == spv::OpTypePointer) {
1328 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
1329 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
1330 // that "points to something."
1331 data1.size = 8;
1332 } else {
1333 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1334 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1335 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001336 } else {
1337 if (def_member.opcode() == spv::OpTypeMatrix) {
1338 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1339 def_member = src.get_def(def_member.word(2));
1340 }
1341
1342 if (def_member.opcode() == spv::OpTypeVector) {
1343 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1344 def_member = src.get_def(def_member.word(2));
1345 }
1346
1347 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1348 data1.size = (def_member.word(2) / 8);
1349 }
1350 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1351 if (array_length_hierarchy_szie > 0) {
1352 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1353
1354 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1355 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1356 }
1357 }
1358 data.struct_members.emplace_back(data1);
1359 ++i;
1360 }
1361 uint32_t total_array_length = 1;
1362 for (const auto length : data1.array_length_hierarchy) {
1363 total_array_length *= length;
1364 }
1365 data.size = local_offset + data1.size * total_array_length;
1366}
1367
1368uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1369 int array_indices_size = static_cast<int>(array_indices.size());
1370 if (array_indices_size) {
1371 uint32_t array_index = 0;
1372 uint32_t i = 0;
1373 for (const auto index : array_indices) {
1374 array_index += (data.array_block_size[i] * index);
1375 ++i;
1376 }
1377 offset += (array_index * data.size);
1378 }
1379 return offset;
1380}
1381
1382void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1383 int array_indices_size = static_cast<int>(array_indices.size());
1384 uint32_t block_memory_size = data.size;
1385 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1386 block_memory_size *= data.array_length_hierarchy[i];
1387 }
1388
1389 offset = UpdateOffset(offset, array_indices, data);
1390
1391 uint32_t end = offset + block_memory_size;
1392 auto used_bytes = data.GetUsedbytes();
1393 if (used_bytes->size() < end) {
1394 used_bytes->resize(end, 0);
1395 }
1396 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1397}
1398
1399void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1400 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1401 if (access_chain_word_index < access_chain_it.len()) {
1402 if (data.array_length_hierarchy.size() > array_indices.size()) {
1403 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1404 ++access_chain_word_index;
1405
1406 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1407 array_indices.emplace_back(def_it.word(3));
1408 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1409 } else {
1410 // If it is a variable, set the all array is used.
1411 if (access_chain_word_index < access_chain_it.len()) {
1412 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1413 for (uint32_t i = 0; i < array_length; ++i) {
1414 auto array_indices2 = array_indices;
1415 array_indices2.emplace_back(i);
1416 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1417 }
1418 } else {
1419 SetUsedBytes(offset, array_indices, data);
1420 }
1421 }
1422 } else {
1423 offset = UpdateOffset(offset, array_indices, data);
1424 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1425 }
1426 } else {
1427 SetUsedBytes(offset, array_indices, data);
1428 }
1429}
1430
1431void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1432 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1433 std::vector<uint32_t> array_indices_emptry;
1434
1435 if (access_chain_word_index < access_chain_it.len()) {
1436 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1437 ++access_chain_word_index;
1438
1439 auto data1 = data.struct_members[strcut_member_index];
1440 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1441 }
1442}
1443
1444void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1445 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1446 for (const auto &func_set : function_set_list) {
1447 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1448 for (auto it = range.first; it != range.second; ++it) {
1449 auto access_chain = src.at(it->second);
1450 if (access_chain.word(3) == variable_id) {
1451 RunUsedStruct(src, 0, 4, access_chain, data);
1452 }
1453 }
1454 }
1455}
1456
1457void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1458 for (auto &entrypoint : src.entry_points) {
1459 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1460 for (auto it = range.first; it != range.second; ++it) {
1461 const auto def_insn = src.at(it->second);
1462
1463 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1464 spirv_inst_iter type = src.get_def(def_insn.word(1));
1465 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1466 std::vector<uint32_t> offsets;
1467
1468 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1469 auto member_decorate = src.at(it2->second);
1470 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1471 offsets.emplace_back(member_decorate.offset());
1472 }
1473 }
1474 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1475 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1476 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1477 entrypoint.second.push_constant_used_in_shader);
1478 }
1479 }
1480 }
1481}
1482
locke-lunarg96dc9632020-06-10 17:22:18 -06001483std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1484 const VkPipelineShaderStageCreateInfo &stage_info) {
1485 std::unordered_set<uint32_t> location_list;
1486 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1487 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1488 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1489 std::unordered_set<unsigned> store_members;
1490 std::unordered_map<unsigned, unsigned> accesschain_members;
1491
1492 for (auto insn : module) {
1493 switch (insn.opcode()) {
1494 case spv::OpStore:
1495 case spv::OpAtomicStore: {
1496 store_members.insert(insn.word(1)); // object id or AccessChain id
1497 break;
1498 }
1499 case spv::OpAccessChain: {
1500 // 2: AccessChain id, 3: object id
1501 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1502 break;
1503 }
1504 default:
1505 break;
1506 }
1507 }
1508 if (store_members.empty()) {
1509 return location_list;
1510 }
1511 for (auto output : outputs) {
1512 auto store_it = store_members.find(output.second.id);
1513 if (store_it != store_members.end()) {
1514 location_list.insert(output.first.first);
1515 store_members.erase(store_it);
1516 continue;
1517 }
1518 store_it = store_members.begin();
1519 while (store_it != store_members.end()) {
1520 auto accesschain_it = accesschain_members.find(*store_it);
1521 if (accesschain_it == accesschain_members.end()) {
1522 ++store_it;
1523 continue;
1524 }
1525 if (accesschain_it->second == output.second.id) {
1526 location_list.insert(output.first.first);
1527 store_members.erase(store_it);
1528 accesschain_members.erase(accesschain_it);
1529 break;
1530 }
1531 ++store_it;
1532 }
1533 }
1534 return location_list;
1535}
1536
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001537bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001538 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1539 // be specified only once.
1540 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1541 bool skip = false;
1542
1543 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1544 auto desc = &vi->pVertexBindingDescriptions[i];
1545 auto &binding = bindings[desc->binding];
1546 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001547 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001548 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1549 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001550 } else {
1551 binding = desc;
1552 }
1553 }
1554
1555 return skip;
1556}
1557
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001558bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1559 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001560 bool skip = false;
1561
Petr Kraus25810d02019-08-27 17:41:15 +02001562 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001563
1564 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001565 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001566 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001567 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1568 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1569 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001570 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1571 }
1572 }
1573 }
1574
Petr Kraus25810d02019-08-27 17:41:15 +02001575 struct AttribInputPair {
1576 const VkVertexInputAttributeDescription *attrib = nullptr;
1577 const interface_var *input = nullptr;
1578 };
1579 std::map<uint32_t, AttribInputPair> location_map;
1580 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1581 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001582
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001583 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001584 const auto location = location_it.first;
1585 const auto attrib = location_it.second.attrib;
1586 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001587
Petr Kraus25810d02019-08-27 17:41:15 +02001588 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001589 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1590 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001591 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001592 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1593 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001594 } else if (attrib && input) {
1595 const auto attrib_type = GetFormatType(attrib->format);
1596 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001597
1598 // Type checking
1599 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001600 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1601 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1602 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001603 }
Petr Kraus25810d02019-08-27 17:41:15 +02001604 } else { // !attrib && !input
1605 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001606 }
1607 }
1608
1609 return skip;
1610}
1611
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001612bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1613 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001614 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001615
Petr Kraus25810d02019-08-27 17:41:15 +02001616 const auto rpci = pipeline->rp_state->createInfo.ptr();
1617
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001618 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001619 const VkAttachmentReference2 *reference = nullptr;
1620 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001621 const interface_var *output = nullptr;
1622 };
1623 std::map<uint32_t, Attachment> location_map;
1624
Petr Kraus25810d02019-08-27 17:41:15 +02001625 const auto subpass = rpci->pSubpasses[subpass_index];
1626 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001627 auto const &reference = subpass.pColorAttachments[i];
1628 location_map[i].reference = &reference;
1629 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1630 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1631 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001632 }
1633 }
1634
Chris Forbes47567b72017-06-09 12:09:45 -07001635 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1636
Petr Kraus25810d02019-08-27 17:41:15 +02001637 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001638 for (const auto &output_it : outputs) {
1639 auto const location = output_it.first.first;
1640 location_map[location].output = &output_it.second;
1641 }
Chris Forbes47567b72017-06-09 12:09:45 -07001642
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001643 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1644 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001645
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001646 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001647 const auto reference = location_it.second.reference;
1648 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1649 continue;
1650 }
1651
Petr Kraus25810d02019-08-27 17:41:15 +02001652 const auto location = location_it.first;
1653 const auto attachment = location_it.second.attachment;
1654 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001655 if (attachment && !output) {
1656 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001657 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1658 "Attachment %" PRIu32
1659 " not written by fragment shader; undefined values will be written to attachment",
1660 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001661 }
1662 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001663 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001664 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1665 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001666 }
Petr Kraus25810d02019-08-27 17:41:15 +02001667 } else if (attachment && output) {
1668 const auto attachment_type = GetFormatType(attachment->format);
1669 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001670
1671 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001672 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001673 skip |=
1674 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1675 "Attachment %" PRIu32
1676 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1677 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001678 }
Petr Kraus25810d02019-08-27 17:41:15 +02001679 } else { // !attachment && !output
1680 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001681 }
1682 }
1683
Petr Kraus25810d02019-08-27 17:41:15 +02001684 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001685 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1686 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
1687 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001688 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1689 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001690 }
1691
Chris Forbes47567b72017-06-09 12:09:45 -07001692 return skip;
1693}
1694
Tobias Hector6663c9b2020-11-05 10:18:02 +00001695// 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 -06001696// This function examines instructions in the static call tree for a write to this variable.
Tobias Hector6663c9b2020-11-05 10:18:02 +00001697static bool IsBuiltInWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001698 auto type = builtin_instr.opcode();
1699 uint32_t target_id = builtin_instr.word(1);
1700 bool init_complete = false;
1701
1702 if (type == spv::OpMemberDecorate) {
1703 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1704 auto insn = entrypoint;
1705 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1706 switch (insn.opcode()) {
1707 case spv::OpTypePointer:
1708 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1709 target_id = insn.word(1);
1710 }
1711 break;
1712 case spv::OpVariable:
1713 if (insn.word(1) == target_id) {
1714 target_id = insn.word(2);
1715 init_complete = true;
1716 }
1717 break;
1718 }
1719 insn++;
1720 }
1721 }
1722
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001723 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1724
1725 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001726 std::unordered_set<uint32_t> worklist;
1727 worklist.insert(entrypoint.word(2));
1728
1729 // Follow instructions in call graph looking for writes to target
1730 while (!worklist.empty() && !found_write) {
1731 auto id_iter = worklist.begin();
1732 auto id = *id_iter;
1733 worklist.erase(id_iter);
1734
1735 auto insn = src->get_def(id);
1736 if (insn == src->end()) {
1737 continue;
1738 }
1739
1740 if (insn.opcode() == spv::OpFunction) {
1741 // Scan body of function looking for other function calls or items in our ID chain
1742 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1743 switch (insn.opcode()) {
1744 case spv::OpAccessChain:
1745 if (insn.word(3) == target_id) {
1746 if (type == spv::OpMemberDecorate) {
1747 auto value = GetConstantValue(src, insn.word(4));
1748 if (value == builtin_instr.word(2)) {
1749 target_id = insn.word(2);
1750 }
1751 } else {
1752 target_id = insn.word(2);
1753 }
1754 }
1755 break;
1756 case spv::OpStore:
1757 if (insn.word(1) == target_id) {
1758 found_write = true;
1759 }
1760 break;
1761 case spv::OpFunctionCall:
1762 worklist.insert(insn.word(3));
1763 break;
1764 }
1765 }
1766 }
1767 }
1768 return found_write;
1769}
1770
Chris Forbes47567b72017-06-09 12:09:45 -07001771// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1772// important for identifying the set of shader resources actually used by an entrypoint, for example.
1773// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1774// - NOT the shader input/output interfaces.
1775//
1776// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1777// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001778std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001779 std::unordered_set<uint32_t> ids;
1780 std::unordered_set<uint32_t> worklist;
1781 worklist.insert(entrypoint.word(2));
1782
1783 while (!worklist.empty()) {
1784 auto id_iter = worklist.begin();
1785 auto id = *id_iter;
1786 worklist.erase(id_iter);
1787
1788 auto insn = src->get_def(id);
1789 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001790 // 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 -07001791 // that we may not care about.
1792 continue;
1793 }
1794
1795 // Try to add to the output set
1796 if (!ids.insert(id).second) {
1797 continue; // If we already saw this id, we don't want to walk it again.
1798 }
1799
1800 switch (insn.opcode()) {
1801 case spv::OpFunction:
1802 // Scan whole body of the function, enlisting anything interesting
1803 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1804 switch (insn.opcode()) {
1805 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001806 worklist.insert(insn.word(3)); // ptr
1807 break;
1808 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001809 worklist.insert(insn.word(1)); // ptr
1810 break;
1811 case spv::OpAccessChain:
1812 case spv::OpInBoundsAccessChain:
1813 worklist.insert(insn.word(3)); // base ptr
1814 break;
1815 case spv::OpSampledImage:
1816 case spv::OpImageSampleImplicitLod:
1817 case spv::OpImageSampleExplicitLod:
1818 case spv::OpImageSampleDrefImplicitLod:
1819 case spv::OpImageSampleDrefExplicitLod:
1820 case spv::OpImageSampleProjImplicitLod:
1821 case spv::OpImageSampleProjExplicitLod:
1822 case spv::OpImageSampleProjDrefImplicitLod:
1823 case spv::OpImageSampleProjDrefExplicitLod:
1824 case spv::OpImageFetch:
1825 case spv::OpImageGather:
1826 case spv::OpImageDrefGather:
1827 case spv::OpImageRead:
1828 case spv::OpImage:
1829 case spv::OpImageQueryFormat:
1830 case spv::OpImageQueryOrder:
1831 case spv::OpImageQuerySizeLod:
1832 case spv::OpImageQuerySize:
1833 case spv::OpImageQueryLod:
1834 case spv::OpImageQueryLevels:
1835 case spv::OpImageQuerySamples:
1836 case spv::OpImageSparseSampleImplicitLod:
1837 case spv::OpImageSparseSampleExplicitLod:
1838 case spv::OpImageSparseSampleDrefImplicitLod:
1839 case spv::OpImageSparseSampleDrefExplicitLod:
1840 case spv::OpImageSparseSampleProjImplicitLod:
1841 case spv::OpImageSparseSampleProjExplicitLod:
1842 case spv::OpImageSparseSampleProjDrefImplicitLod:
1843 case spv::OpImageSparseSampleProjDrefExplicitLod:
1844 case spv::OpImageSparseFetch:
1845 case spv::OpImageSparseGather:
1846 case spv::OpImageSparseDrefGather:
1847 case spv::OpImageTexelPointer:
1848 worklist.insert(insn.word(3)); // Image or sampled image
1849 break;
1850 case spv::OpImageWrite:
1851 worklist.insert(insn.word(1)); // Image -- different operand order to above
1852 break;
1853 case spv::OpFunctionCall:
1854 for (uint32_t i = 3; i < insn.len(); i++) {
1855 worklist.insert(insn.word(i)); // fn itself, and all args
1856 }
1857 break;
1858
1859 case spv::OpExtInst:
1860 for (uint32_t i = 5; i < insn.len(); i++) {
1861 worklist.insert(insn.word(i)); // Operands to ext inst
1862 }
1863 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001864
1865 default: {
1866 if (AtomicOperation(insn.opcode())) {
1867 if (insn.opcode() == spv::OpAtomicStore) {
1868 worklist.insert(insn.word(1)); // ptr
1869 } else {
1870 worklist.insert(insn.word(3)); // ptr
1871 }
1872 }
1873 break;
1874 }
Chris Forbes47567b72017-06-09 12:09:45 -07001875 }
1876 }
1877 break;
1878 }
1879 }
1880
1881 return ids;
1882}
1883
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001884PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
1885 const shader_struct_member &push_constant_used_in_shader,
1886 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001887 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001888 const auto used_bytes_size = used_bytes->size();
1889 if (used_bytes_size == 0) return PC_Byte_Updated;
1890
1891 const auto push_constant_data_update_size = push_constant_data_update.size();
1892 const auto *data = push_constant_data_update.data();
1893 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
1894 if (used_bytes_size <= push_constant_data_update_size) {
1895 return PC_Byte_Updated;
1896 }
1897 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
1898
1899 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
1900 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
1901 return PC_Byte_Updated;
1902 }
locke-lunargde3f0fa2020-09-10 11:55:31 -06001903 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001904
locke-lunargde3f0fa2020-09-10 11:55:31 -06001905 uint32_t i = 0;
1906 for (const auto used : *used_bytes) {
1907 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001908 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001909 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001910 return PC_Byte_Not_Set;
1911 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001912 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001913 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001914 }
1915 }
1916 ++i;
1917 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001918 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001919}
1920
1921bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1922 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001923 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001924 // 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 -06001925 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1926 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1927 return skip;
1928 }
1929 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001930
locke-lunargde3f0fa2020-09-10 11:55:31 -06001931 bool found_stage = false;
1932 for (auto const &range : *push_constant_ranges) {
1933 if (range.stageFlags & pStage->stage) {
1934 found_stage = true;
1935 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001936 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -06001937 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001938 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001939 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001940 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -06001941 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001942 const auto ret =
1943 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001944
locke-lunarg3d8b8f32020-10-26 17:04:16 -06001945 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -06001946 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1947 LogObjectList objlist(src->vk_shader_module);
1948 objlist.add(pipeline.pipeline_layout->layout);
1949 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1950 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1951 string_VkShaderStageFlags(pStage->stage).c_str(),
1952 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1953 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001954 }
1955 }
1956 }
1957
locke-lunargde3f0fa2020-09-10 11:55:31 -06001958 if (!found_stage) {
1959 LogObjectList objlist(src->vk_shader_module);
1960 objlist.add(pipeline.pipeline_layout->layout);
1961 skip |= LogError(
1962 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1963 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1964 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001965 }
Chris Forbes47567b72017-06-09 12:09:45 -07001966 return skip;
1967}
1968
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001969bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const std::unordered_set<uint32_t> &accessible_ids,
1970 VkShaderStageFlagBits stage) const {
1971 bool skip = false;
1972
1973 // Currently all builtin tested are only found in fragment shaders
1974 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
1975 return skip;
1976 }
1977
1978 for (const auto id : accessible_ids) {
1979 auto insn = src->get_def(id);
1980 const decoration_set decorations = src->get_decorations(insn.word(2));
1981
1982 // Built-ins are obtained from OpVariable
1983 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
1984 auto type_pointer = src->get_def(insn.word(1));
1985 assert(type_pointer.opcode() == spv::OpTypePointer);
1986
1987 auto type = src->get_def(type_pointer.word(3));
1988 if (type.opcode() == spv::OpTypeArray) {
1989 uint32_t length = static_cast<uint32_t>(GetConstantValue(src, type.word(3)));
1990
1991 switch (decorations.builtin) {
1992 case spv::BuiltInSampleMask:
1993 // Handles both the input and output sampleMask
1994 if (length > phys_dev_props.limits.maxSampleMaskWords) {
1995 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
1996 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
1997 "maxSampleMaskWords of %u in %s.",
1998 length, phys_dev_props.limits.maxSampleMaskWords,
1999 report_data->FormatHandle(src->vk_shader_module).c_str());
2000 }
2001 break;
2002 }
2003 }
2004 }
2005 }
2006
2007 return skip;
2008}
2009
Chris Forbes47567b72017-06-09 12:09:45 -07002010// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002011bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002012 bool skip = false;
2013
2014 VkSpecializationInfo const *spec = info->pSpecializationInfo;
2015
2016 if (spec) {
2017 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002018 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002019 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
2020 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2021 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2022 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2023 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06002024
2025 continue;
2026 }
Chris Forbes47567b72017-06-09 12:09:45 -07002027 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002028 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
2029 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
2030 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
2031 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2032 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07002033 }
2034 }
2035 }
2036
2037 return skip;
2038}
2039
Jeff Bolz38b3ce72018-09-19 12:53:38 -05002040// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -07002041static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
2042 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -07002043 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08002044 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07002045 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05002046 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002047
2048 // 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 -05002049 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
2050 if (type.opcode() == spv::OpTypeRuntimeArray) {
2051 descriptor_count = 0;
2052 type = module->get_def(type.word(2));
2053 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002054 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07002055 type = module->get_def(type.word(2));
2056 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08002057 if (type.word(2) == spv::StorageClassStorageBuffer) {
2058 is_storage_buffer = true;
2059 }
Chris Forbes47567b72017-06-09 12:09:45 -07002060 type = module->get_def(type.word(3));
2061 }
2062 }
2063
2064 switch (type.opcode()) {
2065 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -08002066 for (auto insn : module->decoration_inst) {
2067 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002068 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08002069 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002070 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2071 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2072 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002073 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002074 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2075 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2076 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
2077 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08002078 }
Chris Forbes47567b72017-06-09 12:09:45 -07002079 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002080 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2081 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
2082 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002083 }
2084 }
2085 }
2086
2087 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05002088 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002089 }
2090
2091 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05002092 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
2093 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2094 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002095
Chris Forbes73c00bf2018-06-22 16:28:06 -07002096 case spv::OpTypeSampledImage: {
2097 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
2098 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
2099 auto image_type = module->get_def(type.word(2));
2100 auto dim = image_type.word(3);
2101 auto sampled = image_type.word(7);
2102 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002103 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2104 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002105 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07002106 }
Jeff Bolze54ae892018-09-08 12:16:29 -05002107 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2108 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002109
2110 case spv::OpTypeImage: {
2111 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
2112 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
2113 auto dim = type.word(3);
2114 auto sampled = type.word(7);
2115
2116 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002117 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
2118 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002119 } else if (dim == spv::DimBuffer) {
2120 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002121 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
2122 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002123 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002124 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
2125 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002126 }
2127 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05002128 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
2129 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
2130 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002131 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05002132 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
2133 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002134 }
2135 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06002136 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -07002137 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
2138 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05002139 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07002140
2141 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
2142 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05002143 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07002144 }
2145}
2146
Jeff Bolze54ae892018-09-08 12:16:29 -05002147static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07002148 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05002149 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
2150 if (ss.tellp()) ss << ", ";
2151 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07002152 }
2153 return ss.str();
2154}
2155
sfricke-samsung0065ce02020-12-03 22:46:37 -08002156bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002157 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002158 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 -05002159 return true;
2160 }
2161 }
2162
2163 return false;
2164}
2165
sfricke-samsung0065ce02020-12-03 22:46:37 -08002166bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002167 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002168 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002169 return true;
2170 }
2171 }
2172
2173 return false;
2174}
2175
locke-lunarg63e4daf2020-08-17 17:53:25 -06002176bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2177 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002178 bool skip = false;
2179
locke-lunarg63e4daf2020-08-17 17:53:25 -06002180 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002181 switch (stage) {
2182 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002183 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2184 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2185 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2186 case VK_SHADER_STAGE_MISS_BIT_NV:
2187 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2188 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2189 case VK_SHADER_STAGE_TASK_BIT_NV:
2190 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002191 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002192 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002193 break;
2194 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002195 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
2196 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002197 break;
2198 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -08002199 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
2200 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -08002201 break;
2202 }
2203 }
2204
Chris Forbes47567b72017-06-09 12:09:45 -07002205 return skip;
2206}
2207
sfricke-samsung94167ca2021-02-26 04:14:59 -08002208bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
2209 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002210 bool skip = false;
2211
sfricke-samsung94167ca2021-02-26 04:14:59 -08002212 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
2213 if (GroupOperation(insn.opcode()) == true) {
2214 // Check the quad operations.
2215 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
2216 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
2217 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
2218 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
2219 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -08002220 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08002221 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002222
sfricke-samsung94167ca2021-02-26 04:14:59 -08002223 uint32_t scope_type = spv::ScopeMax;
2224 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
2225 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
2226 scope_type = spv::ScopeSubgroup;
2227 } else {
2228 // "All <id> used for Scope <id> must be of an OpConstant"
2229 auto scope_id = module->get_def(insn.word(3));
2230 scope_type = scope_id.word(3);
2231 }
sfricke-samsung0065ce02020-12-03 22:46:37 -08002232
sfricke-samsung94167ca2021-02-26 04:14:59 -08002233 if (scope_type == spv::ScopeSubgroup) {
2234 // "Group operations with subgroup scope" must have stage support
2235 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
2236 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -08002237 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -08002238 }
2239
2240 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
2241 auto type = module->get_def(insn.word(1));
2242
2243 if (type.opcode() == spv::OpTypeVector) {
2244 // Get the element type
2245 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -08002246 }
2247
sfricke-samsung94167ca2021-02-26 04:14:59 -08002248 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -08002249 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2250 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002251
sfricke-samsung0065ce02020-12-03 22:46:37 -08002252 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2253 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
2254 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
2255 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
2256 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -05002257 }
2258 }
2259 }
Jeff Bolzee743412019-06-20 22:24:32 -05002260 }
2261
2262 return skip;
2263}
2264
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002265bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002266 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002267 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2268 pStage->stage == VK_SHADER_STAGE_ALL) {
2269 return false;
2270 }
2271
2272 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002273 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002274
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002275 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002276 struct Variable {
2277 uint32_t baseTypePtrID;
2278 uint32_t ID;
2279 uint32_t storageClass;
2280 };
2281 std::vector<Variable> variables;
2282
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002283 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002284 bool is_iso_lines = false;
2285 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002286
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002287 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002288
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002289 for (auto insn : *src) {
2290 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002291 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002292 case spv::OpDecorate:
2293 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002294 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002295 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002296 break;
2297 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002298 default:
2299 break;
2300 }
2301 break;
2302 // Find all input and output variables
2303 case spv::OpVariable: {
2304 Variable var = {};
2305 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002306 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2307 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002308 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002309 var.baseTypePtrID = insn.word(1);
2310 var.ID = insn.word(2);
2311 variables.push_back(var);
2312 }
2313 break;
2314 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002315 case spv::OpExecutionMode:
2316 if (insn.word(1) == entrypoint.word(2)) {
2317 switch (insn.word(2)) {
2318 default:
2319 break;
2320 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002321 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002322 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002323 case spv::ExecutionModeIsolines:
2324 is_iso_lines = true;
2325 break;
2326 case spv::ExecutionModePointMode:
2327 is_point_mode = true;
2328 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002329 }
2330 }
2331 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002332 default:
2333 break;
2334 }
2335 }
2336
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002337 bool strip_output_array_level =
2338 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2339 bool strip_input_array_level =
2340 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2341 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2342
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002343 uint32_t num_comp_in = 0, num_comp_out = 0;
2344 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002345
2346 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2347 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2348
2349 // Find max component location used for input variables.
2350 for (auto &var : inputs) {
2351 int location = var.first.first;
2352 int component = var.first.second;
2353 interface_var &iv = var.second;
2354
2355 // Only need to look at the first location, since we use the type's whole size
2356 if (iv.offset != 0) {
2357 continue;
2358 }
2359
2360 if (iv.is_patch) {
2361 continue;
2362 }
2363
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002364 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2365 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002366 }
2367
2368 // Find max component location used for output variables.
2369 for (auto &var : outputs) {
2370 int location = var.first.first;
2371 int component = var.first.second;
2372 interface_var &iv = var.second;
2373
2374 // Only need to look at the first location, since we use the type's whole size
2375 if (iv.offset != 0) {
2376 continue;
2377 }
2378
2379 if (iv.is_patch) {
2380 continue;
2381 }
2382
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002383 int num_components = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2384 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002385 }
2386
2387 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2388 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002389 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002390 // Check if the variable is a patch. Patches can also be members of blocks,
2391 // but if they are then the top-level arrayness has already been stripped
2392 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002393 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002394
2395 if (var.storageClass == spv::StorageClassInput) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002396 num_comp_in += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002397 } else { // var.storageClass == spv::StorageClassOutput
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002398 num_comp_out += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002399 }
2400 }
2401
2402 switch (pStage->stage) {
2403 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002404 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002405 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2406 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2407 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2408 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002409 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002410 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002411 if (max_comp_out > static_cast<int>(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 output variable uses location that "
2414 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2415 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002416 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002417 break;
2418
2419 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002420 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002421 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2422 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2423 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2424 "components by %u components",
2425 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002426 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002427 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002428 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002429 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002430 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2431 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2432 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2433 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002434 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002435 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002436 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2437 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2438 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2439 "components by %u components",
2440 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002441 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002442 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002443 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002444 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002445 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2446 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2447 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2448 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002449 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002450 break;
2451
2452 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002453 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002454 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2455 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2456 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2457 "components by %u components",
2458 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002459 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002460 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002461 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002462 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002463 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2464 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2465 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2466 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002467 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002468 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002469 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2470 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2471 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2472 "components by %u components",
2473 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002474 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002475 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002476 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -06002477 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002478 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2479 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2480 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2481 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002482 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -07002483 // Portability validation
2484 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
2485 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
2486 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
2487 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2488 " is using abstract patch type IsoLines, but this is not supported on this platform");
2489 }
2490 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
2491 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
2492 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
2493 " is using abstract patch type PointMode, but this is not supported on this platform");
2494 }
2495 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002496 break;
2497
2498 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002499 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002500 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2501 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2502 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2503 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002504 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002505 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002506 if (max_comp_in > static_cast<int>(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 input variable uses location that "
2509 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2510 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002511 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002512 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002513 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2514 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2515 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2516 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002517 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002518 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002519 if (max_comp_out > static_cast<int>(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 output variable uses location that "
2522 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2523 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002524 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002525 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002526 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2527 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2528 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2529 "components by %u components",
2530 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002531 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002532 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002533 break;
2534
2535 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002536 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002537 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2538 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2539 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2540 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002541 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002542 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002543 if (max_comp_in > static_cast<int>(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 input variable uses location that "
2546 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2547 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002548 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002549 break;
2550
Jeff Bolz148d94e2018-12-13 21:25:56 -06002551 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2552 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2553 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2554 case VK_SHADER_STAGE_MISS_BIT_NV:
2555 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2556 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2557 case VK_SHADER_STAGE_TASK_BIT_NV:
2558 case VK_SHADER_STAGE_MESH_BIT_NV:
2559 break;
2560
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002561 default:
2562 assert(false); // This should never happen
2563 }
2564 return skip;
2565}
2566
sfricke-samsungdc96f302020-03-18 20:42:10 -07002567bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2568 bool skip = false;
2569 uint32_t total_resources = 0;
2570
2571 // Only currently testing for graphics and compute pipelines
2572 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2573 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2574 return false;
2575 }
2576
2577 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2578 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2579 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2580 }
2581
2582 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2583 // input from CreatePipeline and CreatePipelineLayout level
2584 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2585 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2586 continue;
2587 }
2588
2589 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2590 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2591 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2592 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2593 // Check only descriptor types listed in maxPerStageResources description in spec
2594 switch (binding->descriptorType) {
2595 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2596 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2597 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2598 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2599 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2600 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2601 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2602 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2603 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2604 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2605 total_resources += binding->descriptorCount;
2606 break;
2607 default:
2608 break;
2609 }
2610 }
2611 }
2612 }
2613
2614 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2615 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2616 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2617 skip |= LogError(pipeline->pipeline, vuid,
2618 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2619 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2620 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2621 }
2622
2623 return skip;
2624}
2625
Jeff Bolze4356752019-03-07 11:23:46 -06002626// copy the specialization constant value into buf, if it is present
2627void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2628 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2629
2630 if (spec && spec_id < spec->mapEntryCount) {
2631 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2632 }
2633}
2634
2635// Fill in value with the constant or specialization constant value, if available.
2636// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002637static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002638 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2639 auto type_id = src->get_def(insn.word(1));
2640 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2641 return false;
2642 }
2643 switch (insn.opcode()) {
2644 case spv::OpSpecConstant:
2645 *value = insn.word(3);
2646 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2647 return true;
2648 case spv::OpConstant:
2649 *value = insn.word(3);
2650 return true;
2651 default:
2652 return false;
2653 }
2654}
2655
2656// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002657VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002658 switch (insn.opcode()) {
2659 case spv::OpTypeInt:
2660 switch (insn.word(2)) {
2661 case 8:
2662 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2663 case 16:
2664 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2665 case 32:
2666 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2667 case 64:
2668 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2669 default:
2670 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2671 }
2672 case spv::OpTypeFloat:
2673 switch (insn.word(2)) {
2674 case 16:
2675 return VK_COMPONENT_TYPE_FLOAT16_NV;
2676 case 32:
2677 return VK_COMPONENT_TYPE_FLOAT32_NV;
2678 case 64:
2679 return VK_COMPONENT_TYPE_FLOAT64_NV;
2680 default:
2681 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2682 }
2683 default:
2684 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2685 }
2686}
2687
2688// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2689// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002690bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002691 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002692 bool skip = false;
2693
2694 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2695 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2696 // Map SPIR-V result ID to the ID of its type.
2697 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2698
2699 struct CoopMatType {
2700 uint32_t scope, rows, cols;
2701 VkComponentTypeNV component_type;
2702 bool all_constant;
2703
2704 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2705
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002706 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002707 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2708 spirv_inst_iter insn = src->get_def(id);
2709 uint32_t component_type_id = insn.word(2);
2710 uint32_t scope_id = insn.word(3);
2711 uint32_t rows_id = insn.word(4);
2712 uint32_t cols_id = insn.word(5);
2713 auto component_type_iter = src->get_def(component_type_id);
2714 auto scope_iter = src->get_def(scope_id);
2715 auto rows_iter = src->get_def(rows_id);
2716 auto cols_iter = src->get_def(cols_id);
2717
2718 all_constant = true;
2719 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2720 all_constant = false;
2721 }
2722 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2723 all_constant = false;
2724 }
2725 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2726 all_constant = false;
2727 }
2728 component_type = GetComponentType(component_type_iter, src);
2729 }
2730 };
2731
2732 bool seen_coopmat_capability = false;
2733
2734 for (auto insn : *src) {
2735 // Whitelist instructions whose result can be a cooperative matrix type, and
2736 // keep track of their types. It would be nice if SPIRV-Headers generated code
2737 // to identify which instructions have a result type and result id. Lacking that,
2738 // this whitelist is based on the set of instructions that
2739 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2740 switch (insn.opcode()) {
2741 case spv::OpLoad:
2742 case spv::OpCooperativeMatrixLoadNV:
2743 case spv::OpCooperativeMatrixMulAddNV:
2744 case spv::OpSNegate:
2745 case spv::OpFNegate:
2746 case spv::OpIAdd:
2747 case spv::OpFAdd:
2748 case spv::OpISub:
2749 case spv::OpFSub:
2750 case spv::OpFDiv:
2751 case spv::OpSDiv:
2752 case spv::OpUDiv:
2753 case spv::OpMatrixTimesScalar:
2754 case spv::OpConstantComposite:
2755 case spv::OpCompositeConstruct:
2756 case spv::OpConvertFToU:
2757 case spv::OpConvertFToS:
2758 case spv::OpConvertSToF:
2759 case spv::OpConvertUToF:
2760 case spv::OpUConvert:
2761 case spv::OpSConvert:
2762 case spv::OpFConvert:
2763 id_to_type_id[insn.word(2)] = insn.word(1);
2764 break;
2765 default:
2766 break;
2767 }
2768
2769 switch (insn.opcode()) {
2770 case spv::OpDecorate:
2771 if (insn.word(2) == spv::DecorationSpecId) {
2772 id_to_spec_id[insn.word(1)] = insn.word(3);
2773 }
2774 break;
2775 case spv::OpCapability:
2776 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2777 seen_coopmat_capability = true;
2778
2779 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002780 skip |= LogError(
2781 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2782 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2783 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002784 }
2785 }
2786 break;
2787 case spv::OpMemoryModel:
2788 // If the capability isn't enabled, don't bother with the rest of this function.
2789 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2790 if (!seen_coopmat_capability) {
2791 return skip;
2792 }
2793 break;
2794 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002795 CoopMatType m;
2796 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002797
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002798 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002799 // Validate that the type parameters are all supported for one of the
2800 // operands of a cooperative matrix property.
2801 bool valid = false;
2802 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002803 if (cooperative_matrix_properties[i].AType == m.component_type &&
2804 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
2805 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002806 valid = true;
2807 break;
2808 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002809 if (cooperative_matrix_properties[i].BType == m.component_type &&
2810 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2811 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002812 valid = true;
2813 break;
2814 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002815 if (cooperative_matrix_properties[i].CType == m.component_type &&
2816 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2817 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002818 valid = true;
2819 break;
2820 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002821 if (cooperative_matrix_properties[i].DType == m.component_type &&
2822 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
2823 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002824 valid = true;
2825 break;
2826 }
2827 }
2828 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002829 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2830 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2831 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002832 }
2833 }
2834 break;
2835 }
2836 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002837 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06002838 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2839 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2840 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2841 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002842 // Couldn't find type of matrix
2843 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002844 break;
2845 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002846 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2847 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2848 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2849 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06002850
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002851 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06002852 // Validate that the type parameters are all supported for the same
2853 // cooperative matrix property.
2854 bool valid = false;
2855 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002856 if (cooperative_matrix_properties[i].AType == a.component_type &&
2857 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
2858 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002859
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002860 cooperative_matrix_properties[i].BType == b.component_type &&
2861 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
2862 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002863
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002864 cooperative_matrix_properties[i].CType == c.component_type &&
2865 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
2866 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06002867
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002868 cooperative_matrix_properties[i].DType == d.component_type &&
2869 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
2870 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06002871 valid = true;
2872 break;
2873 }
2874 }
2875 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002876 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2877 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
2878 "VkCooperativeMatrixPropertiesNV",
2879 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06002880 }
2881 }
2882 break;
2883 }
2884 default:
2885 break;
2886 }
2887 }
2888
2889 return skip;
2890}
2891
John Zulaufac4c6e12019-07-01 16:05:58 -06002892bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002893 auto entrypoint_id = entrypoint.word(2);
2894
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002895 // The first denorm execution mode encountered, along with its bit width.
2896 // Used to check if SeparateDenormSettings is respected.
2897 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002898
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002899 // The first rounding mode encountered, along with its bit width.
2900 // Used to check if SeparateRoundingModeSettings is respected.
2901 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002902
2903 bool skip = false;
2904
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002905 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002906 uint32_t invocations = 0;
2907
sfricke-samsung8a7341a2021-02-28 07:30:21 -08002908 auto it = src->execution_mode_inst.find(entrypoint_id);
2909 if (it != src->execution_mode_inst.end()) {
2910 for (auto insn : it->second) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002911 auto mode = insn.word(2);
2912 switch (mode) {
2913 case spv::ExecutionModeSignedZeroInfNanPreserve: {
2914 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002915 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
2916 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
2917 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002918 skip |= LogError(
2919 device, kVUID_Core_Shader_FeatureNotEnabled,
2920 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
2921 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002922 }
2923 break;
2924 }
2925
2926 case spv::ExecutionModeDenormPreserve: {
2927 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002928 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
2929 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
2930 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002931 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2932 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
2933 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002934 }
2935
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002936 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2937 // Register the first denorm execution mode found
2938 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002939 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002940 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002941 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002942 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002943 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2944 "Shader uses different denorm execution modes for 16 and 64-bit but "
2945 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002946 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002947 }
2948 break;
2949
Mike Schuchardt2df08912020-12-15 16:28:09 -08002950 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002951 break;
2952
Mike Schuchardt2df08912020-12-15 16:28:09 -08002953 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002954 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2955 "Shader uses different denorm execution modes for different bit widths but "
2956 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002957 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002958 break;
2959
2960 default:
2961 break;
2962 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002963 }
2964 break;
2965 }
2966
2967 case spv::ExecutionModeDenormFlushToZero: {
2968 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002969 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
2970 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
2971 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002972 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2973 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
2974 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002975 }
2976
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01002977 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
2978 // Register the first denorm execution mode found
2979 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002980 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002981 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002982 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002983 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002984 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2985 "Shader uses different denorm execution modes for 16 and 64-bit but "
2986 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002987 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002988 }
2989 break;
2990
Mike Schuchardt2df08912020-12-15 16:28:09 -08002991 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002992 break;
2993
Mike Schuchardt2df08912020-12-15 16:28:09 -08002994 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002995 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
2996 "Shader uses different denorm execution modes for different bit widths but "
2997 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08002998 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05002999 break;
3000
3001 default:
3002 break;
3003 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003004 }
3005 break;
3006 }
3007
3008 case spv::ExecutionModeRoundingModeRTE: {
3009 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003010 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3011 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3012 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003013 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3014 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3015 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003016 }
3017
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003018 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3019 // Register the first rounding mode found
3020 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003021 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003022 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003023 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003024 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003025 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3026 "Shader uses different rounding modes for 16 and 64-bit but "
3027 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003028 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003029 }
3030 break;
3031
Mike Schuchardt2df08912020-12-15 16:28:09 -08003032 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003033 break;
3034
Mike Schuchardt2df08912020-12-15 16:28:09 -08003035 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003036 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3037 "Shader uses different rounding modes for different bit widths but "
3038 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003039 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003040 break;
3041
3042 default:
3043 break;
3044 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003045 }
3046 break;
3047 }
3048
3049 case spv::ExecutionModeRoundingModeRTZ: {
3050 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003051 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3052 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3053 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003054 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3055 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3056 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003057 }
3058
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003059 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3060 // Register the first rounding mode found
3061 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003062 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003063 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08003064 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003065 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003066 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3067 "Shader uses different rounding modes for 16 and 64-bit but "
3068 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003069 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003070 }
3071 break;
3072
Mike Schuchardt2df08912020-12-15 16:28:09 -08003073 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003074 break;
3075
Mike Schuchardt2df08912020-12-15 16:28:09 -08003076 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003077 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3078 "Shader uses different rounding modes for different bit widths but "
3079 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08003080 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003081 break;
3082
3083 default:
3084 break;
3085 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003086 }
3087 break;
3088 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003089
3090 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003091 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003092 break;
3093 }
3094
3095 case spv::ExecutionModeInvocations: {
3096 invocations = insn.word(3);
3097 break;
3098 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003099 }
3100 }
3101 }
3102
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003103 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003104 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003105 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3106 "Geometry shader entry point must have an OpExecutionMode instruction that "
3107 "specifies a maximum output vertex count that is greater than 0 and less "
3108 "than or equal to maxGeometryOutputVertices. "
3109 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003110 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003111 }
3112
3113 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003114 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3115 "Geometry shader entry point must have an OpExecutionMode instruction that "
3116 "specifies an invocation count that is greater than 0 and less "
3117 "than or equal to maxGeometryShaderInvocations. "
3118 "Invocations=%d, maxGeometryShaderInvocations=%d",
3119 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003120 }
3121 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003122 return skip;
3123}
3124
locke-lunargd9a069d2019-09-17 01:50:19 -06003125uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003126 auto type = module->get_def(type_id);
3127
3128 while (true) {
3129 switch (type.opcode()) {
3130 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003131 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003132 case spv::OpTypeSampledImage:
3133 type = module->get_def(type.word(2));
3134 break;
3135 case spv::OpTypePointer:
3136 type = module->get_def(type.word(3));
3137 break;
3138 case spv::OpTypeImage: {
3139 auto dim = type.word(3);
3140 auto arrayed = type.word(5);
3141 auto msaa = type.word(6);
3142
Chris Forbes74ba2232018-08-27 15:19:27 -07003143 uint32_t bits = 0;
3144 switch (GetFundamentalType(module, type.word(2))) {
3145 case FORMAT_TYPE_FLOAT:
3146 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3147 break;
3148 case FORMAT_TYPE_UINT:
3149 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3150 break;
3151 case FORMAT_TYPE_SINT:
3152 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3153 break;
3154 default:
3155 break;
3156 }
3157
Chris Forbes47567b72017-06-09 12:09:45 -07003158 switch (dim) {
3159 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003160 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3161 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003162 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003163 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3164 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3165 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003166 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003167 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3168 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003169 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003170 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3171 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003172 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003173 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3174 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003175 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003176 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003177 }
3178 }
3179 default:
3180 return 0;
3181 }
3182 }
3183}
3184
3185// For given pipelineLayout verify that the set_layout_node at slot.first
3186// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003187static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003188 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003189 if (!pipelineLayout) return nullptr;
3190
3191 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3192
3193 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3194}
3195
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003196int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3197 if (module == nullptr) return -1;
3198
3199 auto type = module->get_def(resource.type_id);
3200 while (true) {
3201 switch (type.opcode()) {
3202 case spv::OpTypeSampledImage:
3203 type = module->get_def(type.word(2));
3204 break;
3205 case spv::OpTypePointer:
3206 type = module->get_def(type.word(3));
3207 break;
3208 case spv::OpTypeImage:
3209 return type.word(3);
3210 default:
3211 return -1;
3212 }
3213 }
3214}
3215
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003216// Because the following is legal, need the entry point
3217// OpEntryPoint GLCompute %main "name_a"
3218// OpEntryPoint GLCompute %main "name_b"
3219bool FindLocalSize(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, uint32_t &local_size_x,
3220 uint32_t &local_size_y, uint32_t &local_size_z) {
3221 auto entrypoint_id = entrypoint.word(2);
3222 auto it = src->execution_mode_inst.find(entrypoint_id);
3223 if (it != src->execution_mode_inst.end()) {
3224 for (auto insn : it->second) {
3225 // Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
3226 // In the future if something like LocalSizeId is supported, the <id> will need to be checked also
3227 assert(insn.opcode() == spv::OpExecutionMode);
3228 if (insn.word(2) == spv::ExecutionModeLocalSize) {
3229 local_size_x = insn.word(3);
3230 local_size_y = insn.word(4);
3231 local_size_z = insn.word(5);
3232 return true;
Locke1ec6d952019-04-02 11:57:21 -06003233 }
3234 }
3235 }
3236 return false;
3237}
3238
locke-lunargd9a069d2019-09-17 01:50:19 -06003239void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003240 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003241 bool is_point_mode = false;
3242
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003243 auto it = src->execution_mode_inst.find(entrypoint_id);
3244 if (it != src->execution_mode_inst.end()) {
3245 for (auto insn : it->second) {
Chris Forbes0771b672018-03-22 21:13:46 -07003246 switch (insn.word(2)) {
3247 case spv::ExecutionModePointMode:
3248 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3249 is_point_mode = true;
3250 break;
3251
3252 case spv::ExecutionModeOutputPoints:
3253 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3254 break;
3255
3256 case spv::ExecutionModeIsolines:
3257 case spv::ExecutionModeOutputLineStrip:
3258 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3259 break;
3260
3261 case spv::ExecutionModeTriangles:
3262 case spv::ExecutionModeQuads:
3263 case spv::ExecutionModeOutputTriangleStrip:
3264 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3265 break;
3266 }
3267 }
3268 }
3269
3270 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3271}
3272
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003273// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3274// o If there is only a vertex shader : gl_PointSize must be written when using points
3275// o If there is a geometry or tessellation shader:
3276// - If shaderTessellationAndGeometryPointSize feature is enabled:
3277// * gl_PointSize must be written in the final geometry stage
3278// - If shaderTessellationAndGeometryPointSize feature is disabled:
3279// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003280bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003281 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003282 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3283 return false;
3284 }
3285
3286 bool pointsize_written = false;
3287 bool skip = false;
3288
3289 // Search for PointSize built-in decorations
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003290 for (auto set : src->builtin_decoration_list) {
3291 auto insn = src->at(set.offset);
3292 if (set.builtin == spv::BuiltInPointSize) {
3293 pointsize_written = IsBuiltInWritten(src, insn, entrypoint);
3294 if (pointsize_written) {
3295 break;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003296 }
3297 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003298 }
3299
3300 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003301 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003302 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003303 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3304 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3305 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003306 }
3307 } else if (!pointsize_written) {
3308 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003309 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3310 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3311 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003312 }
3313 return skip;
3314}
John Zulauf14c355b2019-06-27 16:09:37 -06003315
Tobias Hector6663c9b2020-11-05 10:18:02 +00003316bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
3317 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
3318 bool primitiverate_written = false;
3319 bool viewportindex_written = false;
3320 bool viewportmask_written = false;
3321 bool skip = false;
3322
3323 // Check if the primitive shading rate is written
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003324 for (auto set : src->builtin_decoration_list) {
3325 auto insn = src->at(set.offset);
3326 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3327 primitiverate_written = IsBuiltInWritten(src, insn, entrypoint);
3328 } else if (set.builtin == spv::BuiltInViewportIndex) {
3329 viewportindex_written = IsBuiltInWritten(src, insn, entrypoint);
3330 } else if (set.builtin == spv::BuiltInViewportMaskNV) {
3331 viewportmask_written = IsBuiltInWritten(src, insn, entrypoint);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003332 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003333 if (primitiverate_written && viewportindex_written && viewportmask_written) {
3334 break;
3335 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003336 }
3337
Tony-LunarGd44844c2021-01-22 13:24:37 -07003338 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3339 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003340 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
3341 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003342 skip |= LogError(pipeline->pipeline,
3343 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
3344 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
3345 "multiple viewports "
3346 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3347 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003348 }
3349
3350 if (primitiverate_written && viewportindex_written) {
3351 skip |= LogError(pipeline->pipeline,
3352 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
3353 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3354 "ViewportIndex built-ins,"
3355 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3356 string_VkShaderStageFlagBits(stage));
3357 }
3358
3359 if (primitiverate_written && viewportmask_written) {
3360 skip |= LogError(pipeline->pipeline,
3361 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
3362 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
3363 "ViewportMaskNV built-ins,"
3364 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
3365 string_VkShaderStageFlagBits(stage));
3366 }
3367 }
3368 return skip;
3369}
3370
sfricke-samsung486a51e2021-01-02 00:10:15 -08003371// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08003372bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08003373 bool skip = false;
3374
sfricke-samsung94167ca2021-02-26 04:14:59 -08003375 switch (insn.opcode()) {
3376 case spv::OpReadClockKHR: {
3377 auto scope_id = module->get_def(insn.word(3));
3378 auto scope_type = scope_id.word(3);
3379 // if scope isn't Subgroup or Device, spirv-val will catch
3380 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
3381 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
3382 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
3383 report_data->FormatHandle(module->vk_shader_module).c_str());
3384 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
3385 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
3386 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
3387 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08003388 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08003389 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08003390 }
3391 }
3392 return skip;
3393}
3394
John Zulauf14c355b2019-06-27 16:09:37 -06003395bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3396 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003397 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003398 bool skip = false;
3399
3400 // Check the module
3401 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003402 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3403 "%s does not contain valid spirv for stage %s.",
3404 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003405 }
3406
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003407 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3408 // specializations should be applied and validated.
3409 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3410 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3411 // Gather the specialization-constant values.
3412 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003413 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003414 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3415 id_value_map.reserve(specialization_info->mapEntryCount);
3416 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3417 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003418
Jeremy Hayes521221d2020-01-15 16:48:49 -07003419 // Expect only scalar types.
3420 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3421 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3422 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003423 }
3424
3425 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003426 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003427 spvtools::Optimizer optimizer(spirv_environment);
3428 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3429 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003430 skip |= LogError(
3431 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003432 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3433 };
3434 optimizer.SetMessageConsumer(consumer);
3435 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3436 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3437 std::vector<uint32_t> specialized_spirv;
3438 auto const optimized =
3439 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3440 assert(optimized == true);
3441
3442 if (optimized) {
3443 spv_context ctx = spvContextCreate(spirv_environment);
3444 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3445 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003446 spvtools::ValidatorOptions options;
3447 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003448 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3449 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003450 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003451 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3452 report_data->FormatHandle(module->vk_shader_module).c_str(),
3453 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003454 }
3455
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003456 spvDiagnosticDestroy(diag);
3457 spvContextDestroy(ctx);
3458 }
3459 }
3460
John Zulauf14c355b2019-06-27 16:09:37 -06003461 // Check the entrypoint
3462 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003463 skip |=
3464 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3465 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003466 }
3467 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3468
3469 // Mark accessible ids
3470 auto &accessible_ids = stage_state.accessible_ids;
3471
Chris Forbes47567b72017-06-09 12:09:45 -07003472 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003473 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3474 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003475
sfricke-samsung94167ca2021-02-26 04:14:59 -08003476 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
3477 // and mainly only checking the instruction in detail for a single operation
3478 for (auto insn : *module) {
3479 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
3480 skip |= ValidatePropertiesAndFeatures(module, insn);
3481 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
3482 }
3483
locke-lunarg63e4daf2020-08-17 17:53:25 -06003484 skip |=
3485 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003486 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003487 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003488 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003489 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003490 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003491 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003492 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003493 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07003494 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
sfricke-samsungd093e522021-02-26 04:17:45 -08003495 if (enabled_features.cooperative_matrix_features.cooperativeMatrix) {
3496 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
3497 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003498 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
3499 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
3500 }
Chris Forbes47567b72017-06-09 12:09:45 -07003501
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003502 std::string vuid_layout_mismatch;
3503 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3504 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3505 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3506 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3507 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3508 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3509 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3510 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3511 }
3512
Chris Forbes47567b72017-06-09 12:09:45 -07003513 // Validate descriptor use
3514 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003515 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003516 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003517 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07003518 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
3519 std::set<uint32_t> descriptor_types =
3520 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07003521
3522 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003523 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003524 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3525 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003526 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003527 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003528 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3529 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003530 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003531 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003532 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3533 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3534 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003535 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003536 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003537 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3538 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003539 }
3540 }
3541
3542 // Validate use of input attachments against subpass structure
3543 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003544 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003545
Petr Krause91f7a12017-12-14 20:57:36 +01003546 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003547 auto subpass = pipeline->graphicsPipelineCI.subpass;
3548
3549 for (auto use : input_attachment_uses) {
3550 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3551 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003552 ? input_attachments[use.first].attachment
3553 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003554
3555 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003556 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3557 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003558 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003559 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003560 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3561 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3562 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003563 }
3564 }
3565 }
Lockeaa8fdc02019-04-02 11:59:20 -06003566 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
sfricke-samsung8a7341a2021-02-28 07:30:21 -08003567 skip |= ValidateComputeWorkGroupSizes(module, entrypoint);
Lockeaa8fdc02019-04-02 11:59:20 -06003568 }
Chris Forbes47567b72017-06-09 12:09:45 -07003569 return skip;
3570}
3571
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003572bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3573 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3574 spirv_inst_iter consumer_entrypoint,
3575 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003576 bool skip = false;
3577
3578 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003579 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3580 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003581
3582 auto a_it = outputs.begin();
3583 auto b_it = inputs.begin();
3584
3585 // Maps sorted by key (location); walk them together to find mismatches
3586 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3587 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3588 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3589 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3590 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3591
3592 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003593 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3594 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3595 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003596 a_it++;
3597 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003598 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3599 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3600 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003601 b_it++;
3602 } else {
3603 // subtleties of arrayed interfaces:
3604 // - if is_patch, then the member is not arrayed, even though the interface may be.
3605 // - if is_block_member, then the extra array level of an arrayed interface is not
3606 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003607 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3608 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3609 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003610 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3611 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3612 DescribeType(producer, a_it->second.type_id).c_str(),
3613 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003614 }
3615 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003616 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3617 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3618 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3619 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003620 }
3621 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003622 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3623 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3624 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003625 }
3626 a_it++;
3627 b_it++;
3628 }
3629 }
3630
Ari Suonpaa696b3432019-03-11 14:02:57 +02003631 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3632 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3633 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3634
3635 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3636 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003637 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3638 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003639 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
3640 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02003641 } else {
3642 auto it_producer = builtins_producer.begin();
3643 auto it_consumer = builtins_consumer.begin();
3644 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3645 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003646 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3647 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3648 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003649 break;
3650 }
3651 it_producer++;
3652 it_consumer++;
3653 }
3654 }
3655 }
3656 }
3657
Chris Forbes47567b72017-06-09 12:09:45 -07003658 return skip;
3659}
3660
John Zulauf14c355b2019-06-27 16:09:37 -06003661static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003662 uint32_t stage_mask = 0;
3663 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3664 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3665 stage_mask |= pCreateInfo->pStages[i].stage;
3666 }
3667 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003668 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3669 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3670 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003671 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3672 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3673 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3674 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3675 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003676 }
3677 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003678 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003679}
3680
Chris Forbes47567b72017-06-09 12:09:45 -07003681// Validate that the shaders used by the given pipeline and store the active_slots
3682// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003683bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003684 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003685 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3686 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003687
John Zulauf14c355b2019-06-27 16:09:37 -06003688 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003689 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003690 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003691 bool skip = false;
3692
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003693 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003694
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003695 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3696 auto stage = &create_info->pStages[i];
3697 auto stage_id = GetShaderStageId(stage->stage);
3698 shaders[stage_id] = GetShaderModuleState(stage->module);
3699 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
3700 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
3701 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003702 }
3703
3704 // if the shader stages are no good individually, cross-stage validation is pointless.
3705 if (skip) return true;
3706
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003707 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07003708
3709 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003710 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003711 }
3712
3713 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003714 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003715 }
3716
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003717 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3718 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003719
3720 while (!shaders[producer] && producer != fragment_stage) {
3721 producer++;
3722 consumer++;
3723 }
3724
3725 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3726 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003727 if (shaders[consumer]) {
3728 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003729 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3730 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003731 }
Chris Forbes47567b72017-06-09 12:09:45 -07003732
3733 producer = consumer;
3734 }
3735 }
3736
3737 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003738 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003739 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003740 }
3741
3742 return skip;
3743}
3744
Tony-LunarGb2ded512021-02-02 16:03:30 -07003745void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
3746 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
3747
3748 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
3749 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
3750 return;
3751 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00003752
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07003753 std::array<const SHADER_MODULE_STATE *, 32> shaders;
3754 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003755 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00003756
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003757 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3758 auto stage = &create_info->pStages[i];
3759 auto stage_id = GetShaderStageId(stage->stage);
3760 shaders[stage_id] = GetShaderModuleState(stage->module);
3761 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003762
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003763 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3764 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07003765 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00003766
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003767 for (auto set : shaders[stage_id]->builtin_decoration_list) {
3768 auto insn = shaders[stage_id]->at(set.offset);
3769 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
3770 primitiverate_written = IsBuiltInWritten(shaders[stage_id], insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00003771 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003772 if (primitiverate_written) {
3773 break;
3774 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07003775 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08003776
Tony-LunarGb2ded512021-02-02 16:03:30 -07003777 if (primitiverate_written) {
3778 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
3779 }
3780 }
3781 }
3782}
3783
3784bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
3785 const char *caller, const DrawDispatchVuid &vuid) const {
3786 auto create_info = pipeline->graphicsPipelineCI.ptr();
3787 bool skip = false;
3788
3789 for (uint32_t i = 0; i < create_info->stageCount; i++) {
3790 auto stage = &create_info->pStages[i];
3791 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
3792 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
3793 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
3794 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
3795 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00003796 skip |=
3797 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
3798 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
3799 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
3800 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003801 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00003802 }
3803 }
3804 }
3805 }
3806
3807 return skip;
3808}
3809
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003810bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003811 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003812
John Zulauf14c355b2019-06-27 16:09:37 -06003813 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3814 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003815
John Zulauf14c355b2019-06-27 16:09:37 -06003816 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003817}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003818
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003819uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
3820 uint32_t total = 0;
3821
3822 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3823 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
3824 if (stages[stage_index].stage == stageBit) {
3825 total++;
3826 }
3827 }
3828
3829 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3830 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
3831 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
3832 total += CalcShaderStageCount(library_pipeline, stageBit);
3833 }
3834 }
3835
3836 return total;
3837}
3838
sourav parmarcd5fb182020-07-17 12:58:44 -07003839bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003840 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003841
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003842 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003843 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
3844 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
3845 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
3846 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
3847 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
3848 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
3849 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003850 }
sourav parmarcd5fb182020-07-17 12:58:44 -07003851 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
3852 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003853 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07003854 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003855 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003856 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
3857 skip |= LogError(
3858 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
3859 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3860 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003861 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07003862 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
3863 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003864 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
3865 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003866 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003867 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07003868 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
3869 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
3870 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
3871 "member must have been created with values of the maxPipelineRayPayloadSize and "
3872 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
3873 }
3874 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003875 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07003876 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
3877 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
3878 "vkCreateRayTracingPipelinesKHR: If flags includes "
3879 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
3880 "the pLibraries member of libraries must have been created with the "
3881 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
3882 }
sourav parmar83c31b12020-05-06 12:30:54 -07003883 }
3884 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003885 } else {
3886 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07003887 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
3888 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
3889 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003890 pipeline->raytracingPipelineCI.maxRecursionDepth,
3891 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3892 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003893 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003894 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3895 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3896
John Zulaufe4474e72019-07-01 17:28:27 -06003897 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003898 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003899
John Zulaufe4474e72019-07-01 17:28:27 -06003900 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3901 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003902
John Zulaufe4474e72019-07-01 17:28:27 -06003903 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003904 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02003905
3906 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
3907 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
3908 if (raygen_stages_count == 0) {
3909 skip |= LogError(
3910 device,
3911 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3912 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
3913 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003914 }
3915
3916 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3917 const auto &group = groups[group_index];
3918
3919 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3920 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3921 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3922 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3923 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003924 skip |= LogError(device,
3925 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3926 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3927 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003928 }
3929 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3930 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003931 skip |= LogError(device,
3932 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3933 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3934 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003935 }
3936 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3937 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3938 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003939 skip |= LogError(device,
3940 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3941 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3942 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003943 }
3944 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3945 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003946 skip |= LogError(device,
3947 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3948 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3949 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003950 }
3951 }
3952
3953 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3954 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3955 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3956 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003957 skip |= LogError(device,
3958 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3959 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3960 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003961 }
3962 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3963 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3964 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003965 skip |= LogError(device,
3966 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3967 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3968 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003969 }
3970 }
John Zulaufe4474e72019-07-01 17:28:27 -06003971 }
3972 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003973}
3974
Dave Houltona9df0ce2018-02-07 10:51:23 -07003975uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003976
Dave Houltona9df0ce2018-02-07 10:51:23 -07003977static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07003978 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06003979 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003980 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003981 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003982 return nullptr;
3983}
3984
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003985bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003986 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003987 bool skip = false;
3988 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003989
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003990 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003991 return false;
3992 }
3993
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003994 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003995
3996 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003997 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3998 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3999 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004000 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07004001 auto cache = GetValidationCacheInfo(pCreateInfo);
4002 uint32_t hash = 0;
4003 if (cache) {
4004 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004005 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07004006 }
4007
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06004008 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
4009 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004010 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06004011 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07004012 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07004013 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004014 spvtools::ValidatorOptions options;
4015 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06004016 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07004017 if (spv_valid != SPV_SUCCESS) {
4018 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004019 if (spv_valid == SPV_WARNING) {
4020 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4021 diag && diag->error ? diag->error : "(no error text)");
4022 } else {
4023 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
4024 diag && diag->error ? diag->error : "(no error text)");
4025 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004026 }
Chris Forbes9a61e082017-07-24 15:35:29 -07004027 } else {
4028 if (cache) {
4029 cache->Insert(hash);
4030 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07004031 }
4032
4033 spvDiagnosticDestroy(diag);
4034 spvContextDestroy(ctx);
4035 }
4036
Chris Forbes4ae55b32017-06-09 14:42:56 -07004037 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07004038}
4039
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004040bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader, const spirv_inst_iter &entrypoint) const {
Lockeaa8fdc02019-04-02 11:59:20 -06004041 bool skip = false;
4042 uint32_t local_size_x = 0;
4043 uint32_t local_size_y = 0;
4044 uint32_t local_size_z = 0;
sfricke-samsung8a7341a2021-02-28 07:30:21 -08004045 if (FindLocalSize(shader, entrypoint, local_size_x, local_size_y, local_size_z)) {
Lockeaa8fdc02019-04-02 11:59:20 -06004046 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004047 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4048 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
4049 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4050 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06004051 }
4052 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004053 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4054 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
4055 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4056 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06004057 }
4058 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004059 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
4060 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4061 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4062 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004063 }
4064
4065 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4066 uint64_t invocations = local_size_x * local_size_y;
4067 // Prevent overflow.
4068 bool fail = false;
4069 if (invocations > UINT32_MAX || invocations > limit) {
4070 fail = true;
4071 }
4072 if (!fail) {
4073 invocations *= local_size_z;
4074 if (invocations > UINT32_MAX || invocations > limit) {
4075 fail = true;
4076 }
4077 }
4078 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004079 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4080 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4081 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4082 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4083 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004084 }
4085 }
4086 return skip;
4087}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004088
4089spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4090 if (api_version >= VK_API_VERSION_1_2) {
4091 return SPV_ENV_VULKAN_1_2;
4092 } else if (api_version >= VK_API_VERSION_1_1) {
4093 if (spirv_1_4) {
4094 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4095 } else {
4096 return SPV_ENV_VULKAN_1_1;
4097 }
4098 }
4099 return SPV_ENV_VULKAN_1_0;
4100}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004101
4102void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4103 spvtools::ValidatorOptions &options) {
4104 if (device_extensions.vk_khr_relaxed_block_layout) {
4105 options.SetRelaxBlockLayout(true);
4106 }
4107 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4108 options.SetUniformBufferStandardLayout(true);
4109 }
4110 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4111 options.SetScalarBlockLayout(true);
4112 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08004113 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
4114 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
4115 options.SetWorkgroupScalarBlockLayout(true);
4116 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004117}