blob: 7dd6fb5d675b53c68e6566e56055a90a95bdba3a [file] [log] [blame]
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001/* Copyright (c) 2021-2022 The Khronos Group Inc.
sfricke-samsung962cad92021-04-13 00:46:29 -07002 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 *
15 * Author: Spencer Fricke <s.fricke@samsung.com>
16 */
17
18#include "shader_module.h"
19
20#include <sstream>
21#include <string>
22
23#include "vk_layer_data.h"
24#include "vk_layer_utils.h"
Jeremy Gebben5d970742021-05-31 16:04:14 -060025#include "pipeline_state.h"
26#include "descriptor_sets.h"
sfricke-samsung3c5dee22021-10-14 09:58:14 -070027#include "spirv_grammar_helper.h"
sfricke-samsung962cad92021-04-13 00:46:29 -070028
29void decoration_set::merge(decoration_set const &other) {
30 if (other.flags & location_bit) location = other.location;
31 if (other.flags & component_bit) component = other.component;
32 if (other.flags & input_attachment_index_bit) input_attachment_index = other.input_attachment_index;
33 if (other.flags & descriptor_set_bit) descriptor_set = other.descriptor_set;
34 if (other.flags & binding_bit) binding = other.binding;
35 if (other.flags & builtin_bit) builtin = other.builtin;
36 flags |= other.flags;
37}
38
39void decoration_set::add(uint32_t decoration, uint32_t value) {
40 switch (decoration) {
41 case spv::DecorationLocation:
42 flags |= location_bit;
43 location = value;
44 break;
45 case spv::DecorationPatch:
46 flags |= patch_bit;
47 break;
48 case spv::DecorationRelaxedPrecision:
49 flags |= relaxed_precision_bit;
50 break;
51 case spv::DecorationBlock:
52 flags |= block_bit;
53 break;
54 case spv::DecorationBufferBlock:
55 flags |= buffer_block_bit;
56 break;
57 case spv::DecorationComponent:
58 flags |= component_bit;
59 component = value;
60 break;
61 case spv::DecorationInputAttachmentIndex:
62 flags |= input_attachment_index_bit;
63 input_attachment_index = value;
64 break;
65 case spv::DecorationDescriptorSet:
66 flags |= descriptor_set_bit;
67 descriptor_set = value;
68 break;
69 case spv::DecorationBinding:
70 flags |= binding_bit;
71 binding = value;
72 break;
73 case spv::DecorationNonWritable:
74 flags |= nonwritable_bit;
75 break;
76 case spv::DecorationBuiltIn:
77 flags |= builtin_bit;
78 builtin = value;
79 break;
Lionel Landwerlin38d2e122021-07-21 14:21:47 +030080 case spv::DecorationNonReadable:
81 flags |= nonreadable_bit;
82 break;
ziga-lunarg9e94e112021-09-27 00:21:10 +020083 case spv::DecorationPerVertexNV:
84 flags |= per_vertex_bit;
85 break;
86 case spv::DecorationPassthroughNV:
87 flags |= passthrough_bit;
88 break;
sjfrickede734312022-07-14 19:22:43 +090089 case spv::DecorationAliased:
90 flags |= aliased_bit;
91 break;
sfricke-samsung962cad92021-04-13 00:46:29 -070092 }
93}
94
95std::string shader_struct_member::GetLocationDesc(uint32_t index_used_bytes) const {
96 std::string desc = "";
97 if (array_length_hierarchy.size() > 0) {
98 desc += " index:";
99 for (const auto block_size : array_block_size) {
100 desc += "[";
101 desc += std::to_string(index_used_bytes / (block_size * size));
102 desc += "]";
103 index_used_bytes = index_used_bytes % (block_size * size);
104 }
105 }
106 const int struct_members_size = static_cast<int>(struct_members.size());
107 if (struct_members_size > 0) {
108 desc += " member:";
109 for (int i = struct_members_size - 1; i >= 0; --i) {
110 if (index_used_bytes > struct_members[i].offset) {
111 desc += std::to_string(i);
112 desc += struct_members[i].GetLocationDesc(index_used_bytes - struct_members[i].offset);
113 break;
114 }
115 }
116 } else {
117 desc += " offset:";
118 desc += std::to_string(index_used_bytes);
119 }
120 return desc;
121}
122
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800123static uint32_t ExecutionModelToShaderStageFlagBits(uint32_t mode) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700124 switch (mode) {
125 case spv::ExecutionModelVertex:
126 return VK_SHADER_STAGE_VERTEX_BIT;
127 case spv::ExecutionModelTessellationControl:
128 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
129 case spv::ExecutionModelTessellationEvaluation:
130 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
131 case spv::ExecutionModelGeometry:
132 return VK_SHADER_STAGE_GEOMETRY_BIT;
133 case spv::ExecutionModelFragment:
134 return VK_SHADER_STAGE_FRAGMENT_BIT;
135 case spv::ExecutionModelGLCompute:
136 return VK_SHADER_STAGE_COMPUTE_BIT;
sjfricke62366d32022-08-01 21:04:10 +0900137 case spv::ExecutionModelRayGenerationKHR:
138 return VK_SHADER_STAGE_RAYGEN_BIT_KHR;
139 case spv::ExecutionModelAnyHitKHR:
140 return VK_SHADER_STAGE_ANY_HIT_BIT_KHR;
141 case spv::ExecutionModelClosestHitKHR:
142 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR;
143 case spv::ExecutionModelMissKHR:
144 return VK_SHADER_STAGE_MISS_BIT_KHR;
145 case spv::ExecutionModelIntersectionKHR:
146 return VK_SHADER_STAGE_INTERSECTION_BIT_KHR;
147 case spv::ExecutionModelCallableKHR:
148 return VK_SHADER_STAGE_CALLABLE_BIT_KHR;
sfricke-samsung962cad92021-04-13 00:46:29 -0700149 case spv::ExecutionModelTaskNV:
150 return VK_SHADER_STAGE_TASK_BIT_NV;
151 case spv::ExecutionModelMeshNV:
152 return VK_SHADER_STAGE_MESH_BIT_NV;
153 default:
154 return 0;
155 }
156}
157
158// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
159// important for identifying the set of shader resources actually used by an entrypoint, for example.
160// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
161// - NOT the shader input/output interfaces.
162//
163// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
164// converting parts of this to be generated from the machine-readable spec instead.
165layer_data::unordered_set<uint32_t> SHADER_MODULE_STATE::MarkAccessibleIds(spirv_inst_iter entrypoint) const {
166 layer_data::unordered_set<uint32_t> ids;
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600167 if (entrypoint == end() || !has_valid_spirv) {
168 return ids;
169 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700170 layer_data::unordered_set<uint32_t> worklist;
171 worklist.insert(entrypoint.word(2));
172
173 while (!worklist.empty()) {
174 auto id_iter = worklist.begin();
175 auto id = *id_iter;
176 worklist.erase(id_iter);
177
178 auto insn = get_def(id);
179 if (insn == end()) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600180 // ID is something we didn't collect in SpirvStaticData. that's OK -- we'll stumble across all kinds of things here
sfricke-samsung962cad92021-04-13 00:46:29 -0700181 // that we may not care about.
182 continue;
183 }
184
185 // Try to add to the output set
186 if (!ids.insert(id).second) {
187 continue; // If we already saw this id, we don't want to walk it again.
188 }
189
190 switch (insn.opcode()) {
191 case spv::OpFunction:
192 // Scan whole body of the function, enlisting anything interesting
193 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
194 switch (insn.opcode()) {
195 case spv::OpLoad:
196 worklist.insert(insn.word(3)); // ptr
197 break;
198 case spv::OpStore:
199 worklist.insert(insn.word(1)); // ptr
200 break;
201 case spv::OpAccessChain:
202 case spv::OpInBoundsAccessChain:
203 worklist.insert(insn.word(3)); // base ptr
204 break;
205 case spv::OpSampledImage:
206 case spv::OpImageSampleImplicitLod:
207 case spv::OpImageSampleExplicitLod:
208 case spv::OpImageSampleDrefImplicitLod:
209 case spv::OpImageSampleDrefExplicitLod:
210 case spv::OpImageSampleProjImplicitLod:
211 case spv::OpImageSampleProjExplicitLod:
212 case spv::OpImageSampleProjDrefImplicitLod:
213 case spv::OpImageSampleProjDrefExplicitLod:
214 case spv::OpImageFetch:
215 case spv::OpImageGather:
216 case spv::OpImageDrefGather:
217 case spv::OpImageRead:
218 case spv::OpImage:
219 case spv::OpImageQueryFormat:
220 case spv::OpImageQueryOrder:
221 case spv::OpImageQuerySizeLod:
222 case spv::OpImageQuerySize:
223 case spv::OpImageQueryLod:
224 case spv::OpImageQueryLevels:
225 case spv::OpImageQuerySamples:
226 case spv::OpImageSparseSampleImplicitLod:
227 case spv::OpImageSparseSampleExplicitLod:
228 case spv::OpImageSparseSampleDrefImplicitLod:
229 case spv::OpImageSparseSampleDrefExplicitLod:
230 case spv::OpImageSparseSampleProjImplicitLod:
231 case spv::OpImageSparseSampleProjExplicitLod:
232 case spv::OpImageSparseSampleProjDrefImplicitLod:
233 case spv::OpImageSparseSampleProjDrefExplicitLod:
234 case spv::OpImageSparseFetch:
235 case spv::OpImageSparseGather:
236 case spv::OpImageSparseDrefGather:
237 case spv::OpImageTexelPointer:
238 worklist.insert(insn.word(3)); // Image or sampled image
239 break;
240 case spv::OpImageWrite:
241 worklist.insert(insn.word(1)); // Image -- different operand order to above
242 break;
243 case spv::OpFunctionCall:
244 for (uint32_t i = 3; i < insn.len(); i++) {
245 worklist.insert(insn.word(i)); // fn itself, and all args
246 }
247 break;
248
249 case spv::OpExtInst:
250 for (uint32_t i = 5; i < insn.len(); i++) {
251 worklist.insert(insn.word(i)); // Operands to ext inst
252 }
253 break;
254
255 default: {
256 if (AtomicOperation(insn.opcode())) {
257 if (insn.opcode() == spv::OpAtomicStore) {
258 worklist.insert(insn.word(1)); // ptr
259 } else {
260 worklist.insert(insn.word(3)); // ptr
261 }
262 }
263 break;
264 }
265 }
266 }
267 break;
268 }
269 }
270
271 return ids;
272}
273
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600274layer_data::optional<VkPrimitiveTopology> SHADER_MODULE_STATE::GetTopology(const spirv_inst_iter &entrypoint) const {
275 layer_data::optional<VkPrimitiveTopology> result;
276
sfricke-samsung962cad92021-04-13 00:46:29 -0700277 auto entrypoint_id = entrypoint.word(2);
278 bool is_point_mode = false;
279
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600280 auto it = static_data_.execution_mode_inst.find(entrypoint_id);
281 if (it != static_data_.execution_mode_inst.end()) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700282 for (auto insn : it->second) {
283 switch (insn.word(2)) {
284 case spv::ExecutionModePointMode:
285 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
286 is_point_mode = true;
287 break;
288
289 case spv::ExecutionModeOutputPoints:
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600290 result.emplace(VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
sfricke-samsung962cad92021-04-13 00:46:29 -0700291 break;
292
293 case spv::ExecutionModeIsolines:
294 case spv::ExecutionModeOutputLineStrip:
Ricardo Garcia122f8f02021-09-28 16:47:19 +0200295 case spv::ExecutionModeOutputLinesNV:
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600296 result.emplace(VK_PRIMITIVE_TOPOLOGY_LINE_STRIP);
sfricke-samsung962cad92021-04-13 00:46:29 -0700297 break;
298
299 case spv::ExecutionModeTriangles:
300 case spv::ExecutionModeQuads:
301 case spv::ExecutionModeOutputTriangleStrip:
302 case spv::ExecutionModeOutputTrianglesNV:
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600303 result.emplace(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP);
sfricke-samsung962cad92021-04-13 00:46:29 -0700304 break;
305 }
306 }
307 }
308
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600309 if (is_point_mode) {
310 result.emplace(VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
311 }
312
313 return result;
sfricke-samsung962cad92021-04-13 00:46:29 -0700314}
315
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -0700316layer_data::optional<VkPrimitiveTopology> SHADER_MODULE_STATE::GetTopology() const {
317 if (static_data_.entry_points.size() > 0) {
318 const auto entrypoint = static_data_.entry_points.cbegin()->second;
319 return GetTopology(get_def(entrypoint.offset));
320 }
321 return {};
322}
323
sfricke-samsungef15e482022-01-26 11:32:49 -0800324SHADER_MODULE_STATE::SpirvStaticData::SpirvStaticData(const SHADER_MODULE_STATE &module_state) {
325 for (auto insn : module_state) {
sfricke-samsung5a48ed42022-02-13 17:37:13 -0800326 const uint32_t result_word = OpcodeResultWord(insn.opcode());
327 if (result_word != 0) {
328 def_index[insn.word(result_word)] = insn.offset();
329 }
330
sfricke-samsung962cad92021-04-13 00:46:29 -0700331 switch (insn.opcode()) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700332 // Specialization constants
333 case spv::OpSpecConstantTrue:
334 case spv::OpSpecConstantFalse:
335 case spv::OpSpecConstant:
336 case spv::OpSpecConstantComposite:
337 case spv::OpSpecConstantOp:
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600338 has_specialization_constants = true;
sfricke-samsung962cad92021-04-13 00:46:29 -0700339 break;
340
sfricke-samsung962cad92021-04-13 00:46:29 -0700341 // Decorations
342 case spv::OpDecorate: {
343 auto target_id = insn.word(1);
344 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
345 decoration_inst.push_back(insn);
346 if (insn.word(2) == spv::DecorationBuiltIn) {
347 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(3)));
Nathaniel Cesariocf69bda2021-06-22 13:23:42 -0600348 } else if (insn.word(2) == spv::DecorationSpecId) {
349 spec_const_map[insn.word(3)] = target_id;
sfricke-samsung962cad92021-04-13 00:46:29 -0700350 }
351
352 } break;
353 case spv::OpGroupDecorate: {
354 auto const &src = decorations[insn.word(1)];
355 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600356 has_group_decoration = true;
357 } break;
358 case spv::OpDecorationGroup:
359 case spv::OpGroupMemberDecorate: {
360 has_group_decoration = true;
sfricke-samsung962cad92021-04-13 00:46:29 -0700361 } break;
362 case spv::OpMemberDecorate: {
363 member_decoration_inst.push_back(insn);
364 if (insn.word(3) == spv::DecorationBuiltIn) {
365 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(4)));
366 }
367 } break;
368
ziga-lunargbe003732022-04-22 00:20:13 +0200369 case spv::OpCapability:
370 capability_list.push_back(static_cast<spv::Capability>(insn.word(1)));
371 break;
372
sjfricke44d663c2022-06-01 06:42:58 +0900373 case spv::OpVariable:
374 variable_inst.push_back(insn);
375 break;
376
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600377 // Execution Mode
sfricke-samsung61d50ec2022-02-13 17:01:25 -0800378 case spv::OpExecutionMode:
379 case spv::OpExecutionModeId: {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600380 execution_mode_inst[insn.word(1)].push_back(insn);
381 } break;
sjfricke657dfdc2022-08-25 23:40:32 +0900382 // Listed from vkspec.html#ray-tracing-repack
ziga-lunarge25f5f02022-04-16 15:07:35 +0200383 case spv::OpTraceRayKHR:
384 case spv::OpTraceRayMotionNV:
385 case spv::OpReportIntersectionKHR:
386 case spv::OpExecuteCallableKHR:
387 has_invocation_repack_instruction = true;
388 break;
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600389
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600390 default:
391 if (AtomicOperation(insn.opcode()) == true) {
392 // All atomics have a pointer referenced
393 spirv_inst_iter access;
394 if (insn.opcode() == spv::OpAtomicStore) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800395 access = module_state.get_def(insn.word(1));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600396 } else {
sfricke-samsungef15e482022-01-26 11:32:49 -0800397 access = module_state.get_def(insn.word(3));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600398 }
399
400 atomic_instruction atomic;
401
sfricke-samsungef15e482022-01-26 11:32:49 -0800402 auto pointer = module_state.get_def(access.word(1));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600403 // spirv-val should catch if not pointer
404 assert(pointer.opcode() == spv::OpTypePointer);
405 atomic.storage_class = pointer.word(2);
406
sfricke-samsungef15e482022-01-26 11:32:49 -0800407 auto data_type = module_state.get_def(pointer.word(3));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600408 atomic.type = data_type.opcode();
409
410 // TODO - Should have a proper GetBitWidth like spirv-val does
411 assert(data_type.opcode() == spv::OpTypeFloat || data_type.opcode() == spv::OpTypeInt);
412 atomic.bit_width = data_type.word(2);
413
414 atomic_inst[insn.offset()] = atomic;
415 }
416 // We don't care about any other defs for now.
417 break;
418 }
419 }
420
sfricke-samsungef15e482022-01-26 11:32:49 -0800421 entry_points = SHADER_MODULE_STATE::ProcessEntryPoints(module_state);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600422 multiple_entry_points = entry_points.size() > 1;
423}
424
425// static
426std::unordered_multimap<std::string, SHADER_MODULE_STATE::EntryPoint> SHADER_MODULE_STATE::ProcessEntryPoints(
sfricke-samsungef15e482022-01-26 11:32:49 -0800427 const SHADER_MODULE_STATE &module_state) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600428 std::unordered_multimap<std::string, SHADER_MODULE_STATE::EntryPoint> entry_points;
429 function_set func_set = {};
430 EntryPoint *entry_point = nullptr;
431
sfricke-samsungef15e482022-01-26 11:32:49 -0800432 for (auto insn : module_state) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600433 // offset is not 0, it means it's updated and the offset is in a Function.
434 if (func_set.offset) {
435 func_set.op_lists.emplace(insn.opcode(), insn.offset());
436 } else if (entry_point) {
437 entry_point->decorate_list.emplace(insn.opcode(), insn.offset());
438 }
439
440 switch (insn.opcode()) {
441 // Functions
442 case spv::OpFunction:
443 func_set.id = insn.word(2);
444 func_set.offset = insn.offset();
445 func_set.op_lists.clear();
446 break;
447
448 // Entry points ... add to the entrypoint table
449 case spv::OpEntryPoint: {
sfricke-samsung962cad92021-04-13 00:46:29 -0700450 // Entry points do not have an id (the id is the function id) and thus need their own table
451 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
452 auto execution_model = insn.word(1);
453 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
454 entry_points.emplace(entrypoint_name,
455 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
456
457 auto range = entry_points.equal_range(entrypoint_name);
458 for (auto it = range.first; it != range.second; ++it) {
459 if (it->second.offset == insn.offset()) {
460 entry_point = &(it->second);
461 break;
462 }
463 }
464 assert(entry_point != nullptr);
465 break;
466 }
467 case spv::OpFunctionEnd: {
468 assert(entry_point != nullptr);
469 func_set.length = insn.offset() - func_set.offset;
470 entry_point->function_set_list.emplace_back(func_set);
471 break;
472 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700473 }
474 }
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600475
sfricke-samsungef15e482022-01-26 11:32:49 -0800476 SHADER_MODULE_STATE::SetPushConstantUsedInShader(module_state, entry_points);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600477 return entry_points;
sfricke-samsung962cad92021-04-13 00:46:29 -0700478}
479
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600480void SHADER_MODULE_STATE::PreprocessShaderBinary(const spv_target_env env) {
481 if (static_data_.has_group_decoration) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700482 spvtools::Optimizer optimizer(env);
483 optimizer.RegisterPass(spvtools::CreateFlattenDecorationPass());
484 std::vector<uint32_t> optimized_binary;
485 // Run optimizer to flatten decorations only, set skip_validation so as to not re-run validator
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600486 auto result = optimizer.Run(words.data(), words.size(), &optimized_binary, spvtools::ValidatorOptions(), true);
487
sfricke-samsung962cad92021-04-13 00:46:29 -0700488 if (result) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600489 // NOTE: We need to update words with the result from the spirv-tools optimizer.
490 // **THIS ONLY HAPPENS ON INITIALIZATION**. words should remain const for the lifetime
491 // of the SHADER_MODULE_STATE instance.
492 *const_cast<std::vector<uint32_t> *>(&words) = std::move(optimized_binary);
sjfrickededec242022-08-25 15:18:38 +0900493 // Will need to update static data now the words have changed or else the def_index will not align
494 // It is really rare this will get here as Group Decorations have been deprecated and before this was added no one ever
495 // raised an issue for a bug that would crash the layers that was around for many releases
496 *const_cast<SpirvStaticData *>(&static_data_) = SpirvStaticData(*this);
sfricke-samsung962cad92021-04-13 00:46:29 -0700497 }
498 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700499}
500
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800501void SHADER_MODULE_STATE::DescribeTypeInner(std::ostringstream &ss, uint32_t type) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700502 auto insn = get_def(type);
503 assert(insn != end());
504
505 switch (insn.opcode()) {
506 case spv::OpTypeBool:
507 ss << "bool";
508 break;
509 case spv::OpTypeInt:
510 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
511 break;
512 case spv::OpTypeFloat:
513 ss << "float" << insn.word(2);
514 break;
515 case spv::OpTypeVector:
516 ss << "vec" << insn.word(3) << " of ";
517 DescribeTypeInner(ss, insn.word(2));
518 break;
519 case spv::OpTypeMatrix:
520 ss << "mat" << insn.word(3) << " of ";
521 DescribeTypeInner(ss, insn.word(2));
522 break;
523 case spv::OpTypeArray:
524 ss << "arr[" << GetConstantValueById(insn.word(3)) << "] of ";
525 DescribeTypeInner(ss, insn.word(2));
526 break;
527 case spv::OpTypeRuntimeArray:
528 ss << "runtime arr[] of ";
529 DescribeTypeInner(ss, insn.word(2));
530 break;
531 case spv::OpTypePointer:
sjfricke657dfdc2022-08-25 23:40:32 +0900532 ss << "ptr to " << string_SpvStorageClass(insn.word(2)) << " ";
sfricke-samsung962cad92021-04-13 00:46:29 -0700533 DescribeTypeInner(ss, insn.word(3));
534 break;
535 case spv::OpTypeStruct: {
536 ss << "struct of (";
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800537 for (uint32_t i = 2; i < insn.len(); i++) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700538 DescribeTypeInner(ss, insn.word(i));
539 if (i == insn.len() - 1) {
540 ss << ")";
541 } else {
542 ss << ", ";
543 }
544 }
545 break;
546 }
547 case spv::OpTypeSampler:
548 ss << "sampler";
549 break;
550 case spv::OpTypeSampledImage:
551 ss << "sampler+";
552 DescribeTypeInner(ss, insn.word(2));
553 break;
554 case spv::OpTypeImage:
555 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
556 break;
557 case spv::OpTypeAccelerationStructureNV:
558 ss << "accelerationStruture";
559 break;
560 default:
561 ss << "oddtype";
562 break;
563 }
564}
565
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800566std::string SHADER_MODULE_STATE::DescribeType(uint32_t type) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700567 std::ostringstream ss;
568 DescribeTypeInner(ss, type);
569 return ss.str();
570}
571
sfricke-samsung7a9bdca2022-01-24 14:38:03 -0800572std::string SHADER_MODULE_STATE::DescribeInstruction(const spirv_inst_iter &insn) const {
573 std::ostringstream ss;
574 const uint32_t opcode = insn.opcode();
575 uint32_t operand_offset = 1; // where to start printing operands
576 // common disassembled for SPIR-V is
577 // %result = Opcode %result_type %operands
578 if (OpcodeHasResult(opcode)) {
579 operand_offset++;
580 ss << "%" << (OpcodeHasType(opcode) ? insn.word(2) : insn.word(1)) << " = ";
581 }
582
583 ss << string_SpvOpcode(opcode);
584
585 if (OpcodeHasType(opcode)) {
586 operand_offset++;
587 ss << " %" << insn.word(1);
588 }
589
sfricke-samsunged00aa42022-01-27 19:03:01 -0800590 // TODO - For now don't list the '%' for any operands since they are only for reference IDs. Without generating a table of each
591 // instructions operand types and covering the many edge cases (such as optional, paired, or variable operands) this is the
592 // simplest way to print the instruction and give the developer something to look into when an error occurs.
593 //
594 // For now this safely should be able to assume it will never come across a LiteralString such as in OpExtInstImport or
595 // OpEntryPoint
sfricke-samsung7a9bdca2022-01-24 14:38:03 -0800596 for (uint32_t i = operand_offset; i < insn.len(); i++) {
sfricke-samsunged00aa42022-01-27 19:03:01 -0800597 ss << " " << insn.word(i);
sfricke-samsung7a9bdca2022-01-24 14:38:03 -0800598 }
599 return ss.str();
600}
601
sfricke-samsung962cad92021-04-13 00:46:29 -0700602const SHADER_MODULE_STATE::EntryPoint *SHADER_MODULE_STATE::FindEntrypointStruct(char const *name,
603 VkShaderStageFlagBits stageBits) const {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600604 auto range = static_data_.entry_points.equal_range(name);
sfricke-samsung962cad92021-04-13 00:46:29 -0700605 for (auto it = range.first; it != range.second; ++it) {
606 if (it->second.stage == stageBits) {
607 return &(it->second);
608 }
609 }
610 return nullptr;
611}
612
613spirv_inst_iter SHADER_MODULE_STATE::FindEntrypoint(char const *name, VkShaderStageFlagBits stageBits) const {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600614 auto range = static_data_.entry_points.equal_range(name);
sfricke-samsung962cad92021-04-13 00:46:29 -0700615 for (auto it = range.first; it != range.second; ++it) {
616 if (it->second.stage == stageBits) {
617 return at(it->second.offset);
618 }
619 }
620 return end();
621}
622
623// Because the following is legal, need the entry point
624// OpEntryPoint GLCompute %main "name_a"
625// OpEntryPoint GLCompute %main "name_b"
sfricke-samsung61d50ec2022-02-13 17:01:25 -0800626// Assumes shader module contains no spec constants used to set the local size values
sfricke-samsung962cad92021-04-13 00:46:29 -0700627bool SHADER_MODULE_STATE::FindLocalSize(const spirv_inst_iter &entrypoint, uint32_t &local_size_x, uint32_t &local_size_y,
628 uint32_t &local_size_z) const {
sfricke-samsung61d50ec2022-02-13 17:01:25 -0800629 // "If an object is decorated with the WorkgroupSize decoration, this takes precedence over any LocalSize or LocalSizeId
630 // execution mode."
631 for (const auto &builtin : static_data_.builtin_decoration_list) {
632 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
633 const uint32_t workgroup_size_id = at(builtin.offset).word(1);
634 auto composite_def = get_def(workgroup_size_id);
635 if (composite_def.opcode() == spv::OpConstantComposite) {
636 // VUID-WorkgroupSize-WorkgroupSize-04427 makes sure this is a OpTypeVector of int32
sjfricke3b0cb102022-08-10 16:27:45 +0900637 local_size_x = GetConstantValueById(composite_def.word(3));
638 local_size_y = GetConstantValueById(composite_def.word(4));
639 local_size_z = GetConstantValueById(composite_def.word(5));
sfricke-samsung962cad92021-04-13 00:46:29 -0700640 return true;
641 }
642 }
643 }
sfricke-samsung61d50ec2022-02-13 17:01:25 -0800644
645 auto entrypoint_id = entrypoint.word(2);
646 auto it = static_data_.execution_mode_inst.find(entrypoint_id);
647 if (it != static_data_.execution_mode_inst.end()) {
648 for (auto insn : it->second) {
649 if (insn.opcode() == spv::OpExecutionMode && insn.word(2) == spv::ExecutionModeLocalSize) {
650 local_size_x = insn.word(3);
651 local_size_y = insn.word(4);
652 local_size_z = insn.word(5);
653 return true;
654 } else if (insn.opcode() == spv::OpExecutionModeId && insn.word(2) == spv::ExecutionModeLocalSizeId) {
655 local_size_x = GetConstantValueById(insn.word(3));
656 local_size_y = GetConstantValueById(insn.word(4));
657 local_size_z = GetConstantValueById(insn.word(5));
658 return true;
659 }
660 }
661 }
662 return false; // not found
sfricke-samsung962cad92021-04-13 00:46:29 -0700663}
664
665// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
666// Otherwise, returns src->end().
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800667spirv_inst_iter SHADER_MODULE_STATE::GetConstantDef(uint32_t id) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700668 auto value = get_def(id);
669
670 // If id is a copy, see where it was copied from
671 if ((end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
672 id = value.word(3);
673 value = get_def(id);
674 }
675
676 if ((end() != value) && (value.opcode() == spv::OpConstant)) {
677 return value;
678 }
679 return end();
680}
681
sjfricke3b0cb102022-08-10 16:27:45 +0900682// While simple, function name provides a more human readable description why word(3) is used
683uint32_t SHADER_MODULE_STATE::GetConstantValue(const spirv_inst_iter &itr) const {
sjfricke284a13f2022-08-16 15:34:31 +0900684 // This should be a OpConstant (not a OpSpecConstant), if this asserts then 2 things are happening
685 // 1. This function is being used where we don't actually know it is a constant and is a bug in the validation layers
686 // 2. The CreateFoldSpecConstantOpAndCompositePass didn't fully fold everything and is a bug in spirv-opt
sjfricke3b0cb102022-08-10 16:27:45 +0900687 assert(itr.opcode() == spv::OpConstant);
688 return itr.word(3);
689}
690
sfricke-samsung962cad92021-04-13 00:46:29 -0700691// Either returns the constant value described by the instruction at id, or 1
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800692uint32_t SHADER_MODULE_STATE::GetConstantValueById(uint32_t id) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700693 auto value = GetConstantDef(id);
694
695 if (end() == value) {
696 // TODO: Either ensure that the specialization transform is already performed on a module we're
697 // considering here, OR -- specialize on the fly now.
698 return 1;
699 }
sjfricke3b0cb102022-08-10 16:27:45 +0900700
sfricke-samsung962cad92021-04-13 00:46:29 -0700701 return GetConstantValue(value);
702}
703
704// Returns an int32_t corresponding to the spv::Dim of the given resource, when positive, and corresponding to an unknown type, when
705// negative.
706int32_t SHADER_MODULE_STATE::GetShaderResourceDimensionality(const interface_var &resource) const {
707 auto type = get_def(resource.type_id);
708 while (true) {
709 switch (type.opcode()) {
710 case spv::OpTypeSampledImage:
711 type = get_def(type.word(2));
712 break;
713 case spv::OpTypePointer:
714 type = get_def(type.word(3));
715 break;
716 case spv::OpTypeImage:
717 return type.word(3);
718 default:
719 return -1;
720 }
721 }
722}
723
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800724uint32_t SHADER_MODULE_STATE::GetLocationsConsumedByType(uint32_t type, bool strip_array_level) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700725 auto insn = get_def(type);
726 assert(insn != end());
727
728 switch (insn.opcode()) {
729 case spv::OpTypePointer:
730 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
731 // pointers around.
732 return GetLocationsConsumedByType(insn.word(3), strip_array_level);
733 case spv::OpTypeArray:
734 if (strip_array_level) {
735 return GetLocationsConsumedByType(insn.word(2), false);
736 } else {
737 return GetConstantValueById(insn.word(3)) * GetLocationsConsumedByType(insn.word(2), false);
738 }
739 case spv::OpTypeMatrix:
740 // Num locations is the dimension * element size
741 return insn.word(3) * GetLocationsConsumedByType(insn.word(2), false);
742 case spv::OpTypeVector: {
743 auto scalar_type = get_def(insn.word(2));
744 auto bit_width =
745 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
746
747 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
748 return (bit_width * insn.word(3) + 127) / 128;
749 }
750 default:
751 // Everything else is just 1.
752 return 1;
753
754 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
755 }
756}
757
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800758uint32_t SHADER_MODULE_STATE::GetComponentsConsumedByType(uint32_t type, bool strip_array_level) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700759 auto insn = get_def(type);
760 assert(insn != end());
761
762 switch (insn.opcode()) {
763 case spv::OpTypePointer:
764 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
765 // pointers around.
766 return GetComponentsConsumedByType(insn.word(3), strip_array_level);
767 case spv::OpTypeStruct: {
768 uint32_t sum = 0;
769 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
770 sum += GetComponentsConsumedByType(insn.word(i), false);
771 }
772 return sum;
773 }
774 case spv::OpTypeArray:
775 if (strip_array_level) {
776 return GetComponentsConsumedByType(insn.word(2), false);
777 } else {
778 return GetConstantValueById(insn.word(3)) * GetComponentsConsumedByType(insn.word(2), false);
779 }
780 case spv::OpTypeMatrix:
781 // Num locations is the dimension * element size
782 return insn.word(3) * GetComponentsConsumedByType(insn.word(2), false);
783 case spv::OpTypeVector: {
784 auto scalar_type = get_def(insn.word(2));
785 auto bit_width =
786 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
787 // One component is 32-bit
788 return (bit_width * insn.word(3) + 31) / 32;
789 }
790 case spv::OpTypeFloat: {
791 auto bit_width = insn.word(2);
792 return (bit_width + 31) / 32;
793 }
794 case spv::OpTypeInt: {
795 auto bit_width = insn.word(2);
796 return (bit_width + 31) / 32;
797 }
798 case spv::OpConstant:
799 return GetComponentsConsumedByType(insn.word(1), false);
800 default:
801 return 0;
802 }
803}
804
805// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
806// also used for input attachments, as we statically know their format.
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800807uint32_t SHADER_MODULE_STATE::GetFundamentalType(uint32_t type) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700808 auto insn = get_def(type);
809 assert(insn != end());
810
811 switch (insn.opcode()) {
812 case spv::OpTypeInt:
813 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
814 case spv::OpTypeFloat:
815 return FORMAT_TYPE_FLOAT;
816 case spv::OpTypeVector:
817 case spv::OpTypeMatrix:
818 case spv::OpTypeArray:
819 case spv::OpTypeRuntimeArray:
820 case spv::OpTypeImage:
821 return GetFundamentalType(insn.word(2));
822 case spv::OpTypePointer:
823 return GetFundamentalType(insn.word(3));
824
825 default:
826 return 0;
827 }
828}
829
830spirv_inst_iter SHADER_MODULE_STATE::GetStructType(spirv_inst_iter def, bool is_array_of_verts) const {
831 while (true) {
832 if (def.opcode() == spv::OpTypePointer) {
833 def = get_def(def.word(3));
834 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
835 def = get_def(def.word(2));
836 is_array_of_verts = false;
837 } else if (def.opcode() == spv::OpTypeStruct) {
838 return def;
839 } else {
840 return end();
841 }
842 }
843}
844
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800845void SHADER_MODULE_STATE::DefineStructMember(const spirv_inst_iter &it, const std::vector<uint32_t> &member_decorate_offsets,
sfricke-samsung962cad92021-04-13 00:46:29 -0700846 shader_struct_member &data) const {
847 const auto struct_it = GetStructType(it, false);
848 assert(struct_it != end());
849 data.size = 0;
850
851 shader_struct_member data1;
852 uint32_t i = 2;
853 uint32_t local_offset = 0;
854 std::vector<uint32_t> offsets;
855 offsets.resize(struct_it.len() - i);
856
857 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800858 for (const auto offset : member_decorate_offsets) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700859 const auto member_decorate = at(offset);
860 if (member_decorate.word(1) != struct_it.word(1)) {
861 continue;
862 }
863
864 offsets[member_decorate.word(2)] = member_decorate.word(4);
865 }
866
867 for (const auto offset : offsets) {
868 local_offset = offset;
869 data1 = {};
870 data1.root = data.root;
871 data1.offset = local_offset;
872 auto def_member = get_def(struct_it.word(i));
873
874 // Array could be multi-dimensional
875 while (def_member.opcode() == spv::OpTypeArray) {
876 const auto len_id = def_member.word(3);
877 const auto def_len = get_def(len_id);
878 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
879 def_member = get_def(def_member.word(2));
880 }
881
882 if (def_member.opcode() == spv::OpTypeStruct) {
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800883 DefineStructMember(def_member, member_decorate_offsets, data1);
sfricke-samsung962cad92021-04-13 00:46:29 -0700884 } else if (def_member.opcode() == spv::OpTypePointer) {
885 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
886 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
887 // that "points to something."
888 data1.size = 8;
889 } else {
890 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800891 DefineStructMember(def_member, member_decorate_offsets, data1);
sfricke-samsung962cad92021-04-13 00:46:29 -0700892 }
893 } else {
894 if (def_member.opcode() == spv::OpTypeMatrix) {
895 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
896 def_member = get_def(def_member.word(2));
897 }
898
899 if (def_member.opcode() == spv::OpTypeVector) {
900 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
901 def_member = get_def(def_member.word(2));
902 }
903
904 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
905 data1.size = (def_member.word(2) / 8);
906 }
907 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
908 if (array_length_hierarchy_szie > 0) {
909 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
910
911 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
912 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
913 }
914 }
915 data.struct_members.emplace_back(data1);
916 ++i;
917 }
918 uint32_t total_array_length = 1;
919 for (const auto length : data1.array_length_hierarchy) {
920 total_array_length *= length;
921 }
922 data.size = local_offset + data1.size * total_array_length;
923}
924
925static uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
926 int array_indices_size = static_cast<int>(array_indices.size());
927 if (array_indices_size) {
928 uint32_t array_index = 0;
929 uint32_t i = 0;
930 for (const auto index : array_indices) {
931 array_index += (data.array_block_size[i] * index);
932 ++i;
933 }
934 offset += (array_index * data.size);
935 }
936 return offset;
937}
938
939static void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
940 int array_indices_size = static_cast<int>(array_indices.size());
941 uint32_t block_memory_size = data.size;
942 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
943 block_memory_size *= data.array_length_hierarchy[i];
944 }
945
946 offset = UpdateOffset(offset, array_indices, data);
947
948 uint32_t end = offset + block_memory_size;
949 auto used_bytes = data.GetUsedbytes();
950 if (used_bytes->size() < end) {
951 used_bytes->resize(end, 0);
952 }
953 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
954}
955
956void SHADER_MODULE_STATE::RunUsedArray(uint32_t offset, std::vector<uint32_t> array_indices, uint32_t access_chain_word_index,
957 spirv_inst_iter &access_chain_it, const shader_struct_member &data) const {
958 if (access_chain_word_index < access_chain_it.len()) {
959 if (data.array_length_hierarchy.size() > array_indices.size()) {
960 auto def_it = get_def(access_chain_it.word(access_chain_word_index));
961 ++access_chain_word_index;
962
963 if (def_it != end() && def_it.opcode() == spv::OpConstant) {
964 array_indices.emplace_back(def_it.word(3));
965 RunUsedArray(offset, array_indices, access_chain_word_index, access_chain_it, data);
966 } else {
967 // If it is a variable, set the all array is used.
968 if (access_chain_word_index < access_chain_it.len()) {
969 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
970 for (uint32_t i = 0; i < array_length; ++i) {
971 auto array_indices2 = array_indices;
972 array_indices2.emplace_back(i);
973 RunUsedArray(offset, array_indices2, access_chain_word_index, access_chain_it, data);
974 }
975 } else {
976 SetUsedBytes(offset, array_indices, data);
977 }
978 }
979 } else {
980 offset = UpdateOffset(offset, array_indices, data);
981 RunUsedStruct(offset, access_chain_word_index, access_chain_it, data);
982 }
983 } else {
984 SetUsedBytes(offset, array_indices, data);
985 }
986}
987
988void SHADER_MODULE_STATE::RunUsedStruct(uint32_t offset, uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it,
989 const shader_struct_member &data) const {
990 std::vector<uint32_t> array_indices_emptry;
991
992 if (access_chain_word_index < access_chain_it.len()) {
993 auto strcut_member_index = GetConstantValueById(access_chain_it.word(access_chain_word_index));
994 ++access_chain_word_index;
995
996 auto data1 = data.struct_members[strcut_member_index];
997 RunUsedArray(offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
998 }
999}
1000
1001void SHADER_MODULE_STATE::SetUsedStructMember(const uint32_t variable_id, const std::vector<function_set> &function_set_list,
1002 const shader_struct_member &data) const {
1003 for (const auto &func_set : function_set_list) {
1004 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1005 for (auto it = range.first; it != range.second; ++it) {
1006 auto access_chain = at(it->second);
1007 if (access_chain.word(3) == variable_id) {
1008 RunUsedStruct(0, 4, access_chain, data);
1009 }
1010 }
1011 }
1012}
1013
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001014// static
1015void SHADER_MODULE_STATE::SetPushConstantUsedInShader(
sfricke-samsungef15e482022-01-26 11:32:49 -08001016 const SHADER_MODULE_STATE &module_state, std::unordered_multimap<std::string, SHADER_MODULE_STATE::EntryPoint> &entry_points) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001017 for (auto &entrypoint : entry_points) {
1018 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1019 for (auto it = range.first; it != range.second; ++it) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001020 const auto def_insn = module_state.at(it->second);
sfricke-samsung962cad92021-04-13 00:46:29 -07001021
1022 if (def_insn.word(3) == spv::StorageClassPushConstant) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001023 spirv_inst_iter type = module_state.get_def(def_insn.word(1));
sfricke-samsung962cad92021-04-13 00:46:29 -07001024 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1025 std::vector<uint32_t> offsets;
1026
1027 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001028 auto member_decorate = module_state.at(it2->second);
sfricke-samsung962cad92021-04-13 00:46:29 -07001029 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1030 offsets.emplace_back(member_decorate.offset());
1031 }
1032 }
1033 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
sfricke-samsungef15e482022-01-26 11:32:49 -08001034 module_state.DefineStructMember(type, offsets, entrypoint.second.push_constant_used_in_shader);
1035 module_state.SetUsedStructMember(def_insn.word(2), entrypoint.second.function_set_list,
1036 entrypoint.second.push_constant_used_in_shader);
sfricke-samsung962cad92021-04-13 00:46:29 -07001037 }
1038 }
1039 }
1040}
1041
1042uint32_t SHADER_MODULE_STATE::DescriptorTypeToReqs(uint32_t type_id) const {
1043 auto type = get_def(type_id);
1044
1045 while (true) {
1046 switch (type.opcode()) {
1047 case spv::OpTypeArray:
1048 case spv::OpTypeRuntimeArray:
1049 case spv::OpTypeSampledImage:
1050 type = get_def(type.word(2));
1051 break;
1052 case spv::OpTypePointer:
1053 type = get_def(type.word(3));
1054 break;
1055 case spv::OpTypeImage: {
1056 auto dim = type.word(3);
1057 auto arrayed = type.word(5);
1058 auto msaa = type.word(6);
1059
1060 uint32_t bits = 0;
1061 switch (GetFundamentalType(type.word(2))) {
1062 case FORMAT_TYPE_FLOAT:
1063 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
1064 break;
1065 case FORMAT_TYPE_UINT:
1066 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
1067 break;
1068 case FORMAT_TYPE_SINT:
1069 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
1070 break;
1071 default:
1072 break;
1073 }
1074
1075 switch (dim) {
1076 case spv::Dim1D:
1077 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1078 return bits;
1079 case spv::Dim2D:
1080 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1081 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
1082 return bits;
1083 case spv::Dim3D:
1084 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
1085 return bits;
1086 case spv::DimCube:
1087 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1088 return bits;
1089 case spv::DimSubpassData:
1090 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1091 return bits;
1092 default: // buffer, etc.
1093 return bits;
1094 }
1095 }
1096 default:
1097 return 0;
1098 }
1099 }
1100}
1101
1102// For some built-in analysis we need to know if the variable decorated with as the built-in was actually written to.
1103// This function examines instructions in the static call tree for a write to this variable.
1104bool SHADER_MODULE_STATE::IsBuiltInWritten(spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) const {
1105 auto type = builtin_instr.opcode();
1106 uint32_t target_id = builtin_instr.word(1);
1107 bool init_complete = false;
Nathaniel Cesario80c0e0f2021-10-14 13:25:54 -06001108 uint32_t target_member_offset = 0;
sfricke-samsung962cad92021-04-13 00:46:29 -07001109
1110 if (type == spv::OpMemberDecorate) {
1111 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1112 auto insn = entrypoint;
1113 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1114 switch (insn.opcode()) {
1115 case spv::OpTypePointer:
Nathaniel Cesario58fc2282021-08-18 12:20:40 -06001116 if (insn.word(2) == spv::StorageClassOutput) {
1117 const auto type_id = insn.word(3);
1118 if (type_id == target_id) {
1119 target_id = insn.word(1);
1120 } else {
1121 // If the output is an array, check if the element type is what we're looking for
1122 const auto type_insn = get_def(type_id);
1123 if ((type_insn.opcode() == spv::OpTypeArray) && (type_insn.word(2) == target_id)) {
1124 target_id = insn.word(1);
Nathaniel Cesario80c0e0f2021-10-14 13:25:54 -06001125 target_member_offset = 1;
Nathaniel Cesario58fc2282021-08-18 12:20:40 -06001126 }
1127 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001128 }
1129 break;
1130 case spv::OpVariable:
1131 if (insn.word(1) == target_id) {
1132 target_id = insn.word(2);
1133 init_complete = true;
1134 }
1135 break;
1136 }
1137 insn++;
1138 }
1139 }
1140
1141 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1142
1143 bool found_write = false;
1144 layer_data::unordered_set<uint32_t> worklist;
1145 worklist.insert(entrypoint.word(2));
1146
1147 // Follow instructions in call graph looking for writes to target
1148 while (!worklist.empty() && !found_write) {
1149 auto id_iter = worklist.begin();
1150 auto id = *id_iter;
1151 worklist.erase(id_iter);
1152
1153 auto insn = get_def(id);
1154 if (insn == end()) {
1155 continue;
1156 }
1157
1158 if (insn.opcode() == spv::OpFunction) {
1159 // Scan body of function looking for other function calls or items in our ID chain
Nathaniel Cesario58fc2282021-08-18 12:20:40 -06001160 while (++insn, (insn.opcode() != spv::OpFunctionEnd) && !found_write) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001161 switch (insn.opcode()) {
1162 case spv::OpAccessChain:
sjfrickeeaa434d2022-06-22 04:55:28 +09001163 case spv::OpInBoundsAccessChain:
sfricke-samsung962cad92021-04-13 00:46:29 -07001164 if (insn.word(3) == target_id) {
1165 if (type == spv::OpMemberDecorate) {
Nathaniel Cesario80c0e0f2021-10-14 13:25:54 -06001166 // Get the target member of the struct
1167 // NOTE: this will only work for structs and arrays of structs. Deeper levels of nesting (e.g.,
1168 // arrays of structs of structs) is not currently supported.
1169 const auto value_itr = GetConstantDef(insn.word(4 + target_member_offset));
1170 if (value_itr != end()) {
1171 auto value = GetConstantValue(value_itr);
1172 if (value == builtin_instr.word(2)) {
1173 target_id = insn.word(2);
1174 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001175 }
1176 } else {
1177 target_id = insn.word(2);
1178 }
1179 }
1180 break;
1181 case spv::OpStore:
1182 if (insn.word(1) == target_id) {
1183 found_write = true;
1184 }
1185 break;
1186 case spv::OpFunctionCall:
1187 worklist.insert(insn.word(3));
1188 break;
1189 }
1190 }
1191 }
1192 }
1193 return found_write;
1194}
1195
1196// Used by the collection functions to help aid in state tracking
1197struct shader_module_used_operators {
1198 bool updated;
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001199 std::vector<uint32_t> image_read_members;
1200 std::vector<uint32_t> image_write_members;
1201 std::vector<uint32_t> atomic_members;
1202 std::vector<uint32_t> store_members;
1203 std::vector<uint32_t> atomic_store_members;
1204 std::vector<uint32_t> sampler_implicitLod_dref_proj_members; // sampler Load id
1205 std::vector<uint32_t> sampler_bias_offset_members; // sampler Load id
1206 std::vector<uint32_t> image_dref_members;
1207 std::vector<std::pair<uint32_t, uint32_t>> sampled_image_members; // <image,sampler> Load id
1208 layer_data::unordered_map<uint32_t, uint32_t> load_members;
1209 layer_data::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> accesschain_members;
1210 layer_data::unordered_map<uint32_t, uint32_t> image_texel_pointer_members;
sfricke-samsung962cad92021-04-13 00:46:29 -07001211
1212 shader_module_used_operators() : updated(false) {}
1213
1214 bool CheckImageOperandsBiasOffset(uint32_t type) {
1215 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1216 spv::ImageOperandsConstOffsetsMask)
1217 ? true
1218 : false;
1219 }
1220
sfricke-samsungef15e482022-01-26 11:32:49 -08001221 void update(SHADER_MODULE_STATE const *module_state) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001222 if (updated) return;
1223 updated = true;
1224
sfricke-samsungef15e482022-01-26 11:32:49 -08001225 for (auto insn : *module_state) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001226 switch (insn.opcode()) {
1227 case spv::OpImageSampleImplicitLod:
1228 case spv::OpImageSampleProjImplicitLod:
1229 case spv::OpImageSampleProjExplicitLod:
1230 case spv::OpImageSparseSampleImplicitLod:
1231 case spv::OpImageSparseSampleProjImplicitLod:
1232 case spv::OpImageSparseSampleProjExplicitLod: {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001233 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001234 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001235 auto load_id = (id.opcode() == spv::OpSampledImage) ? id.word(4) : insn.word(3);
1236 sampler_implicitLod_dref_proj_members.emplace_back(load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001237 // ImageOperands in index: 5
1238 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001239 sampler_bias_offset_members.emplace_back(load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001240 }
1241 break;
1242 }
Lionel Landwerlincdbe8682021-12-08 15:10:37 +02001243 case spv::OpImageDrefGather:
1244 case spv::OpImageSparseDrefGather: {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001245 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001246 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001247 auto load_id = (id.opcode() == spv::OpSampledImage) ? id.word(3) : insn.word(3);
1248 image_dref_members.emplace_back(load_id);
Lionel Landwerlincdbe8682021-12-08 15:10:37 +02001249 break;
1250 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001251 case spv::OpImageSampleDrefImplicitLod:
1252 case spv::OpImageSampleDrefExplicitLod:
1253 case spv::OpImageSampleProjDrefImplicitLod:
1254 case spv::OpImageSampleProjDrefExplicitLod:
1255 case spv::OpImageSparseSampleDrefImplicitLod:
1256 case spv::OpImageSparseSampleDrefExplicitLod:
1257 case spv::OpImageSparseSampleProjDrefImplicitLod:
1258 case spv::OpImageSparseSampleProjDrefExplicitLod: {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001259 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001260 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001261 auto sampler_load_id = (id.opcode() == spv::OpSampledImage) ? id.word(4) : insn.word(3);
1262 auto image_load_id = (id.opcode() == spv::OpSampledImage) ? id.word(3) : insn.word(3);
1263
1264 image_dref_members.emplace_back(image_load_id);
1265 sampler_implicitLod_dref_proj_members.emplace_back(sampler_load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001266 // ImageOperands in index: 6
1267 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001268 sampler_bias_offset_members.emplace_back(sampler_load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001269 }
1270 break;
1271 }
1272 case spv::OpImageSampleExplicitLod:
1273 case spv::OpImageSparseSampleExplicitLod: {
1274 // ImageOperands in index: 5
1275 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001276 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001277 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001278 auto load_id = (id.opcode() == spv::OpSampledImage) ? id.word(4) : insn.word(3);
1279 sampler_bias_offset_members.emplace_back(load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001280 }
1281 break;
1282 }
1283 case spv::OpStore: {
1284 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1285 break;
1286 }
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001287 case spv::OpImageRead:
1288 case spv::OpImageSparseRead: {
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001289 image_read_members.emplace_back(insn.word(3)); // Load id
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001290 break;
1291 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001292 case spv::OpImageWrite: {
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001293 image_write_members.emplace_back(insn.word(1)); // Load id
sfricke-samsung962cad92021-04-13 00:46:29 -07001294 break;
1295 }
1296 case spv::OpSampledImage: {
1297 // 3: image load id, 4: sampler load id
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001298 sampled_image_members.emplace_back(std::pair<uint32_t, uint32_t>(insn.word(3), insn.word(4)));
sfricke-samsung962cad92021-04-13 00:46:29 -07001299 break;
1300 }
1301 case spv::OpLoad: {
1302 // 2: Load id, 3: object id or AccessChain id
1303 load_members.emplace(insn.word(2), insn.word(3));
1304 break;
1305 }
sjfrickeeaa434d2022-06-22 04:55:28 +09001306 case spv::OpAccessChain:
1307 case spv::OpInBoundsAccessChain: {
sfricke-samsung962cad92021-04-13 00:46:29 -07001308 if (insn.len() == 4) {
1309 // If it is for struct, the length is only 4.
1310 // 2: AccessChain id, 3: object id
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001311 accesschain_members.emplace(insn.word(2), std::pair<uint32_t, uint32_t>(insn.word(3), 0));
sfricke-samsung962cad92021-04-13 00:46:29 -07001312 } else {
1313 // 2: AccessChain id, 3: object id, 4: object id of array index
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001314 accesschain_members.emplace(insn.word(2), std::pair<uint32_t, uint32_t>(insn.word(3), insn.word(4)));
sfricke-samsung962cad92021-04-13 00:46:29 -07001315 }
1316 break;
1317 }
1318 case spv::OpImageTexelPointer: {
1319 // 2: ImageTexelPointer id, 3: object id
1320 image_texel_pointer_members.emplace(insn.word(2), insn.word(3));
1321 break;
1322 }
1323 default: {
1324 if (AtomicOperation(insn.opcode())) {
1325 if (insn.opcode() == spv::OpAtomicStore) {
1326 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1327 } else {
1328 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1329 }
1330 }
1331 break;
1332 }
1333 }
1334 }
1335 }
1336};
1337
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001338static bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<uint32_t> &operator_members,
1339 const layer_data::unordered_map<uint32_t, uint32_t> &load_members,
1340 const layer_data::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> &accesschain_members) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001341 for (auto load_id : operator_members) {
1342 if (object_id == load_id) return true;
1343 auto load_it = load_members.find(load_id);
1344 if (load_it == load_members.end()) {
1345 continue;
1346 }
1347 if (load_it->second == object_id) {
1348 return true;
1349 }
1350
1351 auto accesschain_it = accesschain_members.find(load_it->second);
1352 if (accesschain_it == accesschain_members.end()) {
1353 continue;
1354 }
1355 if (accesschain_it->second.first == object_id) {
1356 return true;
1357 }
1358 }
1359 return false;
1360}
1361
1362// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1363// atomic operation, matching images to samplers, etc
1364void SHADER_MODULE_STATE::IsSpecificDescriptorType(const spirv_inst_iter &id_it, bool is_storage_buffer, bool is_check_writable,
sjfrickeeaa434d2022-06-22 04:55:28 +09001365 interface_var &out_interface_var) const {
1366 shader_module_used_operators used_operators;
sfricke-samsung962cad92021-04-13 00:46:29 -07001367 uint32_t type_id = id_it.word(1);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001368 uint32_t id = id_it.word(2);
sfricke-samsung962cad92021-04-13 00:46:29 -07001369
1370 auto type = get_def(type_id);
1371
1372 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
1373 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1374 type.opcode() == spv::OpTypeSampledImage) {
1375 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1376 type.opcode() == spv::OpTypeSampledImage) {
1377 type = get_def(type.word(2)); // Element type
1378 } else {
1379 type = get_def(type.word(3)); // Pointer type
1380 }
1381 }
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001382
sfricke-samsung962cad92021-04-13 00:46:29 -07001383 switch (type.opcode()) {
1384 case spv::OpTypeImage: {
1385 auto dim = type.word(3);
1386 if (dim != spv::DimSubpassData) {
1387 used_operators.update(this);
1388
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001389 // Sampled == 2 indicates used without a sampler (a storage image)
1390 bool is_image_without_format = false;
1391 if (type.word(7) == 2) is_image_without_format = type.word(8) == spv::ImageFormatUnknown;
1392
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001393 if (CheckObjectIDFromOpLoad(id, used_operators.image_write_members, used_operators.load_members,
sfricke-samsung962cad92021-04-13 00:46:29 -07001394 used_operators.accesschain_members)) {
1395 out_interface_var.is_writable = true;
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001396 if (is_image_without_format) out_interface_var.is_write_without_format = true;
1397 }
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001398 if (CheckObjectIDFromOpLoad(id, used_operators.image_read_members, used_operators.load_members,
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001399 used_operators.accesschain_members)) {
1400 out_interface_var.is_readable = true;
1401 if (is_image_without_format) out_interface_var.is_read_without_format = true;
sfricke-samsung962cad92021-04-13 00:46:29 -07001402 }
1403 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1404 used_operators.accesschain_members)) {
1405 out_interface_var.is_sampler_implicitLod_dref_proj = true;
1406 }
1407 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1408 used_operators.accesschain_members)) {
1409 out_interface_var.is_sampler_bias_offset = true;
1410 }
1411 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1412 used_operators.accesschain_members) ||
1413 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1414 used_operators.accesschain_members)) {
1415 out_interface_var.is_atomic_operation = true;
1416 }
Lionel Landwerlincdbe8682021-12-08 15:10:37 +02001417 if (CheckObjectIDFromOpLoad(id, used_operators.image_dref_members, used_operators.load_members,
1418 used_operators.accesschain_members)) {
1419 out_interface_var.is_dref_operation = true;
1420 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001421
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001422 for (auto &itp_id : used_operators.sampled_image_members) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001423 // Find if image id match.
1424 uint32_t image_index = 0;
1425 auto load_it = used_operators.load_members.find(itp_id.first);
1426 if (load_it == used_operators.load_members.end()) {
1427 continue;
1428 } else {
1429 if (load_it->second != id) {
1430 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1431 if (accesschain_it == used_operators.accesschain_members.end()) {
1432 continue;
1433 } else {
1434 if (accesschain_it->second.first != id) {
1435 continue;
1436 }
1437
1438 const auto const_itr = GetConstantDef(accesschain_it->second.second);
1439 if (const_itr == end()) {
1440 // access chain index not a constant, skip.
1441 break;
1442 }
1443 image_index = GetConstantValue(const_itr);
1444 }
1445 }
1446 }
1447 // Find sampler's set binding.
1448 load_it = used_operators.load_members.find(itp_id.second);
1449 if (load_it == used_operators.load_members.end()) {
1450 continue;
1451 } else {
1452 uint32_t sampler_id = load_it->second;
1453 uint32_t sampler_index = 0;
1454 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1455
1456 if (accesschain_it != used_operators.accesschain_members.end()) {
1457 const auto const_itr = GetConstantDef(accesschain_it->second.second);
1458 if (const_itr == end()) {
1459 // access chain index representing sampler index is not a constant, skip.
1460 break;
1461 }
1462 sampler_id = const_itr.offset();
1463 sampler_index = GetConstantValue(const_itr);
1464 }
1465 auto sampler_dec = get_decorations(sampler_id);
1466 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1467 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1468 }
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001469
1470 // Need to check again for these properties in case not using a combined image sampler
1471 if (CheckObjectIDFromOpLoad(sampler_id, used_operators.sampler_implicitLod_dref_proj_members,
1472 used_operators.load_members, used_operators.accesschain_members)) {
1473 out_interface_var.is_sampler_implicitLod_dref_proj = true;
1474 }
1475 if (CheckObjectIDFromOpLoad(sampler_id, used_operators.sampler_bias_offset_members,
1476 used_operators.load_members, used_operators.accesschain_members)) {
1477 out_interface_var.is_sampler_bias_offset = true;
1478 }
1479
sfricke-samsung962cad92021-04-13 00:46:29 -07001480 out_interface_var.samplers_used_by_image[image_index].emplace(
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001481 SamplerUsedByImage{DescriptorSlot{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
sfricke-samsung962cad92021-04-13 00:46:29 -07001482 }
1483 }
1484 }
1485 return;
1486 }
1487
1488 case spv::OpTypeStruct: {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001489 layer_data::unordered_set<uint32_t> nonwritable_members;
sfricke-samsung962cad92021-04-13 00:46:29 -07001490 if (get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001491 for (auto insn : static_data_.member_decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001492 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
1493 nonwritable_members.insert(insn.word(2));
1494 }
1495 }
1496
1497 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1498 // as nonwritable.
1499 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
1500 used_operators.update(this);
1501
1502 for (auto oid : used_operators.store_members) {
1503 if (id == oid) {
1504 out_interface_var.is_writable = true;
1505 return;
1506 }
1507 auto accesschain_it = used_operators.accesschain_members.find(oid);
1508 if (accesschain_it == used_operators.accesschain_members.end()) {
1509 continue;
1510 }
1511 if (accesschain_it->second.first == id) {
1512 out_interface_var.is_writable = true;
1513 return;
1514 }
1515 }
1516 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1517 used_operators.accesschain_members)) {
1518 out_interface_var.is_writable = true;
1519 return;
1520 }
1521 }
1522 }
1523 }
1524}
1525
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001526std::vector<std::pair<DescriptorSlot, interface_var>> SHADER_MODULE_STATE::CollectInterfaceByDescriptorSlot(
ziga-lunargc2de4782022-04-14 19:49:07 +02001527 layer_data::unordered_set<uint32_t> const &accessible_ids) const {
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001528 std::vector<std::pair<DescriptorSlot, interface_var>> out;
sfricke-samsung962cad92021-04-13 00:46:29 -07001529
ziga-lunargc2de4782022-04-14 19:49:07 +02001530 for (auto id : accessible_ids) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001531 auto insn = get_def(id);
1532 assert(insn != end());
1533
1534 if (insn.opcode() == spv::OpVariable &&
Lionel Landwerlin6a9f89c2021-12-07 15:46:46 +02001535 (insn.word(3) == spv::StorageClassUniform ||
1536 insn.word(3) == spv::StorageClassUniformConstant ||
sfricke-samsung962cad92021-04-13 00:46:29 -07001537 insn.word(3) == spv::StorageClassStorageBuffer)) {
1538 auto d = get_decorations(insn.word(2));
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001539 uint32_t set = d.descriptor_set;
1540 uint32_t binding = d.binding;
sfricke-samsung962cad92021-04-13 00:46:29 -07001541
1542 interface_var v = {};
1543 v.id = insn.word(2);
1544 v.type_id = insn.word(1);
1545
1546 IsSpecificDescriptorType(insn, insn.word(3) == spv::StorageClassStorageBuffer,
sjfrickeeaa434d2022-06-22 04:55:28 +09001547 !(d.flags & decoration_set::nonwritable_bit), v);
Jeremy Gebben84b838b2021-08-23 08:41:39 -06001548 out.emplace_back(DescriptorSlot{set, binding}, v);
sfricke-samsung962cad92021-04-13 00:46:29 -07001549 }
1550 }
1551
1552 return out;
1553}
1554
1555layer_data::unordered_set<uint32_t> SHADER_MODULE_STATE::CollectWritableOutputLocationinFS(
Jeremy Gebben84b838b2021-08-23 08:41:39 -06001556 const spirv_inst_iter &entrypoint) const {
sfricke-samsung962cad92021-04-13 00:46:29 -07001557 layer_data::unordered_set<uint32_t> location_list;
sfricke-samsung962cad92021-04-13 00:46:29 -07001558 const auto outputs = CollectInterfaceByLocation(entrypoint, spv::StorageClassOutput, false);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001559 layer_data::unordered_set<uint32_t> store_members;
1560 layer_data::unordered_map<uint32_t, uint32_t> accesschain_members;
sfricke-samsung962cad92021-04-13 00:46:29 -07001561
1562 for (auto insn : *this) {
1563 switch (insn.opcode()) {
1564 case spv::OpStore:
1565 case spv::OpAtomicStore: {
1566 store_members.insert(insn.word(1)); // object id or AccessChain id
1567 break;
1568 }
sjfrickeeaa434d2022-06-22 04:55:28 +09001569 case spv::OpAccessChain:
1570 case spv::OpInBoundsAccessChain: {
sfricke-samsung962cad92021-04-13 00:46:29 -07001571 // 2: AccessChain id, 3: object id
1572 if (insn.word(3)) accesschain_members.emplace(insn.word(2), insn.word(3));
1573 break;
1574 }
1575 default:
1576 break;
1577 }
1578 }
1579 if (store_members.empty()) {
1580 return location_list;
1581 }
1582 for (auto output : outputs) {
1583 auto store_it = store_members.find(output.second.id);
1584 if (store_it != store_members.end()) {
1585 location_list.insert(output.first.first);
1586 store_members.erase(store_it);
1587 continue;
1588 }
1589 store_it = store_members.begin();
1590 while (store_it != store_members.end()) {
1591 auto accesschain_it = accesschain_members.find(*store_it);
1592 if (accesschain_it == accesschain_members.end()) {
1593 ++store_it;
1594 continue;
1595 }
1596 if (accesschain_it->second == output.second.id) {
1597 location_list.insert(output.first.first);
1598 store_members.erase(store_it);
1599 accesschain_members.erase(accesschain_it);
1600 break;
1601 }
1602 ++store_it;
1603 }
1604 }
1605 return location_list;
1606}
1607
1608bool SHADER_MODULE_STATE::CollectInterfaceBlockMembers(std::map<location_t, interface_var> *out, bool is_array_of_verts,
ziga-lunarg9e94e112021-09-27 00:21:10 +02001609 uint32_t id, uint32_t type_id, bool is_patch,
1610 uint32_t /*first_location*/) const {
sfricke-samsung962cad92021-04-13 00:46:29 -07001611 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
1612 auto type = GetStructType(get_def(type_id), is_array_of_verts && !is_patch);
1613 if (type == end() || !(get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
1614 // This isn't an interface block.
1615 return false;
1616 }
1617
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001618 layer_data::unordered_map<uint32_t, uint32_t> member_components;
1619 layer_data::unordered_map<uint32_t, uint32_t> member_relaxed_precision;
1620 layer_data::unordered_map<uint32_t, uint32_t> member_patch;
sfricke-samsung962cad92021-04-13 00:46:29 -07001621
1622 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001623 for (auto insn : static_data_.member_decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001624 if (insn.word(1) == type.word(1)) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001625 uint32_t member_index = insn.word(2);
sfricke-samsung962cad92021-04-13 00:46:29 -07001626
1627 if (insn.word(3) == spv::DecorationComponent) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001628 uint32_t component = insn.word(4);
sfricke-samsung962cad92021-04-13 00:46:29 -07001629 member_components[member_index] = component;
1630 }
1631
1632 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
1633 member_relaxed_precision[member_index] = 1;
1634 }
1635
1636 if (insn.word(3) == spv::DecorationPatch) {
1637 member_patch[member_index] = 1;
1638 }
1639 }
1640 }
1641
1642 // TODO: correctly handle location assignment from outside
1643
1644 // Second pass -- produce the output, from Location decorations
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001645 for (auto insn : static_data_.member_decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001646 if (insn.word(1) == type.word(1)) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001647 uint32_t member_index = insn.word(2);
1648 uint32_t member_type_id = type.word(2 + member_index);
sfricke-samsung962cad92021-04-13 00:46:29 -07001649
1650 if (insn.word(3) == spv::DecorationLocation) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001651 uint32_t location = insn.word(4);
1652 uint32_t num_locations = GetLocationsConsumedByType(member_type_id, false);
sfricke-samsung962cad92021-04-13 00:46:29 -07001653 auto component_it = member_components.find(member_index);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001654 uint32_t component = component_it == member_components.end() ? 0 : component_it->second;
sfricke-samsung962cad92021-04-13 00:46:29 -07001655 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
1656 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
1657
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001658 for (uint32_t offset = 0; offset < num_locations; offset++) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001659 interface_var v = {};
1660 v.id = id;
1661 // TODO: member index in interface_var too?
1662 v.type_id = member_type_id;
1663 v.offset = offset;
1664 v.is_patch = member_is_patch;
1665 v.is_block_member = true;
1666 v.is_relaxed_precision = is_relaxed_precision;
1667 (*out)[std::make_pair(location + offset, component)] = v;
1668 }
1669 }
1670 }
1671 }
1672
1673 return true;
1674}
1675
1676std::map<location_t, interface_var> SHADER_MODULE_STATE::CollectInterfaceByLocation(spirv_inst_iter entrypoint,
1677 spv::StorageClass sinterface,
1678 bool is_array_of_verts) const {
1679 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
1680
1681 std::map<location_t, interface_var> out;
1682
1683 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
1684 auto insn = get_def(iid);
1685 assert(insn != end());
1686 assert(insn.opcode() == spv::OpVariable);
1687
ziga-lunarg9e94e112021-09-27 00:21:10 +02001688 const auto d = get_decorations(iid);
1689 bool passthrough = sinterface == spv::StorageClassOutput && insn.word(3) == spv::StorageClassInput &&
1690 (d.flags & decoration_set::passthrough_bit) != 0;
1691 if (insn.word(3) == static_cast<uint32_t>(sinterface) || passthrough) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001692 uint32_t id = insn.word(2);
1693 uint32_t type = insn.word(1);
sfricke-samsung962cad92021-04-13 00:46:29 -07001694
ziga-lunarg9e94e112021-09-27 00:21:10 +02001695 auto location = d.location;
sfricke-samsung962cad92021-04-13 00:46:29 -07001696 int builtin = d.builtin;
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001697 uint32_t component = d.component;
sfricke-samsung962cad92021-04-13 00:46:29 -07001698 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
1699 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
ziga-lunarg9e94e112021-09-27 00:21:10 +02001700 bool is_per_vertex = (d.flags & decoration_set::per_vertex_bit) != 0;
sfricke-samsung962cad92021-04-13 00:46:29 -07001701
1702 if (builtin != -1) {
1703 continue;
ziga-lunarg9e94e112021-09-27 00:21:10 +02001704 } else if (!CollectInterfaceBlockMembers(&out, is_array_of_verts, id, type, is_patch, location) ||
1705 location != decoration_set::kInvalidValue) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001706 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
1707 // one result for each.
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001708 uint32_t num_locations = GetLocationsConsumedByType(type, (is_array_of_verts && !is_patch) || is_per_vertex);
1709 for (uint32_t offset = 0; offset < num_locations; offset++) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001710 interface_var v = {};
1711 v.id = id;
1712 v.type_id = type;
1713 v.offset = offset;
1714 v.is_patch = is_patch;
1715 v.is_relaxed_precision = is_relaxed_precision;
1716 out[std::make_pair(location + offset, component)] = v;
1717 }
1718 }
1719 }
1720 }
1721
1722 return out;
1723}
1724
1725std::vector<uint32_t> SHADER_MODULE_STATE::CollectBuiltinBlockMembers(spirv_inst_iter entrypoint, uint32_t storageClass) const {
sfricke-samsung962cad92021-04-13 00:46:29 -07001726 // Find all interface variables belonging to the entrypoint and matching the storage class
sfricke-samsung0df5ee72021-07-24 23:27:16 -07001727 std::vector<uint32_t> variables;
sfricke-samsung962cad92021-04-13 00:46:29 -07001728 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
1729 auto def = get_def(id);
1730 assert(def != end());
1731 assert(def.opcode() == spv::OpVariable);
1732
1733 if (def.word(3) == storageClass) variables.push_back(def.word(1));
1734 }
1735
1736 // Find all members belonging to the builtin block selected
1737 std::vector<uint32_t> builtin_block_members;
1738 for (auto &var : variables) {
1739 auto def = get_def(get_def(var).word(3));
1740
1741 // It could be an array of IO blocks. The element type should be the struct defining the block contents
1742 if (def.opcode() == spv::OpTypeArray) def = get_def(def.word(2));
1743
1744 // Now find all members belonging to the struct defining the IO block
1745 if (def.opcode() == spv::OpTypeStruct) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001746 for (auto set : static_data_.builtin_decoration_list) {
sfricke-samsung0df5ee72021-07-24 23:27:16 -07001747 auto insn = at(set.offset);
1748 if ((insn.opcode() == spv::OpMemberDecorate) && (def.word(1) == insn.word(1))) {
1749 // Start with undefined builtin for each struct member.
1750 // But only when confirmed the struct is the built-in inteface block (can only be one per shader)
1751 if (builtin_block_members.size() == 0) {
1752 builtin_block_members.resize(def.len() - 2, spv::BuiltInMax);
sfricke-samsung962cad92021-04-13 00:46:29 -07001753 }
sfricke-samsung0df5ee72021-07-24 23:27:16 -07001754 auto struct_index = insn.word(2);
1755 assert(struct_index < builtin_block_members.size());
1756 builtin_block_members[struct_index] = insn.word(4);
sfricke-samsung962cad92021-04-13 00:46:29 -07001757 }
1758 }
1759 }
1760 }
1761
1762 return builtin_block_members;
1763}
1764
1765std::vector<std::pair<uint32_t, interface_var>> SHADER_MODULE_STATE::CollectInterfaceByInputAttachmentIndex(
1766 layer_data::unordered_set<uint32_t> const &accessible_ids) const {
1767 std::vector<std::pair<uint32_t, interface_var>> out;
1768
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001769 for (auto insn : static_data_.decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001770 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
1771 auto attachment_index = insn.word(3);
1772 auto id = insn.word(1);
1773
1774 if (accessible_ids.count(id)) {
1775 auto def = get_def(id);
1776 assert(def != end());
1777 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
1778 auto num_locations = GetLocationsConsumedByType(def.word(1), false);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001779 for (uint32_t offset = 0; offset < num_locations; offset++) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001780 interface_var v = {};
1781 v.id = id;
1782 v.type_id = def.word(1);
1783 v.offset = offset;
1784 out.emplace_back(attachment_index + offset, v);
1785 }
1786 }
1787 }
1788 }
1789 }
1790
1791 return out;
1792}
1793
ziga-lunarg8346fe82021-08-22 17:30:50 +02001794uint32_t SHADER_MODULE_STATE::GetNumComponentsInBaseType(const spirv_inst_iter &iter) const {
1795 const uint32_t opcode = iter.opcode();
1796 if (opcode == spv::OpTypeFloat || opcode == spv::OpTypeInt) {
1797 return 1;
1798 } else if (opcode == spv::OpTypeVector) {
1799 const uint32_t component_count = iter.word(3);
1800 return component_count;
1801 } else if (opcode == spv::OpTypeMatrix) {
1802 const auto column_type = get_def(iter.word(2));
1803 const uint32_t vector_length = GetNumComponentsInBaseType(column_type);
ziga-lunarg38e44982022-04-05 00:10:46 +02001804 // Because we are calculating components for a single location we do not care about column count
1805 return vector_length;
ziga-lunarg8346fe82021-08-22 17:30:50 +02001806 } else if (opcode == spv::OpTypeArray) {
1807 const auto element_type = get_def(iter.word(2));
1808 const uint32_t element_length = GetNumComponentsInBaseType(element_type);
1809 return element_length;
1810 } else if (opcode == spv::OpTypeStruct) {
1811 uint32_t total_size = 0;
1812 for (uint32_t i = 2; i < iter.len(); ++i) {
1813 total_size += GetNumComponentsInBaseType(get_def(iter.word(i)));
1814 }
1815 return total_size;
1816 } else if (opcode == spv::OpTypePointer) {
1817 const auto type = get_def(iter.word(3));
1818 return GetNumComponentsInBaseType(type);
1819 }
1820 return 0;
1821}
1822
ziga-lunarga26b3602021-08-08 15:53:00 +02001823uint32_t SHADER_MODULE_STATE::GetTypeBitsSize(const spirv_inst_iter &iter) const {
1824 const uint32_t opcode = iter.opcode();
1825 if (opcode == spv::OpTypeFloat || opcode == spv::OpTypeInt) {
1826 return iter.word(2);
1827 } else if (opcode == spv::OpTypeVector) {
1828 const auto component_type = get_def(iter.word(2));
1829 uint32_t scalar_width = GetTypeBitsSize(component_type);
1830 uint32_t component_count = iter.word(3);
1831 return scalar_width * component_count;
1832 } else if (opcode == spv::OpTypeMatrix) {
1833 const auto column_type = get_def(iter.word(2));
1834 uint32_t vector_width = GetTypeBitsSize(column_type);
1835 uint32_t column_count = iter.word(3);
1836 return vector_width * column_count;
1837 } else if (opcode == spv::OpTypeArray) {
1838 const auto element_type = get_def(iter.word(2));
1839 uint32_t element_width = GetTypeBitsSize(element_type);
1840 const auto length_type = get_def(iter.word(3));
1841 uint32_t length = GetConstantValue(length_type);
1842 return element_width * length;
1843 } else if (opcode == spv::OpTypeStruct) {
1844 uint32_t total_size = 0;
1845 for (uint32_t i = 2; i < iter.len(); ++i) {
1846 total_size += GetTypeBitsSize(get_def(iter.word(i)));
1847 }
1848 return total_size;
ziga-lunarg8346fe82021-08-22 17:30:50 +02001849 } else if (opcode == spv::OpTypePointer) {
1850 const auto type = get_def(iter.word(3));
1851 return GetTypeBitsSize(type);
ziga-lunargef2c3172021-11-07 10:35:29 +01001852 } else if (opcode == spv::OpVariable) {
1853 const auto type = get_def(iter.word(1));
1854 return GetTypeBitsSize(type);
ziga-lunarga26b3602021-08-08 15:53:00 +02001855 }
1856 return 0;
1857}
1858
1859uint32_t SHADER_MODULE_STATE::GetTypeBytesSize(const spirv_inst_iter &iter) const { return GetTypeBitsSize(iter) / 8; }
1860
ziga-lunarg19fc6ae2021-09-09 00:05:19 +02001861// Returns the base type (float, int or unsigned int) or struct (can have multiple different base types inside)
sjfricke6086f792022-08-25 16:38:15 +09001862// Will return 0 if it can not be determined
ziga-lunarg8346fe82021-08-22 17:30:50 +02001863uint32_t SHADER_MODULE_STATE::GetBaseType(const spirv_inst_iter &iter) const {
1864 const uint32_t opcode = iter.opcode();
sjfricke10f74a82022-08-18 18:12:56 +09001865 if (opcode == spv::OpTypeFloat || opcode == spv::OpTypeInt || opcode == spv::OpTypeBool || opcode == spv::OpTypeStruct) {
1866 // point to itself as its the base type (or a struct that needs to be traversed still)
ziga-lunarg8346fe82021-08-22 17:30:50 +02001867 return iter.word(1);
1868 } else if (opcode == spv::OpTypeVector) {
1869 const auto& component_type = get_def(iter.word(2));
1870 return GetBaseType(component_type);
1871 } else if (opcode == spv::OpTypeMatrix) {
1872 const auto& column_type = get_def(iter.word(2));
1873 return GetBaseType(column_type);
sjfricke6a03e012022-06-23 17:54:11 +09001874 } else if (opcode == spv::OpTypeArray || opcode == spv::OpTypeRuntimeArray) {
ziga-lunarg8346fe82021-08-22 17:30:50 +02001875 const auto& element_type = get_def(iter.word(2));
1876 return GetBaseType(element_type);
1877 } else if (opcode == spv::OpTypePointer) {
sjfricke6086f792022-08-25 16:38:15 +09001878 const auto &storage_class = iter.word(2);
ziga-lunarg8346fe82021-08-22 17:30:50 +02001879 const auto& type = get_def(iter.word(3));
sjfricke6086f792022-08-25 16:38:15 +09001880 if (storage_class == spv::StorageClassPhysicalStorageBuffer && type.opcode() == spv::OpTypeStruct) {
1881 // A physical storage buffer to a struct has a chance to point to itself and can't resolve a baseType
1882 // GLSL example:
1883 // layout(buffer_reference) buffer T1 {
1884 // T1 b[2];
1885 // };
1886 return 0;
1887 }
ziga-lunarg8346fe82021-08-22 17:30:50 +02001888 return GetBaseType(type);
1889 }
sjfricke10f74a82022-08-18 18:12:56 +09001890 // If we assert here, we are missing a valid base type that must be handled. Without this assert, a return value of 0 will
1891 // produce a hard bug to track
1892 assert(false);
ziga-lunarg8346fe82021-08-22 17:30:50 +02001893 return 0;
1894}
1895
sfricke-samsunga6c1ddc2022-01-23 14:15:40 -08001896// Returns type_id if id has type or zero otherwise
1897uint32_t SHADER_MODULE_STATE::GetTypeId(uint32_t id) const {
1898 const auto type = get_def(id);
1899 return OpcodeHasType(type.opcode()) ? type.word(1) : 0;
1900}
1901
sfricke-samsung962cad92021-04-13 00:46:29 -07001902std::vector<uint32_t> FindEntrypointInterfaces(const spirv_inst_iter &entrypoint) {
1903 assert(entrypoint.opcode() == spv::OpEntryPoint);
1904
1905 std::vector<uint32_t> interfaces;
1906 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
1907 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
1908 uint32_t word = 3;
1909 while (entrypoint.word(word) & 0xff000000u) {
1910 ++word;
1911 }
1912 ++word;
1913
1914 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
1915
1916 return interfaces;
1917}