blob: f9010a97eb30865c8eef59cc2dec76b58976197d [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>
Petr Kraus25810d02019-08-27 17:41:15 +020027#include <cinttypes>
Jeff Bolzf234bf82019-11-04 14:07:15 -060028#include <cmath>
Chris Forbes47567b72017-06-09 12:09:45 -070029#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <string>
Petr Kraus25810d02019-08-27 17:41:15 +020031#include <vector>
32
Mark Lobodzinski102687e2020-04-28 11:03:28 -060033#include <spirv/unified1/spirv.hpp>
Chris Forbes47567b72017-06-09 12:09:45 -070034#include "vk_enum_string_helper.h"
Chris Forbes47567b72017-06-09 12:09:45 -070035#include "vk_layer_data.h"
Chris Forbes47567b72017-06-09 12:09:45 -070036#include "vk_layer_utils.h"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070037#include "chassis.h"
Chris Forbes47567b72017-06-09 12:09:45 -070038#include "core_validation.h"
Petr Kraus25810d02019-08-27 17:41:15 +020039
Chris Forbes9a61e082017-07-24 15:35:29 -070040#include "xxhash.h"
Chris Forbes47567b72017-06-09 12:09:45 -070041
Chris Forbes47567b72017-06-09 12:09:45 -070042static shader_stage_attributes shader_stage_attribs[] = {
Ari Suonpaa696b3432019-03-11 14:02:57 +020043 {"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
44 {"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
45 {"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
46 {"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
47 {"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
Chris Forbes47567b72017-06-09 12:09:45 -070048};
49
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060050static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -070051 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
52 return type.word(2) < 64;
53}
54
Mark Lobodzinski3c59d972019-04-25 11:28:14 -060055static 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 -060056 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -070057 // Walk two type trees together, and complain about differences
58 auto a_insn = a->get_def(a_type);
59 auto b_insn = b->get_def(b_type);
60 assert(a_insn != a->end());
61 assert(b_insn != b->end());
62
Chris Forbes062f1222018-08-21 15:34:15 -070063 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
64
Chris Forbes47567b72017-06-09 12:09:45 -070065 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060066 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -070067 }
68
69 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
70 // 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 -060071 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -070072 }
73
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060074 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
75 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -070076 }
77
78 if (a_insn.opcode() != b_insn.opcode()) {
79 return false;
80 }
81
82 if (a_insn.opcode() == spv::OpTypePointer) {
83 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -060084 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -070085 }
86
87 if (a_arrayed || b_arrayed) {
88 // If we havent resolved array-of-verts by here, we're not going to.
89 return false;
90 }
91
92 switch (a_insn.opcode()) {
93 case spv::OpTypeBool:
94 return true;
95 case spv::OpTypeInt:
96 // Match on width, signedness
97 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
98 case spv::OpTypeFloat:
99 // Match on width
100 return a_insn.word(2) == b_insn.word(2);
101 case spv::OpTypeVector:
102 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600103 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
104 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700105 return a_insn.word(3) >= b_insn.word(3);
106 } else {
107 return a_insn.word(3) == b_insn.word(3);
108 }
109 case spv::OpTypeMatrix:
110 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600111 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700112 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700113 case spv::OpTypeArray:
114 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
115 // 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 -0600116 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
sfricke-samsung962cad92021-04-13 00:46:29 -0700117 a->GetConstantValueById(a_insn.word(3)) == b->GetConstantValueById(b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700118 case spv::OpTypeStruct:
119 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700120 {
121 if (a_insn.len() != b_insn.len()) {
122 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700123 }
Chris Forbes47567b72017-06-09 12:09:45 -0700124
Dave Houltona9df0ce2018-02-07 10:51:23 -0700125 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600126 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700127 return false;
128 }
129 }
130
131 return true;
132 }
Chris Forbes47567b72017-06-09 12:09:45 -0700133 default:
134 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
135 return false;
136 }
137}
138
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600139static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700140 switch (format) {
141 case VK_FORMAT_R64G64B64A64_SFLOAT:
142 case VK_FORMAT_R64G64B64A64_SINT:
143 case VK_FORMAT_R64G64B64A64_UINT:
144 case VK_FORMAT_R64G64B64_SFLOAT:
145 case VK_FORMAT_R64G64B64_SINT:
146 case VK_FORMAT_R64G64B64_UINT:
147 return 2;
148 default:
149 return 1;
150 }
151}
152
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600153static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700154 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
155 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
156 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
157 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700158 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
159 return FORMAT_TYPE_FLOAT;
160}
161
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600162static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700163 uint32_t bit_pos = uint32_t(u_ffs(stage));
164 return bit_pos - 1;
165}
166
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700167bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700168 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
169 // be specified only once.
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700170 layer_data::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
Chris Forbes47567b72017-06-09 12:09:45 -0700171 bool skip = false;
172
173 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
174 auto desc = &vi->pVertexBindingDescriptions[i];
175 auto &binding = bindings[desc->binding];
176 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -0600177 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700178 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
179 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -0700180 } else {
181 binding = desc;
182 }
183 }
184
185 return skip;
186}
187
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700188bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
189 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700190 bool skip = false;
191
sfricke-samsung962cad92021-04-13 00:46:29 -0700192 const auto inputs = vs->CollectInterfaceByLocation(entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700193
194 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +0200195 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -0700196 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +0200197 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
198 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
199 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -0700200 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
201 }
202 }
203 }
204
Petr Kraus25810d02019-08-27 17:41:15 +0200205 struct AttribInputPair {
206 const VkVertexInputAttributeDescription *attrib = nullptr;
207 const interface_var *input = nullptr;
208 };
209 std::map<uint32_t, AttribInputPair> location_map;
210 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
211 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -0700212
Jamie Madillc1f7ca82020-03-16 17:08:26 -0400213 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +0200214 const auto location = location_it.first;
215 const auto attrib = location_it.second.attrib;
216 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -0600217
Petr Kraus25810d02019-08-27 17:41:15 +0200218 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700219 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
220 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +0200221 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700222 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
223 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +0200224 } else if (attrib && input) {
225 const auto attrib_type = GetFormatType(attrib->format);
sfricke-samsung962cad92021-04-13 00:46:29 -0700226 const auto input_type = vs->GetFundamentalType(input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700227
228 // Type checking
229 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700230 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
231 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
sfricke-samsung962cad92021-04-13 00:46:29 -0700232 string_VkFormat(attrib->format), location, vs->DescribeType(input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700233 }
Petr Kraus25810d02019-08-27 17:41:15 +0200234 } else { // !attrib && !input
235 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -0700236 }
237 }
238
239 return skip;
240}
241
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700242bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
243 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +0200244 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -0700245
Petr Kraus25810d02019-08-27 17:41:15 +0200246 const auto rpci = pipeline->rp_state->createInfo.ptr();
247
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600248 struct Attachment {
Mike Schuchardt2df08912020-12-15 16:28:09 -0800249 const VkAttachmentReference2 *reference = nullptr;
250 const VkAttachmentDescription2 *attachment = nullptr;
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600251 const interface_var *output = nullptr;
252 };
253 std::map<uint32_t, Attachment> location_map;
254
Petr Kraus25810d02019-08-27 17:41:15 +0200255 const auto subpass = rpci->pSubpasses[subpass_index];
256 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600257 auto const &reference = subpass.pColorAttachments[i];
258 location_map[i].reference = &reference;
259 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
260 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
261 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -0700262 }
263 }
264
Chris Forbes47567b72017-06-09 12:09:45 -0700265 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
266
sfricke-samsung962cad92021-04-13 00:46:29 -0700267 const auto outputs = fs->CollectInterfaceByLocation(entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600268 for (const auto &output_it : outputs) {
269 auto const location = output_it.first.first;
270 location_map[location].output = &output_it.second;
271 }
Chris Forbes47567b72017-06-09 12:09:45 -0700272
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700273 const bool alpha_to_coverage_enabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
274 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -0700275
Jamie Madillc1f7ca82020-03-16 17:08:26 -0400276 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -0600277 const auto reference = location_it.second.reference;
278 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
279 continue;
280 }
281
Petr Kraus25810d02019-08-27 17:41:15 +0200282 const auto location = location_it.first;
283 const auto attachment = location_it.second.attachment;
284 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +0200285 if (attachment && !output) {
286 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700287 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
288 "Attachment %" PRIu32
289 " not written by fragment shader; undefined values will be written to attachment",
290 location);
Petr Kraus25810d02019-08-27 17:41:15 +0200291 }
292 } else if (!attachment && output) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700293 if (!(alpha_to_coverage_enabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700294 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
295 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200296 }
Petr Kraus25810d02019-08-27 17:41:15 +0200297 } else if (attachment && output) {
298 const auto attachment_type = GetFormatType(attachment->format);
sfricke-samsung962cad92021-04-13 00:46:29 -0700299 const auto output_type = fs->GetFundamentalType(output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -0700300
301 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +0200302 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700303 skip |=
304 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
305 "Attachment %" PRIu32
306 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
sfricke-samsung962cad92021-04-13 00:46:29 -0700307 location, string_VkFormat(attachment->format), fs->DescribeType(output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700308 }
Petr Kraus25810d02019-08-27 17:41:15 +0200309 } else { // !attachment && !output
310 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -0700311 }
312 }
313
Petr Kraus25810d02019-08-27 17:41:15 +0200314 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700315 bool location_zero_has_alpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
sfricke-samsung962cad92021-04-13 00:46:29 -0700316 fs->GetComponentsConsumedByType(output_zero->type_id, false) == 4;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700317 if (alpha_to_coverage_enabled && !location_zero_has_alpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700318 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
319 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +0200320 }
321
Chris Forbes47567b72017-06-09 12:09:45 -0700322 return skip;
323}
324
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600325PushConstantByteState CoreChecks::ValidatePushConstantSetUpdate(const std::vector<uint8_t> &push_constant_data_update,
326 const shader_struct_member &push_constant_used_in_shader,
327 uint32_t &out_issue_index) const {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600328 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600329 const auto used_bytes_size = used_bytes->size();
330 if (used_bytes_size == 0) return PC_Byte_Updated;
331
332 const auto push_constant_data_update_size = push_constant_data_update.size();
333 const auto *data = push_constant_data_update.data();
334 if ((*data == PC_Byte_Updated) && std::memcmp(data, data + 1, push_constant_data_update_size - 1) == 0) {
335 if (used_bytes_size <= push_constant_data_update_size) {
336 return PC_Byte_Updated;
337 }
338 const auto used_bytes_size1 = used_bytes_size - push_constant_data_update_size;
339
340 const auto *used_bytes_data1 = used_bytes->data() + push_constant_data_update_size;
341 if ((*used_bytes_data1 == 0) && std::memcmp(used_bytes_data1, used_bytes_data1 + 1, used_bytes_size1 - 1) == 0) {
342 return PC_Byte_Updated;
343 }
locke-lunargde3f0fa2020-09-10 11:55:31 -0600344 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600345
locke-lunargde3f0fa2020-09-10 11:55:31 -0600346 uint32_t i = 0;
347 for (const auto used : *used_bytes) {
348 if (used) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600349 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600350 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600351 return PC_Byte_Not_Set;
352 } else if (push_constant_data_update[i] == PC_Byte_Not_Updated) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600353 out_issue_index = i;
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600354 return PC_Byte_Not_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -0600355 }
356 }
357 ++i;
358 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600359 return PC_Byte_Updated;
locke-lunargde3f0fa2020-09-10 11:55:31 -0600360}
361
362bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
sfricke-samsung7699b912021-04-12 23:01:51 -0700363 VkPipelineShaderStageCreateInfo const *pStage, const std::string &vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700364 bool skip = false;
sfricke-samsung5c65b372021-03-25 05:39:57 -0700365 // Temp workaround to prevent false positive errors
366 // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/2450
367 if (src->multiple_entry_points) {
368 return skip;
369 }
370
Chris Forbes47567b72017-06-09 12:09:45 -0700371 // Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
sfricke-samsung962cad92021-04-13 00:46:29 -0700372 const auto *entrypoint = src->FindEntrypointStruct(pStage->pName, pStage->stage);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600373 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
374 return skip;
375 }
376 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -0700377
locke-lunargde3f0fa2020-09-10 11:55:31 -0600378 bool found_stage = false;
379 for (auto const &range : *push_constant_ranges) {
380 if (range.stageFlags & pStage->stage) {
381 found_stage = true;
382 std::string location_desc;
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600383 std::vector<uint8_t> push_constant_bytes_set;
locke-lunargde3f0fa2020-09-10 11:55:31 -0600384 if (range.offset > 0) {
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600385 push_constant_bytes_set.resize(range.offset, PC_Byte_Not_Set);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600386 }
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600387 push_constant_bytes_set.resize(range.offset + range.size, PC_Byte_Updated);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600388 uint32_t issue_index = 0;
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600389 const auto ret =
390 ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -0700391
locke-lunarg3d8b8f32020-10-26 17:04:16 -0600392 if (ret == PC_Byte_Not_Set) {
locke-lunargde3f0fa2020-09-10 11:55:31 -0600393 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
394 LogObjectList objlist(src->vk_shader_module);
395 objlist.add(pipeline.pipeline_layout->layout);
sfricke-samsung7699b912021-04-12 23:01:51 -0700396 skip |= LogError(objlist, vuid, "Push constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
locke-lunargde3f0fa2020-09-10 11:55:31 -0600397 string_VkShaderStageFlags(pStage->stage).c_str(),
398 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
399 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700400 }
401 }
402 }
403
locke-lunargde3f0fa2020-09-10 11:55:31 -0600404 if (!found_stage) {
405 LogObjectList objlist(src->vk_shader_module);
406 objlist.add(pipeline.pipeline_layout->layout);
sfricke-samsung7699b912021-04-12 23:01:51 -0700407 skip |= LogError(objlist, vuid, "Push constant is used in %s of %s. But %s doesn't set %s.",
408 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
409 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(),
410 string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -0700411 }
Chris Forbes47567b72017-06-09 12:09:45 -0700412 return skip;
413}
414
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700415bool CoreChecks::ValidateBuiltinLimits(SHADER_MODULE_STATE const *src, const layer_data::unordered_set<uint32_t> &accessible_ids,
sfricke-samsungef2a68c2020-10-26 04:22:46 -0700416 VkShaderStageFlagBits stage) const {
417 bool skip = false;
418
419 // Currently all builtin tested are only found in fragment shaders
420 if (stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
421 return skip;
422 }
423
424 for (const auto id : accessible_ids) {
425 auto insn = src->get_def(id);
426 const decoration_set decorations = src->get_decorations(insn.word(2));
427
428 // Built-ins are obtained from OpVariable
429 if (((decorations.flags & decoration_set::builtin_bit) != 0) && (insn.opcode() == spv::OpVariable)) {
430 auto type_pointer = src->get_def(insn.word(1));
431 assert(type_pointer.opcode() == spv::OpTypePointer);
432
433 auto type = src->get_def(type_pointer.word(3));
434 if (type.opcode() == spv::OpTypeArray) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700435 uint32_t length = static_cast<uint32_t>(src->GetConstantValueById(type.word(3)));
sfricke-samsungef2a68c2020-10-26 04:22:46 -0700436
437 switch (decorations.builtin) {
438 case spv::BuiltInSampleMask:
439 // Handles both the input and output sampleMask
440 if (length > phys_dev_props.limits.maxSampleMaskWords) {
441 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-maxSampleMaskWords-00711",
442 "vkCreateGraphicsPipelines(): The BuiltIns SampleMask array sizes is %u which exceeds "
443 "maxSampleMaskWords of %u in %s.",
444 length, phys_dev_props.limits.maxSampleMaskWords,
445 report_data->FormatHandle(src->vk_shader_module).c_str());
446 }
447 break;
448 }
449 }
450 }
451 }
452
453 return skip;
454}
455
Chris Forbes47567b72017-06-09 12:09:45 -0700456// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -0700457bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700458 bool skip = false;
459
460 VkSpecializationInfo const *spec = info->pSpecializationInfo;
461
462 if (spec) {
463 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -0600464 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700465 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
466 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
467 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
468 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
469 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -0600470
471 continue;
472 }
Chris Forbes47567b72017-06-09 12:09:45 -0700473 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700474 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
475 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
476 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
477 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
478 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -0700479 }
480 }
481 }
482
483 return skip;
484}
485
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500486// TODO (jbolz): Can this return a const reference?
sourav parmarcd5fb182020-07-17 12:58:44 -0700487static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count,
488 bool is_khr) {
Chris Forbes47567b72017-06-09 12:09:45 -0700489 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -0800490 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -0700491 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -0500492 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700493
494 // 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 -0500495 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
496 if (type.opcode() == spv::OpTypeRuntimeArray) {
497 descriptor_count = 0;
498 type = module->get_def(type.word(2));
499 } else if (type.opcode() == spv::OpTypeArray) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700500 descriptor_count *= module->GetConstantValueById(type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700501 type = module->get_def(type.word(2));
502 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -0800503 if (type.word(2) == spv::StorageClassStorageBuffer) {
504 is_storage_buffer = true;
505 }
Chris Forbes47567b72017-06-09 12:09:45 -0700506 type = module->get_def(type.word(3));
507 }
508 }
509
510 switch (type.opcode()) {
511 case spv::OpTypeStruct: {
sfricke-samsung94d71a52021-02-26 05:25:43 -0800512 for (auto insn : module->decoration_inst) {
513 if (insn.word(1) == type.word(1)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700514 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -0800515 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -0500516 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
517 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
518 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -0800519 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -0500520 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
521 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
522 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
523 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -0800524 }
Chris Forbes47567b72017-06-09 12:09:45 -0700525 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -0500526 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
527 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
528 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700529 }
530 }
531 }
532
533 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -0500534 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700535 }
536
537 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -0500538 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
539 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
540 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700541
Chris Forbes73c00bf2018-06-22 16:28:06 -0700542 case spv::OpTypeSampledImage: {
543 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
544 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
545 auto image_type = module->get_def(type.word(2));
546 auto dim = image_type.word(3);
547 auto sampled = image_type.word(7);
548 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -0500549 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
550 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700551 }
Chris Forbes73c00bf2018-06-22 16:28:06 -0700552 }
Jeff Bolze54ae892018-09-08 12:16:29 -0500553 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
554 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700555
556 case spv::OpTypeImage: {
557 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
558 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
559 auto dim = type.word(3);
560 auto sampled = type.word(7);
561
562 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -0500563 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
564 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700565 } else if (dim == spv::DimBuffer) {
566 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -0500567 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
568 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700569 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -0500570 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
571 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700572 }
573 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -0500574 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
575 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
576 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700577 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -0500578 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
579 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700580 }
581 }
Shannon McPherson0fa28232018-11-01 11:59:02 -0600582 case spv::OpTypeAccelerationStructureNV:
sourav parmarcd5fb182020-07-17 12:58:44 -0700583 is_khr ? ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR)
584 : ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -0500585 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -0700586
587 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
588 default:
Jeff Bolze54ae892018-09-08 12:16:29 -0500589 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -0700590 }
591}
592
Jeff Bolze54ae892018-09-08 12:16:29 -0500593static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -0700594 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -0500595 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
596 if (ss.tellp()) ss << ", ";
597 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -0700598 }
599 return ss.str();
600}
601
sfricke-samsung0065ce02020-12-03 22:46:37 -0800602bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure, const char *vuid) const {
Jeff Bolzee743412019-06-20 22:24:32 -0500603 if (!check) {
sfricke-samsung0065ce02020-12-03 22:46:37 -0800604 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 -0500605 return true;
606 }
607 }
608
609 return false;
610}
611
sfricke-samsung0065ce02020-12-03 22:46:37 -0800612bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name, const char *vuid) const {
Chris Forbes47567b72017-06-09 12:09:45 -0700613 if (!feature) {
sfricke-samsung0065ce02020-12-03 22:46:37 -0800614 if (LogError(device, vuid, "Shader requires %s but is not enabled on the device", feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700615 return true;
616 }
617 }
618
619 return false;
620}
621
locke-lunarg63e4daf2020-08-17 17:53:25 -0600622bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
623 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -0500624 bool skip = false;
625
locke-lunarg63e4daf2020-08-17 17:53:25 -0600626 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -0800627 switch (stage) {
628 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -0600629 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
630 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
631 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
632 case VK_SHADER_STAGE_MISS_BIT_NV:
633 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
634 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
635 case VK_SHADER_STAGE_TASK_BIT_NV:
636 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -0800637 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -0600638 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -0800639 break;
640 case VK_SHADER_STAGE_FRAGMENT_BIT:
sfricke-samsung0065ce02020-12-03 22:46:37 -0800641 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics",
642 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -0800643 break;
644 default:
sfricke-samsung0065ce02020-12-03 22:46:37 -0800645 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics",
646 kVUID_Core_Shader_FeatureNotEnabled);
Chris Forbes349b3132018-03-07 11:38:08 -0800647 break;
648 }
649 }
650
Chris Forbes47567b72017-06-09 12:09:45 -0700651 return skip;
652}
653
sfricke-samsung94167ca2021-02-26 04:14:59 -0800654bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
655 spirv_inst_iter &insn) const {
Jeff Bolzee743412019-06-20 22:24:32 -0500656 bool skip = false;
657
sfricke-samsung94167ca2021-02-26 04:14:59 -0800658 // Check anything using a group operation (which currently is only OpGroupNonUnifrom* operations)
659 if (GroupOperation(insn.opcode()) == true) {
660 // Check the quad operations.
661 if ((insn.opcode() == spv::OpGroupNonUniformQuadBroadcast) || (insn.opcode() == spv::OpGroupNonUniformQuadSwap)) {
662 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
663 skip |= RequireFeature(phys_dev_props_core11.subgroupQuadOperationsInAllStages,
664 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages",
665 kVUID_Core_Shader_FeatureNotEnabled);
sfricke-samsung0065ce02020-12-03 22:46:37 -0800666 }
sfricke-samsung94167ca2021-02-26 04:14:59 -0800667 }
Jeff Bolz526f2d52019-09-18 13:18:08 -0500668
sfricke-samsung94167ca2021-02-26 04:14:59 -0800669 uint32_t scope_type = spv::ScopeMax;
670 if (insn.opcode() == spv::OpGroupNonUniformPartitionNV) {
671 // OpGroupNonUniformPartitionNV always assumed subgroup as missing operand
672 scope_type = spv::ScopeSubgroup;
673 } else {
674 // "All <id> used for Scope <id> must be of an OpConstant"
675 auto scope_id = module->get_def(insn.word(3));
676 scope_type = scope_id.word(3);
677 }
sfricke-samsung0065ce02020-12-03 22:46:37 -0800678
sfricke-samsung94167ca2021-02-26 04:14:59 -0800679 if (scope_type == spv::ScopeSubgroup) {
680 // "Group operations with subgroup scope" must have stage support
681 const VkSubgroupFeatureFlags supported_stages = phys_dev_props_core11.subgroupSupportedStages;
682 skip |= RequirePropertyFlag(supported_stages & stage, string_VkShaderStageFlagBits(stage),
sfricke-samsung0065ce02020-12-03 22:46:37 -0800683 "VkPhysicalDeviceSubgroupProperties::supportedStages", kVUID_Core_Shader_ExceedDeviceLimit);
sfricke-samsung94167ca2021-02-26 04:14:59 -0800684 }
685
686 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
687 auto type = module->get_def(insn.word(1));
688
689 if (type.opcode() == spv::OpTypeVector) {
690 // Get the element type
691 type = module->get_def(type.word(2));
sfricke-samsung0065ce02020-12-03 22:46:37 -0800692 }
693
sfricke-samsung94167ca2021-02-26 04:14:59 -0800694 if (type.opcode() != spv::OpTypeBool) {
sfricke-samsung0065ce02020-12-03 22:46:37 -0800695 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
696 const uint32_t width = type.word(2);
Jeff Bolz526f2d52019-09-18 13:18:08 -0500697
sfricke-samsung0065ce02020-12-03 22:46:37 -0800698 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
699 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
700 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
701 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes",
702 kVUID_Core_Shader_FeatureNotEnabled);
Jeff Bolz526f2d52019-09-18 13:18:08 -0500703 }
704 }
705 }
Jeff Bolzee743412019-06-20 22:24:32 -0500706 }
707
708 return skip;
709}
710
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600711bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -0600712 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200713 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
714 pStage->stage == VK_SHADER_STAGE_ALL) {
715 return false;
716 }
717
718 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -0700719 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200720
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700721 std::set<uint32_t> patch_i_ds;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200722 struct Variable {
723 uint32_t baseTypePtrID;
724 uint32_t ID;
725 uint32_t storageClass;
726 };
727 std::vector<Variable> variables;
728
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700729 uint32_t num_vertices = 0;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -0700730 bool is_iso_lines = false;
731 bool is_point_mode = false;
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500732
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700733 auto entrypoint_variables = FindEntrypointInterfaces(entrypoint);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600734
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200735 for (auto insn : *src) {
736 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500737 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200738 case spv::OpDecorate:
739 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500740 case spv::DecorationPatch: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700741 patch_i_ds.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200742 break;
743 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200744 default:
745 break;
746 }
747 break;
748 // Find all input and output variables
749 case spv::OpVariable: {
750 Variable var = {};
751 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600752 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
753 // Only include variables in the entrypoint's interface
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700754 find(entrypoint_variables.begin(), entrypoint_variables.end(), insn.word(2)) != entrypoint_variables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200755 var.baseTypePtrID = insn.word(1);
756 var.ID = insn.word(2);
757 variables.push_back(var);
758 }
759 break;
760 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500761 case spv::OpExecutionMode:
762 if (insn.word(1) == entrypoint.word(2)) {
763 switch (insn.word(2)) {
764 default:
765 break;
766 case spv::ExecutionModeOutputVertices:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700767 num_vertices = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500768 break;
Nathaniel Cesario75fb7222020-12-07 10:54:53 -0700769 case spv::ExecutionModeIsolines:
770 is_iso_lines = true;
771 break;
772 case spv::ExecutionModePointMode:
773 is_point_mode = true;
774 break;
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500775 }
776 }
777 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200778 default:
779 break;
780 }
781 }
782
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500783 bool strip_output_array_level =
784 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
785 bool strip_input_array_level =
786 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
787 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
788
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700789 uint32_t num_comp_in = 0, num_comp_out = 0;
790 int max_comp_in = 0, max_comp_out = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -0600791
sfricke-samsung962cad92021-04-13 00:46:29 -0700792 auto inputs = src->CollectInterfaceByLocation(entrypoint, spv::StorageClassInput, strip_input_array_level);
793 auto outputs = src->CollectInterfaceByLocation(entrypoint, spv::StorageClassOutput, strip_output_array_level);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600794
795 // Find max component location used for input variables.
796 for (auto &var : inputs) {
797 int location = var.first.first;
798 int component = var.first.second;
799 interface_var &iv = var.second;
800
801 // Only need to look at the first location, since we use the type's whole size
802 if (iv.offset != 0) {
803 continue;
804 }
805
806 if (iv.is_patch) {
807 continue;
808 }
809
sfricke-samsung962cad92021-04-13 00:46:29 -0700810 int num_components = src->GetComponentsConsumedByType(iv.type_id, strip_input_array_level);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700811 max_comp_in = std::max(max_comp_in, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600812 }
813
814 // Find max component location used for output variables.
815 for (auto &var : outputs) {
816 int location = var.first.first;
817 int component = var.first.second;
818 interface_var &iv = var.second;
819
820 // Only need to look at the first location, since we use the type's whole size
821 if (iv.offset != 0) {
822 continue;
823 }
824
825 if (iv.is_patch) {
826 continue;
827 }
828
sfricke-samsung962cad92021-04-13 00:46:29 -0700829 int num_components = src->GetComponentsConsumedByType(iv.type_id, strip_output_array_level);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700830 max_comp_out = std::max(max_comp_out, location * 4 + component + num_components);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600831 }
832
833 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
834 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200835 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500836 // Check if the variable is a patch. Patches can also be members of blocks,
837 // but if they are then the top-level arrayness has already been stripped
838 // by the time GetComponentsConsumedByType gets to it.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700839 bool is_patch = patch_i_ds.find(var.ID) != patch_i_ds.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200840
841 if (var.storageClass == spv::StorageClassInput) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700842 num_comp_in += src->GetComponentsConsumedByType(var.baseTypePtrID, strip_input_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200843 } else { // var.storageClass == spv::StorageClassOutput
sfricke-samsung962cad92021-04-13 00:46:29 -0700844 num_comp_out += src->GetComponentsConsumedByType(var.baseTypePtrID, strip_output_array_level && !is_patch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200845 }
846 }
847
848 switch (pStage->stage) {
849 case VK_SHADER_STAGE_VERTEX_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700850 if (num_comp_out > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700851 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
852 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
853 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
854 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700855 limits.maxVertexOutputComponents, num_comp_out - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200856 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700857 if (max_comp_out > static_cast<int>(limits.maxVertexOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700858 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
859 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
860 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
861 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600862 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200863 break;
864
865 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700866 if (num_comp_in > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700867 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
868 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
869 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
870 "components by %u components",
871 limits.maxTessellationControlPerVertexInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700872 num_comp_in - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200873 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700874 if (max_comp_in > static_cast<int>(limits.maxTessellationControlPerVertexInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -0600875 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700876 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
877 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
878 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
879 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600880 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700881 if (num_comp_out > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700882 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
883 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
884 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
885 "components by %u components",
886 limits.maxTessellationControlPerVertexOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700887 num_comp_out - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200888 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700889 if (max_comp_out > static_cast<int>(limits.maxTessellationControlPerVertexOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -0600890 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700891 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
892 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
893 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
894 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600895 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200896 break;
897
898 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700899 if (num_comp_in > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700900 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
901 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
902 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
903 "components by %u components",
904 limits.maxTessellationEvaluationInputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700905 num_comp_in - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200906 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700907 if (max_comp_in > static_cast<int>(limits.maxTessellationEvaluationInputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -0600908 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700909 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
910 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
911 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
912 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600913 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700914 if (num_comp_out > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700915 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
916 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
917 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
918 "components by %u components",
919 limits.maxTessellationEvaluationOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700920 num_comp_out - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200921 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700922 if (max_comp_out > static_cast<int>(limits.maxTessellationEvaluationOutputComponents)) {
Jeff Bolzf234bf82019-11-04 14:07:15 -0600923 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700924 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
925 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
926 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
927 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600928 }
Nathaniel Cesario75fb7222020-12-07 10:54:53 -0700929 // Portability validation
930 if (IsExtEnabled(device_extensions.vk_khr_portability_subset)) {
931 if (is_iso_lines && (VK_FALSE == enabled_features.portability_subset_features.tessellationIsolines)) {
932 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_Isolines,
933 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
934 " is using abstract patch type IsoLines, but this is not supported on this platform");
935 }
936 if (is_point_mode && (VK_FALSE == enabled_features.portability_subset_features.tessellationPointMode)) {
937 skip |= LogError(pipeline->pipeline, kVUID_Portability_Tessellation_PointMode,
938 "Invalid Pipeline CreateInfo state (portability error): Tessellation evaluation shader"
939 " is using abstract patch type PointMode, but this is not supported on this platform");
940 }
941 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200942 break;
943
944 case VK_SHADER_STAGE_GEOMETRY_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700945 if (num_comp_in > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700946 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
947 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
948 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
949 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700950 limits.maxGeometryInputComponents, num_comp_in - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200951 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700952 if (max_comp_in > static_cast<int>(limits.maxGeometryInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700953 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
954 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
955 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
956 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600957 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700958 if (num_comp_out > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700959 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
960 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
961 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
962 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700963 limits.maxGeometryOutputComponents, num_comp_out - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200964 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700965 if (max_comp_out > static_cast<int>(limits.maxGeometryOutputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700966 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
967 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
968 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
969 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600970 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700971 if (num_comp_out * num_vertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700972 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
973 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
974 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
975 "components by %u components",
976 limits.maxGeometryTotalOutputComponents,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700977 num_comp_out * num_vertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500978 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200979 break;
980
981 case VK_SHADER_STAGE_FRAGMENT_BIT:
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700982 if (num_comp_in > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700983 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
984 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
985 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
986 "components by %u components",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700987 limits.maxFragmentInputComponents, num_comp_in - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200988 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700989 if (max_comp_in > static_cast<int>(limits.maxFragmentInputComponents)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -0700990 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
991 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
992 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
993 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -0600994 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200995 break;
996
Jeff Bolz148d94e2018-12-13 21:25:56 -0600997 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
998 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
999 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
1000 case VK_SHADER_STAGE_MISS_BIT_NV:
1001 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
1002 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
1003 case VK_SHADER_STAGE_TASK_BIT_NV:
1004 case VK_SHADER_STAGE_MESH_BIT_NV:
1005 break;
1006
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02001007 default:
1008 assert(false); // This should never happen
1009 }
1010 return skip;
1011}
1012
sfricke-samsungdc96f302020-03-18 20:42:10 -07001013bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
1014 bool skip = false;
1015 uint32_t total_resources = 0;
1016
1017 // Only currently testing for graphics and compute pipelines
1018 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
1019 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
1020 return false;
1021 }
1022
1023 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
1024 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
1025 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
1026 }
1027
1028 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
1029 // input from CreatePipeline and CreatePipelineLayout level
1030 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
1031 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
1032 continue;
1033 }
1034
1035 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
1036 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
1037 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
1038 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
1039 // Check only descriptor types listed in maxPerStageResources description in spec
1040 switch (binding->descriptorType) {
1041 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
1042 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
1043 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
1044 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
1045 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
1046 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
1047 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
1048 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
1049 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
1050 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
1051 total_resources += binding->descriptorCount;
1052 break;
1053 default:
1054 break;
1055 }
1056 }
1057 }
1058 }
1059
1060 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
1061 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
1062 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
1063 skip |= LogError(pipeline->pipeline, vuid,
1064 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
1065 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
1066 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
1067 }
1068
1069 return skip;
1070}
1071
Jeff Bolze4356752019-03-07 11:23:46 -06001072// copy the specialization constant value into buf, if it is present
1073void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
1074 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
1075
1076 if (spec && spec_id < spec->mapEntryCount) {
1077 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
1078 }
1079}
1080
1081// Fill in value with the constant or specialization constant value, if available.
1082// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001083static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001084 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
Jeff Bolze4356752019-03-07 11:23:46 -06001085 auto type_id = src->get_def(insn.word(1));
1086 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
1087 return false;
1088 }
1089 switch (insn.opcode()) {
1090 case spv::OpSpecConstant:
1091 *value = insn.word(3);
1092 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
1093 return true;
1094 case spv::OpConstant:
1095 *value = insn.word(3);
1096 return true;
1097 default:
1098 return false;
1099 }
1100}
1101
1102// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001103VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06001104 switch (insn.opcode()) {
1105 case spv::OpTypeInt:
1106 switch (insn.word(2)) {
1107 case 8:
1108 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
1109 case 16:
1110 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
1111 case 32:
1112 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
1113 case 64:
1114 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
1115 default:
1116 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1117 }
1118 case spv::OpTypeFloat:
1119 switch (insn.word(2)) {
1120 case 16:
1121 return VK_COMPONENT_TYPE_FLOAT16_NV;
1122 case 32:
1123 return VK_COMPONENT_TYPE_FLOAT32_NV;
1124 case 64:
1125 return VK_COMPONENT_TYPE_FLOAT64_NV;
1126 default:
1127 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1128 }
1129 default:
1130 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
1131 }
1132}
1133
1134// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
1135// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001136bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06001137 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06001138 bool skip = false;
1139
1140 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001141 layer_data::unordered_map<uint32_t, uint32_t> id_to_spec_id;
Jeff Bolze4356752019-03-07 11:23:46 -06001142 // Map SPIR-V result ID to the ID of its type.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001143 layer_data::unordered_map<uint32_t, uint32_t> id_to_type_id;
Jeff Bolze4356752019-03-07 11:23:46 -06001144
1145 struct CoopMatType {
1146 uint32_t scope, rows, cols;
1147 VkComponentTypeNV component_type;
1148 bool all_constant;
1149
1150 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
1151
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001152 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001153 const layer_data::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
Jeff Bolze4356752019-03-07 11:23:46 -06001154 spirv_inst_iter insn = src->get_def(id);
1155 uint32_t component_type_id = insn.word(2);
1156 uint32_t scope_id = insn.word(3);
1157 uint32_t rows_id = insn.word(4);
1158 uint32_t cols_id = insn.word(5);
1159 auto component_type_iter = src->get_def(component_type_id);
1160 auto scope_iter = src->get_def(scope_id);
1161 auto rows_iter = src->get_def(rows_id);
1162 auto cols_iter = src->get_def(cols_id);
1163
1164 all_constant = true;
1165 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
1166 all_constant = false;
1167 }
1168 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
1169 all_constant = false;
1170 }
1171 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
1172 all_constant = false;
1173 }
1174 component_type = GetComponentType(component_type_iter, src);
1175 }
1176 };
1177
1178 bool seen_coopmat_capability = false;
1179
1180 for (auto insn : *src) {
1181 // Whitelist instructions whose result can be a cooperative matrix type, and
1182 // keep track of their types. It would be nice if SPIRV-Headers generated code
1183 // to identify which instructions have a result type and result id. Lacking that,
1184 // this whitelist is based on the set of instructions that
1185 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
1186 switch (insn.opcode()) {
1187 case spv::OpLoad:
1188 case spv::OpCooperativeMatrixLoadNV:
1189 case spv::OpCooperativeMatrixMulAddNV:
1190 case spv::OpSNegate:
1191 case spv::OpFNegate:
1192 case spv::OpIAdd:
1193 case spv::OpFAdd:
1194 case spv::OpISub:
1195 case spv::OpFSub:
1196 case spv::OpFDiv:
1197 case spv::OpSDiv:
1198 case spv::OpUDiv:
1199 case spv::OpMatrixTimesScalar:
1200 case spv::OpConstantComposite:
1201 case spv::OpCompositeConstruct:
1202 case spv::OpConvertFToU:
1203 case spv::OpConvertFToS:
1204 case spv::OpConvertSToF:
1205 case spv::OpConvertUToF:
1206 case spv::OpUConvert:
1207 case spv::OpSConvert:
1208 case spv::OpFConvert:
1209 id_to_type_id[insn.word(2)] = insn.word(1);
1210 break;
1211 default:
1212 break;
1213 }
1214
1215 switch (insn.opcode()) {
1216 case spv::OpDecorate:
1217 if (insn.word(2) == spv::DecorationSpecId) {
1218 id_to_spec_id[insn.word(1)] = insn.word(3);
1219 }
1220 break;
1221 case spv::OpCapability:
1222 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
1223 seen_coopmat_capability = true;
1224
1225 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001226 skip |= LogError(
1227 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
1228 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
1229 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06001230 }
1231 }
1232 break;
1233 case spv::OpMemoryModel:
1234 // If the capability isn't enabled, don't bother with the rest of this function.
1235 // OpMemoryModel is the first required instruction after all OpCapability instructions.
1236 if (!seen_coopmat_capability) {
1237 return skip;
1238 }
1239 break;
1240 case spv::OpTypeCooperativeMatrixNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001241 CoopMatType m;
1242 m.Init(insn.word(1), src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06001243
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001244 if (m.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06001245 // Validate that the type parameters are all supported for one of the
1246 // operands of a cooperative matrix property.
1247 bool valid = false;
1248 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001249 if (cooperative_matrix_properties[i].AType == m.component_type &&
1250 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].KSize == m.cols &&
1251 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06001252 valid = true;
1253 break;
1254 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001255 if (cooperative_matrix_properties[i].BType == m.component_type &&
1256 cooperative_matrix_properties[i].KSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
1257 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06001258 valid = true;
1259 break;
1260 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001261 if (cooperative_matrix_properties[i].CType == m.component_type &&
1262 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
1263 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06001264 valid = true;
1265 break;
1266 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001267 if (cooperative_matrix_properties[i].DType == m.component_type &&
1268 cooperative_matrix_properties[i].MSize == m.rows && cooperative_matrix_properties[i].NSize == m.cols &&
1269 cooperative_matrix_properties[i].scope == m.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06001270 valid = true;
1271 break;
1272 }
1273 }
1274 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001275 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
1276 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
1277 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06001278 }
1279 }
1280 break;
1281 }
1282 case spv::OpCooperativeMatrixMulAddNV: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001283 CoopMatType a, b, c, d;
Jeff Bolze4356752019-03-07 11:23:46 -06001284 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
1285 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
1286 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
1287 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07001288 // Couldn't find type of matrix
1289 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06001290 break;
1291 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001292 d.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
1293 a.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
1294 b.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
1295 c.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
Jeff Bolze4356752019-03-07 11:23:46 -06001296
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001297 if (a.all_constant && b.all_constant && c.all_constant && d.all_constant) {
Jeff Bolze4356752019-03-07 11:23:46 -06001298 // Validate that the type parameters are all supported for the same
1299 // cooperative matrix property.
1300 bool valid = false;
1301 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001302 if (cooperative_matrix_properties[i].AType == a.component_type &&
1303 cooperative_matrix_properties[i].MSize == a.rows && cooperative_matrix_properties[i].KSize == a.cols &&
1304 cooperative_matrix_properties[i].scope == a.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06001305
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001306 cooperative_matrix_properties[i].BType == b.component_type &&
1307 cooperative_matrix_properties[i].KSize == b.rows && cooperative_matrix_properties[i].NSize == b.cols &&
1308 cooperative_matrix_properties[i].scope == b.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06001309
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001310 cooperative_matrix_properties[i].CType == c.component_type &&
1311 cooperative_matrix_properties[i].MSize == c.rows && cooperative_matrix_properties[i].NSize == c.cols &&
1312 cooperative_matrix_properties[i].scope == c.scope &&
Jeff Bolze4356752019-03-07 11:23:46 -06001313
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001314 cooperative_matrix_properties[i].DType == d.component_type &&
1315 cooperative_matrix_properties[i].MSize == d.rows && cooperative_matrix_properties[i].NSize == d.cols &&
1316 cooperative_matrix_properties[i].scope == d.scope) {
Jeff Bolze4356752019-03-07 11:23:46 -06001317 valid = true;
1318 break;
1319 }
1320 }
1321 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001322 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
1323 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
1324 "VkCooperativeMatrixPropertiesNV",
1325 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06001326 }
1327 }
1328 break;
1329 }
1330 default:
1331 break;
1332 }
1333 }
1334
1335 return skip;
1336}
1337
John Zulaufac4c6e12019-07-01 16:05:58 -06001338bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001339 auto entrypoint_id = entrypoint.word(2);
1340
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01001341 // The first denorm execution mode encountered, along with its bit width.
1342 // Used to check if SeparateDenormSettings is respected.
1343 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001344
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01001345 // The first rounding mode encountered, along with its bit width.
1346 // Used to check if SeparateRoundingModeSettings is respected.
1347 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001348
1349 bool skip = false;
1350
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001351 uint32_t vertices_out = 0;
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001352 uint32_t invocations = 0;
1353
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001354 auto it = src->execution_mode_inst.find(entrypoint_id);
1355 if (it != src->execution_mode_inst.end()) {
1356 for (auto insn : it->second) {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001357 auto mode = insn.word(2);
1358 switch (mode) {
1359 case spv::ExecutionModeSignedZeroInfNanPreserve: {
1360 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001361 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
1362 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
1363 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001364 skip |= LogError(
1365 device, kVUID_Core_Shader_FeatureNotEnabled,
1366 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
1367 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001368 }
1369 break;
1370 }
1371
1372 case spv::ExecutionModeDenormPreserve: {
1373 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001374 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
1375 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
1376 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001377 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1378 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
1379 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001380 }
1381
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01001382 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
1383 // Register the first denorm execution mode found
1384 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001385 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001386 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001387 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001388 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001389 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1390 "Shader uses different denorm execution modes for 16 and 64-bit but "
1391 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001392 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001393 }
1394 break;
1395
Mike Schuchardt2df08912020-12-15 16:28:09 -08001396 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001397 break;
1398
Mike Schuchardt2df08912020-12-15 16:28:09 -08001399 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001400 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1401 "Shader uses different denorm execution modes for different bit widths but "
1402 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001403 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001404 break;
1405
1406 default:
1407 break;
1408 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001409 }
1410 break;
1411 }
1412
1413 case spv::ExecutionModeDenormFlushToZero: {
1414 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001415 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
1416 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
1417 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001418 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1419 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
1420 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001421 }
1422
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01001423 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
1424 // Register the first denorm execution mode found
1425 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001426 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001427 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001428 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001429 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001430 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1431 "Shader uses different denorm execution modes for 16 and 64-bit but "
1432 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001433 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001434 }
1435 break;
1436
Mike Schuchardt2df08912020-12-15 16:28:09 -08001437 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001438 break;
1439
Mike Schuchardt2df08912020-12-15 16:28:09 -08001440 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001441 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1442 "Shader uses different denorm execution modes for different bit widths but "
1443 "denormBehaviorIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001444 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001445 break;
1446
1447 default:
1448 break;
1449 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001450 }
1451 break;
1452 }
1453
1454 case spv::ExecutionModeRoundingModeRTE: {
1455 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001456 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
1457 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
1458 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001459 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1460 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
1461 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001462 }
1463
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01001464 if (first_rounding_mode.first == spv::ExecutionModeMax) {
1465 // Register the first rounding mode found
1466 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001467 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001468 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001469 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001470 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001471 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1472 "Shader uses different rounding modes for 16 and 64-bit but "
1473 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001474 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001475 }
1476 break;
1477
Mike Schuchardt2df08912020-12-15 16:28:09 -08001478 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001479 break;
1480
Mike Schuchardt2df08912020-12-15 16:28:09 -08001481 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001482 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1483 "Shader uses different rounding modes for different bit widths but "
1484 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001485 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001486 break;
1487
1488 default:
1489 break;
1490 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001491 }
1492 break;
1493 }
1494
1495 case spv::ExecutionModeRoundingModeRTZ: {
1496 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001497 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
1498 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
1499 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001500 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1501 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
1502 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001503 }
1504
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01001505 if (first_rounding_mode.first == spv::ExecutionModeMax) {
1506 // Register the first rounding mode found
1507 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001508 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07001509 switch (phys_dev_props_core12.roundingModeIndependence) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001510 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001511 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001512 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1513 "Shader uses different rounding modes for 16 and 64-bit but "
1514 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001515 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001516 }
1517 break;
1518
Mike Schuchardt2df08912020-12-15 16:28:09 -08001519 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL:
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001520 break;
1521
Mike Schuchardt2df08912020-12-15 16:28:09 -08001522 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001523 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
1524 "Shader uses different rounding modes for different bit widths but "
1525 "roundingModeIndependence is "
Mike Schuchardt2df08912020-12-15 16:28:09 -08001526 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05001527 break;
1528
1529 default:
1530 break;
1531 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001532 }
1533 break;
1534 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001535
1536 case spv::ExecutionModeOutputVertices: {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001537 vertices_out = insn.word(3);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001538 break;
1539 }
1540
1541 case spv::ExecutionModeInvocations: {
1542 invocations = insn.word(3);
1543 break;
1544 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001545 }
1546 }
1547 }
1548
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001549 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001550 if (vertices_out == 0 || vertices_out > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001551 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
1552 "Geometry shader entry point must have an OpExecutionMode instruction that "
1553 "specifies a maximum output vertex count that is greater than 0 and less "
1554 "than or equal to maxGeometryOutputVertices. "
1555 "OutputVertices=%d, maxGeometryOutputVertices=%d",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001556 vertices_out, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001557 }
1558
1559 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001560 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
1561 "Geometry shader entry point must have an OpExecutionMode instruction that "
1562 "specifies an invocation count that is greater than 0 and less "
1563 "than or equal to maxGeometryShaderInvocations. "
1564 "Invocations=%d, maxGeometryShaderInvocations=%d",
1565 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001566 }
1567 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001568 return skip;
1569}
1570
Chris Forbes47567b72017-06-09 12:09:45 -07001571// For given pipelineLayout verify that the set_layout_node at slot.first
1572// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06001573static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001574 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07001575 if (!pipelineLayout) return nullptr;
1576
1577 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
1578
1579 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
1580}
1581
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001582// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
1583// o If there is only a vertex shader : gl_PointSize must be written when using points
1584// o If there is a geometry or tessellation shader:
1585// - If shaderTessellationAndGeometryPointSize feature is enabled:
1586// * gl_PointSize must be written in the final geometry stage
1587// - If shaderTessellationAndGeometryPointSize feature is disabled:
1588// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001589bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06001590 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001591 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1592 return false;
1593 }
1594
1595 bool pointsize_written = false;
1596 bool skip = false;
1597
1598 // Search for PointSize built-in decorations
sfricke-samsungc0eb5282021-02-28 23:05:55 -08001599 for (auto set : src->builtin_decoration_list) {
1600 auto insn = src->at(set.offset);
1601 if (set.builtin == spv::BuiltInPointSize) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001602 pointsize_written = src->IsBuiltInWritten(insn, entrypoint);
sfricke-samsungc0eb5282021-02-28 23:05:55 -08001603 if (pointsize_written) {
1604 break;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001605 }
1606 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001607 }
1608
1609 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06001610 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001611 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001612 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
1613 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
1614 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001615 }
1616 } else if (!pointsize_written) {
1617 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001618 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
1619 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
1620 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001621 }
1622 return skip;
1623}
John Zulauf14c355b2019-06-27 16:09:37 -06001624
Tobias Hector6663c9b2020-11-05 10:18:02 +00001625bool CoreChecks::ValidatePrimitiveRateShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
1626 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
1627 bool primitiverate_written = false;
1628 bool viewportindex_written = false;
1629 bool viewportmask_written = false;
1630 bool skip = false;
1631
1632 // Check if the primitive shading rate is written
sfricke-samsungc0eb5282021-02-28 23:05:55 -08001633 for (auto set : src->builtin_decoration_list) {
1634 auto insn = src->at(set.offset);
1635 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001636 primitiverate_written = src->IsBuiltInWritten(insn, entrypoint);
sfricke-samsungc0eb5282021-02-28 23:05:55 -08001637 } else if (set.builtin == spv::BuiltInViewportIndex) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001638 viewportindex_written = src->IsBuiltInWritten(insn, entrypoint);
sfricke-samsungc0eb5282021-02-28 23:05:55 -08001639 } else if (set.builtin == spv::BuiltInViewportMaskNV) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001640 viewportmask_written = src->IsBuiltInWritten(insn, entrypoint);
Tobias Hector6663c9b2020-11-05 10:18:02 +00001641 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08001642 if (primitiverate_written && viewportindex_written && viewportmask_written) {
1643 break;
1644 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00001645 }
1646
Tony-LunarGd44844c2021-01-22 13:24:37 -07001647 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
1648 pipeline->graphicsPipelineCI.pViewportState) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00001649 if (!IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) &&
1650 pipeline->graphicsPipelineCI.pViewportState->viewportCount > 1 && primitiverate_written) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001651 skip |= LogError(pipeline->pipeline,
1652 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04503",
1653 "vkCreateGraphicsPipelines: %s shader statically writes to PrimitiveShadingRateKHR built-in, but "
1654 "multiple viewports "
1655 "are used and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
1656 string_VkShaderStageFlagBits(stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00001657 }
1658
1659 if (primitiverate_written && viewportindex_written) {
1660 skip |= LogError(pipeline->pipeline,
1661 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04504",
1662 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
1663 "ViewportIndex built-ins,"
1664 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
1665 string_VkShaderStageFlagBits(stage));
1666 }
1667
1668 if (primitiverate_written && viewportmask_written) {
1669 skip |= LogError(pipeline->pipeline,
1670 "VUID-VkGraphicsPipelineCreateInfo-primitiveFragmentShadingRateWithMultipleViewports-04505",
1671 "vkCreateGraphicsPipelines: %s shader statically writes to both PrimitiveShadingRateKHR and "
1672 "ViewportMaskNV built-ins,"
1673 "but the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
1674 string_VkShaderStageFlagBits(stage));
1675 }
1676 }
1677 return skip;
1678}
1679
sfricke-samsung486a51e2021-01-02 00:10:15 -08001680// Validate runtime usage of various opcodes that depends on what Vulkan properties or features are exposed
sfricke-samsung94167ca2021-02-26 04:14:59 -08001681bool CoreChecks::ValidatePropertiesAndFeatures(SHADER_MODULE_STATE const *module, spirv_inst_iter &insn) const {
sfricke-samsung486a51e2021-01-02 00:10:15 -08001682 bool skip = false;
1683
sfricke-samsung94167ca2021-02-26 04:14:59 -08001684 switch (insn.opcode()) {
1685 case spv::OpReadClockKHR: {
1686 auto scope_id = module->get_def(insn.word(3));
1687 auto scope_type = scope_id.word(3);
1688 // if scope isn't Subgroup or Device, spirv-val will catch
1689 if ((scope_type == spv::ScopeSubgroup) && (enabled_features.shader_clock_feature.shaderSubgroupClock == VK_FALSE)) {
1690 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderSubgroupClock",
1691 "%s: OpReadClockKHR is used with a Subgroup scope but shaderSubgroupClock was not enabled.",
1692 report_data->FormatHandle(module->vk_shader_module).c_str());
1693 } else if ((scope_type == spv::ScopeDevice) && (enabled_features.shader_clock_feature.shaderDeviceClock == VK_FALSE)) {
1694 skip |= LogError(device, "UNASSIGNED-spirv-shaderClock-shaderDeviceClock",
1695 "%s: OpReadClockKHR is used with a Device scope but shaderDeviceClock was not enabled.",
1696 report_data->FormatHandle(module->vk_shader_module).c_str());
sfricke-samsung486a51e2021-01-02 00:10:15 -08001697 }
sfricke-samsung94167ca2021-02-26 04:14:59 -08001698 break;
sfricke-samsung486a51e2021-01-02 00:10:15 -08001699 }
1700 }
1701 return skip;
1702}
1703
John Zulauf14c355b2019-06-27 16:09:37 -06001704bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
1705 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06001706 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06001707 bool skip = false;
1708
1709 // Check the module
1710 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001711 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
1712 "%s does not contain valid spirv for stage %s.",
1713 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06001714 }
1715
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001716 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
1717 // specializations should be applied and validated.
1718 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
1719 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
1720 // Gather the specialization-constant values.
1721 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07001722 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001723 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map; // note: this must be std:: to work with spvtools
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001724 id_value_map.reserve(specialization_info->mapEntryCount);
1725 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
1726 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001727
Jeremy Hayes521221d2020-01-15 16:48:49 -07001728 // Expect only scalar types.
1729 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
Jeremy Gebben12933ef2021-05-12 17:16:27 -06001730 if ((map_entry.offset + map_entry.size) <= specialization_info->dataSize) {
1731 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
1732 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
1733 }
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001734 }
1735
1736 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06001737 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001738 spvtools::Optimizer optimizer(spirv_environment);
1739 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
1740 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001741 skip |= LogError(
1742 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001743 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
1744 };
1745 optimizer.SetMessageConsumer(consumer);
1746 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
1747 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
1748 std::vector<uint32_t> specialized_spirv;
1749 auto const optimized =
1750 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
1751 assert(optimized == true);
1752
1753 if (optimized) {
1754 spv_context ctx = spvContextCreate(spirv_environment);
1755 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
1756 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06001757 spvtools::ValidatorOptions options;
1758 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001759 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
1760 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07001761 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001762 "After specialization was applied, %s does not contain valid spirv for stage %s.",
1763 report_data->FormatHandle(module->vk_shader_module).c_str(),
1764 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001765 }
1766
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06001767 spvDiagnosticDestroy(diag);
1768 spvContextDestroy(ctx);
1769 }
1770 }
1771
John Zulauf14c355b2019-06-27 16:09:37 -06001772 // Check the entrypoint
1773 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001774 skip |=
1775 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
1776 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06001777 }
1778 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
1779
1780 // Mark accessible ids
1781 auto &accessible_ids = stage_state.accessible_ids;
1782
Chris Forbes47567b72017-06-09 12:09:45 -07001783 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06001784 bool has_writable_descriptor = stage_state.has_writable_descriptor;
1785 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07001786
sfricke-samsung94167ca2021-02-26 04:14:59 -08001787 // The following tries to limit the number of passes through the shader module. The validation passes in here are "stateless"
1788 // and mainly only checking the instruction in detail for a single operation
1789 for (auto insn : *module) {
1790 skip |= ValidateShaderCapabilitiesAndExtensions(module, insn);
1791 skip |= ValidatePropertiesAndFeatures(module, insn);
1792 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, insn);
1793 }
1794
locke-lunarg63e4daf2020-08-17 17:53:25 -06001795 skip |=
1796 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05001797 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07001798 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00001799 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001800 skip |= ValidateSpecializationOffsets(pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05001801 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07001802 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001803 }
sfricke-samsungef2a68c2020-10-26 04:22:46 -07001804 skip |= ValidateBuiltinLimits(module, accessible_ids, pStage->stage);
sfricke-samsungd093e522021-02-26 04:17:45 -08001805 if (enabled_features.cooperative_matrix_features.cooperativeMatrix) {
1806 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
1807 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00001808 if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) {
1809 skip |= ValidatePrimitiveRateShaderState(pipeline, module, entrypoint, pStage->stage);
1810 }
Chris Forbes47567b72017-06-09 12:09:45 -07001811
sfricke-samsung7699b912021-04-12 23:01:51 -07001812 // "layout must be consistent with the layout of the * shader"
1813 // 'consistent' -> #descriptorsets-pipelinelayout-consistency
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001814 std::string vuid_layout_mismatch;
1815 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
1816 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
1817 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
1818 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
1819 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
1820 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
1821 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
1822 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
1823 }
1824
sfricke-samsung7699b912021-04-12 23:01:51 -07001825 // Validate Push Constants use
1826 skip |= ValidatePushConstantUsage(*pipeline, module, pStage, vuid_layout_mismatch);
1827
Chris Forbes47567b72017-06-09 12:09:45 -07001828 // Validate descriptor use
1829 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07001830 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05001831 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07001832 unsigned required_descriptor_count;
sourav parmarcd5fb182020-07-17 12:58:44 -07001833 bool is_khr = binding && binding->descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
1834 std::set<uint32_t> descriptor_types =
1835 TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count, is_khr);
Chris Forbes47567b72017-06-09 12:09:45 -07001836
1837 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001838 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001839 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
1840 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001841 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001842 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001843 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
1844 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Tony-LunarGf563b362021-03-18 16:13:18 -06001845 } else if ((binding->descriptorType != VK_DESCRIPTOR_TYPE_MUTABLE_VALVE) &&
1846 (descriptor_types.find(binding->descriptorType) == descriptor_types.end())) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001847 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001848 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
1849 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
1850 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07001851 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001852 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001853 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
1854 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07001855 }
1856 }
1857
1858 // Validate use of input attachments against subpass structure
1859 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001860 auto input_attachment_uses = module->CollectInterfaceByInputAttachmentIndex(accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07001861
Petr Krause91f7a12017-12-14 20:57:36 +01001862 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07001863 auto subpass = pipeline->graphicsPipelineCI.subpass;
1864
1865 for (auto use : input_attachment_uses) {
1866 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
1867 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07001868 ? input_attachments[use.first].attachment
1869 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07001870
1871 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001872 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
1873 "Shader consumes input attachment index %d but not provided in subpass", use.first);
sfricke-samsung962cad92021-04-13 00:46:29 -07001874 } else if (!(GetFormatType(rpci->pAttachments[index].format) & module->GetFundamentalType(use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07001875 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001876 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
1877 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
sfricke-samsung962cad92021-04-13 00:46:29 -07001878 string_VkFormat(rpci->pAttachments[index].format), module->DescribeType(use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001879 }
1880 }
1881 }
Lockeaa8fdc02019-04-02 11:59:20 -06001882 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001883 skip |= ValidateComputeWorkGroupSizes(module, entrypoint);
Lockeaa8fdc02019-04-02 11:59:20 -06001884 }
Chris Forbes47567b72017-06-09 12:09:45 -07001885 return skip;
1886}
1887
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001888bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
1889 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
1890 spirv_inst_iter consumer_entrypoint,
1891 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001892 bool skip = false;
1893
1894 auto outputs =
sfricke-samsung962cad92021-04-13 00:46:29 -07001895 producer->CollectInterfaceByLocation(producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
1896 auto inputs = consumer->CollectInterfaceByLocation(consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07001897
1898 auto a_it = outputs.begin();
1899 auto b_it = inputs.begin();
1900
1901 // Maps sorted by key (location); walk them together to find mismatches
1902 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1903 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1904 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1905 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1906 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1907
1908 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001909 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1910 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
1911 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001912 a_it++;
1913 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001914 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1915 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
1916 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001917 b_it++;
1918 } else {
1919 // subtleties of arrayed interfaces:
1920 // - if is_patch, then the member is not arrayed, even though the interface may be.
1921 // - if is_block_member, then the extra array level of an arrayed interface is not
1922 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001923 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1924 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
1925 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001926 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1927 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
sfricke-samsung962cad92021-04-13 00:46:29 -07001928 producer->DescribeType(a_it->second.type_id).c_str(),
1929 consumer->DescribeType(b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001930 }
1931 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001932 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1933 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
1934 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1935 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001936 }
1937 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001938 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1939 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
1940 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07001941 }
1942 a_it++;
1943 b_it++;
1944 }
1945 }
1946
Ari Suonpaa696b3432019-03-11 14:02:57 +02001947 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001948 auto builtins_producer = producer->CollectBuiltinBlockMembers(producer_entrypoint, spv::StorageClassOutput);
1949 auto builtins_consumer = consumer->CollectBuiltinBlockMembers(consumer_entrypoint, spv::StorageClassInput);
Ari Suonpaa696b3432019-03-11 14:02:57 +02001950
1951 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
1952 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001953 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1954 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001955 producer_stage->name, static_cast<int>(builtins_producer.size()), consumer_stage->name,
1956 static_cast<int>(builtins_consumer.size()));
Ari Suonpaa696b3432019-03-11 14:02:57 +02001957 } else {
1958 auto it_producer = builtins_producer.begin();
1959 auto it_consumer = builtins_consumer.begin();
1960 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
1961 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001962 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1963 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
1964 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02001965 break;
1966 }
1967 it_producer++;
1968 it_consumer++;
1969 }
1970 }
1971 }
1972 }
1973
Chris Forbes47567b72017-06-09 12:09:45 -07001974 return skip;
1975}
1976
John Zulauf14c355b2019-06-27 16:09:37 -06001977static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001978 uint32_t stage_mask = 0;
1979 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
1980 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1981 stage_mask |= pCreateInfo->pStages[i].stage;
1982 }
1983 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05001984 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
1985 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
1986 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001987 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
1988 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
1989 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
1990 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
1991 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001992 }
1993 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001994 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06001995}
1996
Chris Forbes47567b72017-06-09 12:09:45 -07001997// Validate that the shaders used by the given pipeline and store the active_slots
1998// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06001999bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002000 auto create_info = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002001 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2002 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002003
John Zulauf14c355b2019-06-27 16:09:37 -06002004 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002005 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05002006 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07002007 bool skip = false;
2008
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002009 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, create_info);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06002010
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002011 for (uint32_t i = 0; i < create_info->stageCount; i++) {
2012 auto stage = &create_info->pStages[i];
2013 auto stage_id = GetShaderStageId(stage->stage);
2014 shaders[stage_id] = GetShaderModuleState(stage->module);
sfricke-samsung962cad92021-04-13 00:46:29 -07002015 entrypoints[stage_id] = shaders[stage_id]->FindEntrypoint(stage->pName, stage->stage);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002016 skip |= ValidatePipelineShaderStage(stage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
2017 (pointlist_stage_mask == stage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07002018 }
2019
2020 // if the shader stages are no good individually, cross-stage validation is pointless.
2021 if (skip) return true;
2022
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002023 auto vi = create_info->pVertexInputState;
Chris Forbes47567b72017-06-09 12:09:45 -07002024
2025 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002026 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07002027 }
2028
2029 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002030 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07002031 }
2032
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06002033 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
2034 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07002035
2036 while (!shaders[producer] && producer != fragment_stage) {
2037 producer++;
2038 consumer++;
2039 }
2040
2041 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
2042 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002043 if (shaders[consumer]) {
2044 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002045 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
2046 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08002047 }
Chris Forbes47567b72017-06-09 12:09:45 -07002048
2049 producer = consumer;
2050 }
2051 }
2052
2053 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002054 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002055 create_info->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07002056 }
2057
2058 return skip;
2059}
2060
Tony-LunarGb2ded512021-02-02 16:03:30 -07002061void CoreChecks::RecordGraphicsPipelineShaderDynamicState(PIPELINE_STATE *pipeline_state) {
2062 auto create_info = pipeline_state->graphicsPipelineCI.ptr();
2063
2064 if (phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports ||
2065 !IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)) {
2066 return;
2067 }
Tobias Hector6663c9b2020-11-05 10:18:02 +00002068
Nathaniel Cesario1c3d3652021-01-25 18:35:12 -07002069 std::array<const SHADER_MODULE_STATE *, 32> shaders;
2070 std::fill(shaders.begin(), shaders.end(), nullptr);
Tobias Hector6663c9b2020-11-05 10:18:02 +00002071 spirv_inst_iter entrypoints[32];
Tobias Hector6663c9b2020-11-05 10:18:02 +00002072
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002073 for (uint32_t i = 0; i < create_info->stageCount; i++) {
2074 auto stage = &create_info->pStages[i];
2075 auto stage_id = GetShaderStageId(stage->stage);
2076 shaders[stage_id] = GetShaderModuleState(stage->module);
sfricke-samsung962cad92021-04-13 00:46:29 -07002077 entrypoints[stage_id] = shaders[stage_id]->FindEntrypoint(stage->pName, stage->stage);
Tobias Hector6663c9b2020-11-05 10:18:02 +00002078
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002079 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
2080 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
Tony-LunarGb2ded512021-02-02 16:03:30 -07002081 bool primitiverate_written = false;
Tobias Hector6663c9b2020-11-05 10:18:02 +00002082
sfricke-samsungc0eb5282021-02-28 23:05:55 -08002083 for (auto set : shaders[stage_id]->builtin_decoration_list) {
2084 auto insn = shaders[stage_id]->at(set.offset);
2085 if (set.builtin == spv::BuiltInPrimitiveShadingRateKHR) {
sfricke-samsung962cad92021-04-13 00:46:29 -07002086 primitiverate_written = shaders[stage_id]->IsBuiltInWritten(insn, entrypoints[stage_id]);
Tobias Hector6663c9b2020-11-05 10:18:02 +00002087 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08002088 if (primitiverate_written) {
2089 break;
2090 }
Tony-LunarGb2ded512021-02-02 16:03:30 -07002091 }
sfricke-samsungc0eb5282021-02-28 23:05:55 -08002092
Tony-LunarGb2ded512021-02-02 16:03:30 -07002093 if (primitiverate_written) {
2094 pipeline_state->wrote_primitive_shading_rate.insert(stage->stage);
2095 }
2096 }
2097 }
2098}
2099
2100bool CoreChecks::ValidateGraphicsPipelineShaderDynamicState(const PIPELINE_STATE *pipeline, const CMD_BUFFER_STATE *pCB,
2101 const char *caller, const DrawDispatchVuid &vuid) const {
2102 auto create_info = pipeline->graphicsPipelineCI.ptr();
2103 bool skip = false;
2104
2105 for (uint32_t i = 0; i < create_info->stageCount; i++) {
2106 auto stage = &create_info->pStages[i];
2107 if (stage->stage == VK_SHADER_STAGE_VERTEX_BIT || stage->stage == VK_SHADER_STAGE_GEOMETRY_BIT ||
2108 stage->stage == VK_SHADER_STAGE_MESH_BIT_NV) {
2109 if (!phys_dev_ext_props.fragment_shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports &&
2110 IsDynamic(pipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) && pCB->viewportWithCountCount != 1) {
2111 if (pipeline->wrote_primitive_shading_rate.find(stage->stage) != pipeline->wrote_primitive_shading_rate.end()) {
Tobias Hector6663c9b2020-11-05 10:18:02 +00002112 skip |=
2113 LogError(pipeline->pipeline, vuid.viewport_count_primitive_shading_rate,
2114 "%s: %s shader of currently bound pipeline statically writes to PrimitiveShadingRateKHR built-in"
2115 "but multiple viewports are set by the last call to vkCmdSetViewportWithCountEXT,"
2116 "and the primitiveFragmentShadingRateWithMultipleViewports limit is not supported.",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002117 caller, string_VkShaderStageFlagBits(stage->stage));
Tobias Hector6663c9b2020-11-05 10:18:02 +00002118 }
2119 }
2120 }
2121 }
2122
2123 return skip;
2124}
2125
sfricke-samsunge72a85e2020-02-29 21:48:37 -08002126bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06002127 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07002128
John Zulauf14c355b2019-06-27 16:09:37 -06002129 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
sfricke-samsung962cad92021-04-13 00:46:29 -07002130 const spirv_inst_iter entrypoint = module->FindEntrypoint(stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07002131
John Zulauf14c355b2019-06-27 16:09:37 -06002132 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07002133}
Chris Forbes4ae55b32017-06-09 14:42:56 -07002134
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02002135uint32_t CoreChecks::CalcShaderStageCount(const PIPELINE_STATE *pipeline, VkShaderStageFlagBits stageBit) const {
2136 uint32_t total = 0;
2137
2138 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
2139 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
2140 if (stages[stage_index].stage == stageBit) {
2141 total++;
2142 }
2143 }
2144
2145 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
2146 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
2147 const PIPELINE_STATE *library_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
2148 total += CalcShaderStageCount(library_pipeline, stageBit);
2149 }
2150 }
2151
2152 return total;
2153}
2154
sourav parmarcd5fb182020-07-17 12:58:44 -07002155bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, VkPipelineCreateFlags flags, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06002156 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04002157
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002158 if (isKHR) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002159 if (pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth >
2160 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth) {
2161 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589",
2162 "vkCreateRayTracingPipelinesKHR: maxPipelineRayRecursionDepth (%d ) must be less than or equal to "
2163 "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::maxRayRecursionDepth %d",
2164 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth,
2165 phys_dev_ext_props.ray_tracing_propsKHR.maxRayRecursionDepth);
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002166 }
sourav parmarcd5fb182020-07-17 12:58:44 -07002167 if (pipeline->raytracingPipelineCI.pLibraryInfo) {
2168 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002169 const PIPELINE_STATE *library_pipelinestate =
sourav parmarcd5fb182020-07-17 12:58:44 -07002170 GetPipelineState(pipeline->raytracingPipelineCI.pLibraryInfo->pLibraries[i]);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002171 if (library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth !=
sourav parmarcd5fb182020-07-17 12:58:44 -07002172 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth) {
2173 skip |= LogError(
2174 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591",
2175 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
2176 "created with the value of maxPipelineRayRecursionDepth (%d) equal to that in this pipeline (%d) .",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002177 i, library_pipelinestate->raytracingPipelineCI.maxPipelineRayRecursionDepth,
sourav parmarcd5fb182020-07-17 12:58:44 -07002178 pipeline->raytracingPipelineCI.maxPipelineRayRecursionDepth);
2179 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002180 if (library_pipelinestate->raytracingPipelineCI.pLibraryInfo &&
2181 (library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07002182 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayHitAttributeSize ||
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002183 library_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize !=
sourav parmarcd5fb182020-07-17 12:58:44 -07002184 pipeline->raytracingPipelineCI.pLibraryInterface->maxPipelineRayPayloadSize)) {
2185 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593",
2186 "vkCreateRayTracingPipelinesKHR: If pLibraryInfo is not NULL, each element of its pLibraries "
2187 "member must have been created with values of the maxPipelineRayPayloadSize and "
2188 "maxPipelineRayHitAttributeSize members of pLibraryInterface equal to those in this pipeline");
2189 }
2190 if ((flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002191 !(library_pipelinestate->raytracingPipelineCI.flags &
sourav parmarcd5fb182020-07-17 12:58:44 -07002192 VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) {
2193 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594",
2194 "vkCreateRayTracingPipelinesKHR: If flags includes "
2195 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR, each element of "
2196 "the pLibraries member of libraries must have been created with the "
2197 "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR bit set");
2198 }
sourav parmar83c31b12020-05-06 12:30:54 -07002199 }
2200 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002201 } else {
2202 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002203 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457",
2204 "vkCreateRayTracingPipelinesNV: maxRecursionDepth (%d) must be less than or equal to "
2205 "VkPhysicalDeviceRayTracingPropertiesNV::maxRecursionDepth (%d)",
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002206 pipeline->raytracingPipelineCI.maxRecursionDepth,
2207 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
2208 }
Jason Macnak15f95e82019-08-21 21:52:02 -04002209 }
Jason Macnak15f95e82019-08-21 21:52:02 -04002210 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
2211 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
2212
John Zulaufe4474e72019-07-01 17:28:27 -06002213 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04002214 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05002215
John Zulaufe4474e72019-07-01 17:28:27 -06002216 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
sfricke-samsung962cad92021-04-13 00:46:29 -07002217 const spirv_inst_iter entrypoint = module->FindEntrypoint(stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05002218
John Zulaufe4474e72019-07-01 17:28:27 -06002219 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04002220 }
Ricardo Garcia6f3477e2020-10-21 10:58:53 +02002221
2222 if ((pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) == 0) {
2223 const uint32_t raygen_stages_count = CalcShaderStageCount(pipeline, VK_SHADER_STAGE_RAYGEN_BIT_KHR);
2224 if (raygen_stages_count == 0) {
2225 skip |= LogError(
2226 device,
2227 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
2228 " : The stage member of at least one element of pStages must be VK_SHADER_STAGE_RAYGEN_BIT_KHR.");
2229 }
Jason Macnak15f95e82019-08-21 21:52:02 -04002230 }
2231
2232 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
2233 const auto &group = groups[group_index];
2234
2235 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
2236 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
2237 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
2238 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
2239 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002240 skip |= LogError(device,
2241 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
2242 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
2243 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04002244 }
2245 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
2246 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002247 skip |= LogError(device,
2248 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
2249 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
2250 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04002251 }
2252 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
2253 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
2254 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002255 skip |= LogError(device,
2256 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
2257 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
2258 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04002259 }
2260 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
2261 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002262 skip |= LogError(device,
2263 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
2264 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
2265 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04002266 }
2267 }
2268
2269 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
2270 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
2271 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
2272 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002273 skip |= LogError(device,
2274 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
2275 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
2276 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04002277 }
2278 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
2279 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
2280 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002281 skip |= LogError(device,
2282 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
2283 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
2284 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04002285 }
2286 }
John Zulaufe4474e72019-07-01 17:28:27 -06002287 }
2288 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05002289}
2290
Dave Houltona9df0ce2018-02-07 10:51:23 -07002291uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07002292
Dave Houltona9df0ce2018-02-07 10:51:23 -07002293static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07002294 const auto validation_cache_ci = LvlFindInChain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
John Zulauf25ea2432019-04-05 10:07:38 -06002295 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06002296 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07002297 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002298 return nullptr;
2299}
2300
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07002301bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002302 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002303 bool skip = false;
2304 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002305
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06002306 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07002307 return false;
2308 }
2309
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06002310 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07002311
2312 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002313 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
2314 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
2315 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002316 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07002317 auto cache = GetValidationCacheInfo(pCreateInfo);
2318 uint32_t hash = 0;
2319 if (cache) {
2320 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002321 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07002322 }
2323
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06002324 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
2325 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06002326 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06002327 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07002328 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07002329 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06002330 spvtools::ValidatorOptions options;
2331 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06002332 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07002333 if (spv_valid != SPV_SUCCESS) {
2334 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002335 if (spv_valid == SPV_WARNING) {
2336 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
2337 diag && diag->error ? diag->error : "(no error text)");
2338 } else {
2339 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
2340 diag && diag->error ? diag->error : "(no error text)");
2341 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002342 }
Chris Forbes9a61e082017-07-24 15:35:29 -07002343 } else {
2344 if (cache) {
2345 cache->Insert(hash);
2346 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07002347 }
2348
2349 spvDiagnosticDestroy(diag);
2350 spvContextDestroy(ctx);
2351 }
2352
Chris Forbes4ae55b32017-06-09 14:42:56 -07002353 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07002354}
2355
sfricke-samsung8a7341a2021-02-28 07:30:21 -08002356bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader, const spirv_inst_iter &entrypoint) const {
Lockeaa8fdc02019-04-02 11:59:20 -06002357 bool skip = false;
2358 uint32_t local_size_x = 0;
2359 uint32_t local_size_y = 0;
2360 uint32_t local_size_z = 0;
sfricke-samsung962cad92021-04-13 00:46:29 -07002361 if (shader->FindLocalSize(entrypoint, local_size_x, local_size_y, local_size_z)) {
Lockeaa8fdc02019-04-02 11:59:20 -06002362 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002363 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
2364 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
2365 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
2366 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06002367 }
2368 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002369 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
2370 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
2371 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
2372 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06002373 }
2374 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002375 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
2376 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
2377 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
2378 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06002379 }
2380
2381 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
2382 uint64_t invocations = local_size_x * local_size_y;
2383 // Prevent overflow.
2384 bool fail = false;
2385 if (invocations > UINT32_MAX || invocations > limit) {
2386 fail = true;
2387 }
2388 if (!fail) {
2389 invocations *= local_size_z;
2390 if (invocations > UINT32_MAX || invocations > limit) {
2391 fail = true;
2392 }
2393 }
2394 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002395 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
2396 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2397 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
2398 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
2399 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06002400 }
2401 }
2402 return skip;
2403}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06002404
2405spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
2406 if (api_version >= VK_API_VERSION_1_2) {
2407 return SPV_ENV_VULKAN_1_2;
2408 } else if (api_version >= VK_API_VERSION_1_1) {
2409 if (spirv_1_4) {
2410 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
2411 } else {
2412 return SPV_ENV_VULKAN_1_1;
2413 }
2414 }
2415 return SPV_ENV_VULKAN_1_0;
2416}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06002417
2418void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
2419 spvtools::ValidatorOptions &options) {
2420 if (device_extensions.vk_khr_relaxed_block_layout) {
2421 options.SetRelaxBlockLayout(true);
2422 }
2423 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
2424 options.SetUniformBufferStandardLayout(true);
2425 }
2426 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
2427 options.SetScalarBlockLayout(true);
2428 }
Caio Marcelo de Oliveira Filhod1bfbcd2021-01-27 01:44:04 -08002429 if (device_extensions.vk_khr_workgroup_memory_explicit_layout &&
2430 enabled_features.workgroup_memory_explicit_layout_features.workgroupMemoryExplicitLayoutScalarBlockLayout) {
2431 options.SetWorkgroupScalarBlockLayout(true);
2432 }
Tony-LunarG9fe69a42020-07-23 15:09:37 -06002433}