• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "vtn_private.h"
25 #include "spirv_info.h"
26 #include "nir_deref.h"
27 #include <vulkan/vulkan_core.h>
28 
29 static struct vtn_pointer*
vtn_align_pointer(struct vtn_builder * b,struct vtn_pointer * ptr,unsigned alignment)30 vtn_align_pointer(struct vtn_builder *b, struct vtn_pointer *ptr,
31                   unsigned alignment)
32 {
33    if (alignment == 0)
34       return ptr;
35 
36    if (!util_is_power_of_two_nonzero(alignment)) {
37       vtn_warn("Provided alignment is not a power of two");
38       alignment = 1 << (ffs(alignment) - 1);
39    }
40 
41    /* If this pointer doesn't have a deref, bail.  This either means we're
42     * using the old offset+alignment pointers which don't support carrying
43     * alignment information or we're a pointer that is below the block
44     * boundary in our access chain in which case alignment is meaningless.
45     */
46    if (ptr->deref == NULL)
47       return ptr;
48 
49    /* Ignore alignment information on logical pointers.  This way, we don't
50     * trip up drivers with unnecessary casts.
51     */
52    nir_address_format addr_format = vtn_mode_to_address_format(b, ptr->mode);
53    if (addr_format == nir_address_format_logical)
54       return ptr;
55 
56    struct vtn_pointer *copy = vtn_alloc(b, struct vtn_pointer);
57    *copy = *ptr;
58    copy->deref = nir_alignment_deref_cast(&b->nb, ptr->deref, alignment, 0);
59 
60    return copy;
61 }
62 
63 static void
ptr_decoration_cb(struct vtn_builder * b,struct vtn_value * val,int member,const struct vtn_decoration * dec,void * void_ptr)64 ptr_decoration_cb(struct vtn_builder *b, struct vtn_value *val, int member,
65                   const struct vtn_decoration *dec, void *void_ptr)
66 {
67    struct vtn_pointer *ptr = void_ptr;
68 
69    switch (dec->decoration) {
70    case SpvDecorationNonUniformEXT:
71       ptr->access |= ACCESS_NON_UNIFORM;
72       break;
73 
74    default:
75       break;
76    }
77 }
78 
79 struct access_align {
80    enum gl_access_qualifier access;
81    uint32_t alignment;
82 };
83 
84 static void
access_align_cb(struct vtn_builder * b,struct vtn_value * val,int member,const struct vtn_decoration * dec,void * void_ptr)85 access_align_cb(struct vtn_builder *b, struct vtn_value *val, int member,
86                 const struct vtn_decoration *dec, void *void_ptr)
87 {
88    struct access_align *aa = void_ptr;
89 
90    switch (dec->decoration) {
91    case SpvDecorationAlignment:
92       aa->alignment = dec->operands[0];
93       break;
94 
95    case SpvDecorationNonUniformEXT:
96       aa->access |= ACCESS_NON_UNIFORM;
97       break;
98 
99    default:
100       break;
101    }
102 }
103 
104 static struct vtn_pointer*
vtn_decorate_pointer(struct vtn_builder * b,struct vtn_value * val,struct vtn_pointer * ptr)105 vtn_decorate_pointer(struct vtn_builder *b, struct vtn_value *val,
106                      struct vtn_pointer *ptr)
107 {
108    struct access_align aa = { 0, };
109    vtn_foreach_decoration(b, val, access_align_cb, &aa);
110 
111    ptr = vtn_align_pointer(b, ptr, aa.alignment);
112 
113    /* If we're adding access flags, make a copy of the pointer.  We could
114     * probably just OR them in without doing so but this prevents us from
115     * leaking them any further than actually specified in the SPIR-V.
116     */
117    if (aa.access & ~ptr->access) {
118       struct vtn_pointer *copy = vtn_alloc(b, struct vtn_pointer);
119       *copy = *ptr;
120       copy->access |= aa.access;
121       return copy;
122    }
123 
124    return ptr;
125 }
126 
127 struct vtn_value *
vtn_push_pointer(struct vtn_builder * b,uint32_t value_id,struct vtn_pointer * ptr)128 vtn_push_pointer(struct vtn_builder *b, uint32_t value_id,
129                  struct vtn_pointer *ptr)
130 {
131    struct vtn_value *val = vtn_push_value(b, value_id, vtn_value_type_pointer);
132    val->pointer = vtn_decorate_pointer(b, val, ptr);
133    return val;
134 }
135 
136 void
vtn_copy_value(struct vtn_builder * b,uint32_t src_value_id,uint32_t dst_value_id)137 vtn_copy_value(struct vtn_builder *b, uint32_t src_value_id,
138                uint32_t dst_value_id)
139 {
140    struct vtn_value *src = vtn_untyped_value(b, src_value_id);
141    struct vtn_value *dst = vtn_untyped_value(b, dst_value_id);
142 
143    vtn_fail_if(dst->value_type != vtn_value_type_invalid,
144                "SPIR-V id %u has already been written by another instruction",
145                dst_value_id);
146 
147    vtn_fail_if(dst->type->id != src->type->id,
148                "Result Type must equal Operand type");
149 
150    if (src->value_type == vtn_value_type_ssa && src->ssa->is_variable) {
151       nir_variable *dst_var =
152          nir_local_variable_create(b->nb.impl, src->ssa->type, "var_copy");
153       nir_deref_instr *dst_deref = nir_build_deref_var(&b->nb, dst_var);
154       nir_deref_instr *src_deref = vtn_get_deref_for_ssa_value(b, src->ssa);
155 
156       vtn_local_store(b, vtn_local_load(b, src_deref, 0), dst_deref, 0);
157 
158       vtn_push_var_ssa(b, dst_value_id, dst_var);
159       return;
160    }
161 
162    struct vtn_value src_copy = *src;
163    src_copy.name = dst->name;
164    src_copy.decoration = dst->decoration;
165    src_copy.type = dst->type;
166    *dst = src_copy;
167 
168    if (dst->value_type == vtn_value_type_pointer)
169       dst->pointer = vtn_decorate_pointer(b, dst, dst->pointer);
170 }
171 
172 static struct vtn_access_chain *
vtn_access_chain_create(struct vtn_builder * b,unsigned length)173 vtn_access_chain_create(struct vtn_builder *b, unsigned length)
174 {
175    struct vtn_access_chain *chain;
176 
177    /* Subtract 1 from the length since there's already one built in */
178    size_t size = sizeof(*chain) +
179                  (MAX2(length, 1) - 1) * sizeof(chain->link[0]);
180    chain = vtn_zalloc_size(b, size);
181    chain->length = length;
182 
183    return chain;
184 }
185 
186 static bool
vtn_mode_is_cross_invocation(struct vtn_builder * b,enum vtn_variable_mode mode)187 vtn_mode_is_cross_invocation(struct vtn_builder *b,
188                              enum vtn_variable_mode mode)
189 {
190    /* TODO: add TCS here once nir_remove_unused_io_vars() can handle vector indexing. */
191    bool cross_invocation_outputs = b->shader->info.stage == MESA_SHADER_MESH;
192    return mode == vtn_variable_mode_ssbo ||
193           mode == vtn_variable_mode_ubo ||
194           mode == vtn_variable_mode_phys_ssbo ||
195           mode == vtn_variable_mode_push_constant ||
196           mode == vtn_variable_mode_workgroup ||
197           mode == vtn_variable_mode_cross_workgroup ||
198           mode == vtn_variable_mode_node_payload ||
199           (cross_invocation_outputs && mode == vtn_variable_mode_output) ||
200           (b->shader->info.stage == MESA_SHADER_TASK && mode == vtn_variable_mode_task_payload);
201 }
202 
203 static bool
vtn_pointer_is_external_block(struct vtn_builder * b,struct vtn_pointer * ptr)204 vtn_pointer_is_external_block(struct vtn_builder *b,
205                               struct vtn_pointer *ptr)
206 {
207    return ptr->mode == vtn_variable_mode_ssbo ||
208           ptr->mode == vtn_variable_mode_ubo ||
209           ptr->mode == vtn_variable_mode_phys_ssbo;
210 }
211 
212 static nir_def *
vtn_access_link_as_ssa(struct vtn_builder * b,struct vtn_access_link link,unsigned stride,unsigned bit_size)213 vtn_access_link_as_ssa(struct vtn_builder *b, struct vtn_access_link link,
214                        unsigned stride, unsigned bit_size)
215 {
216    vtn_assert(stride > 0);
217    if (link.mode == vtn_access_mode_literal) {
218       return nir_imm_intN_t(&b->nb, link.id * stride, bit_size);
219    } else {
220       nir_def *ssa = vtn_ssa_value(b, link.id)->def;
221       if (ssa->bit_size != bit_size)
222          ssa = nir_i2iN(&b->nb, ssa, bit_size);
223       return nir_imul_imm(&b->nb, ssa, stride);
224    }
225 }
226 
227 static VkDescriptorType
vk_desc_type_for_mode(struct vtn_builder * b,enum vtn_variable_mode mode)228 vk_desc_type_for_mode(struct vtn_builder *b, enum vtn_variable_mode mode)
229 {
230    switch (mode) {
231    case vtn_variable_mode_ubo:
232       return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
233    case vtn_variable_mode_ssbo:
234       return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
235    case vtn_variable_mode_accel_struct:
236       return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
237    default:
238       vtn_fail("Invalid mode for vulkan_resource_index");
239    }
240 }
241 
242 static nir_def *
vtn_variable_resource_index(struct vtn_builder * b,struct vtn_variable * var,nir_def * desc_array_index)243 vtn_variable_resource_index(struct vtn_builder *b, struct vtn_variable *var,
244                             nir_def *desc_array_index)
245 {
246    vtn_assert(b->options->environment == NIR_SPIRV_VULKAN);
247 
248    if (!desc_array_index)
249       desc_array_index = nir_imm_int(&b->nb, 0);
250 
251    if (b->vars_used_indirectly) {
252       vtn_assert(var->var);
253       _mesa_set_add(b->vars_used_indirectly, var->var);
254    }
255 
256    nir_intrinsic_instr *instr =
257       nir_intrinsic_instr_create(b->nb.shader,
258                                  nir_intrinsic_vulkan_resource_index);
259    instr->src[0] = nir_src_for_ssa(desc_array_index);
260    nir_intrinsic_set_desc_set(instr, var->descriptor_set);
261    nir_intrinsic_set_binding(instr, var->binding);
262    nir_intrinsic_set_desc_type(instr, vk_desc_type_for_mode(b, var->mode));
263 
264    nir_address_format addr_format = vtn_mode_to_address_format(b, var->mode);
265    nir_def_init(&instr->instr, &instr->def,
266                 nir_address_format_num_components(addr_format),
267                 nir_address_format_bit_size(addr_format));
268    instr->num_components = instr->def.num_components;
269    nir_builder_instr_insert(&b->nb, &instr->instr);
270 
271    return &instr->def;
272 }
273 
274 static nir_def *
vtn_resource_reindex(struct vtn_builder * b,enum vtn_variable_mode mode,nir_def * base_index,nir_def * offset_index)275 vtn_resource_reindex(struct vtn_builder *b, enum vtn_variable_mode mode,
276                      nir_def *base_index, nir_def *offset_index)
277 {
278    vtn_assert(b->options->environment == NIR_SPIRV_VULKAN);
279 
280    nir_intrinsic_instr *instr =
281       nir_intrinsic_instr_create(b->nb.shader,
282                                  nir_intrinsic_vulkan_resource_reindex);
283    instr->src[0] = nir_src_for_ssa(base_index);
284    instr->src[1] = nir_src_for_ssa(offset_index);
285    nir_intrinsic_set_desc_type(instr, vk_desc_type_for_mode(b, mode));
286 
287    nir_address_format addr_format = vtn_mode_to_address_format(b, mode);
288    nir_def_init(&instr->instr, &instr->def,
289                 nir_address_format_num_components(addr_format),
290                 nir_address_format_bit_size(addr_format));
291    instr->num_components = instr->def.num_components;
292    nir_builder_instr_insert(&b->nb, &instr->instr);
293 
294    return &instr->def;
295 }
296 
297 static nir_def *
vtn_descriptor_load(struct vtn_builder * b,enum vtn_variable_mode mode,nir_def * desc_index)298 vtn_descriptor_load(struct vtn_builder *b, enum vtn_variable_mode mode,
299                     nir_def *desc_index)
300 {
301    vtn_assert(b->options->environment == NIR_SPIRV_VULKAN);
302 
303    nir_intrinsic_instr *desc_load =
304       nir_intrinsic_instr_create(b->nb.shader,
305                                  nir_intrinsic_load_vulkan_descriptor);
306    desc_load->src[0] = nir_src_for_ssa(desc_index);
307    nir_intrinsic_set_desc_type(desc_load, vk_desc_type_for_mode(b, mode));
308 
309    nir_address_format addr_format = vtn_mode_to_address_format(b, mode);
310    nir_def_init(&desc_load->instr, &desc_load->def,
311                 nir_address_format_num_components(addr_format),
312                 nir_address_format_bit_size(addr_format));
313    desc_load->num_components = desc_load->def.num_components;
314    nir_builder_instr_insert(&b->nb, &desc_load->instr);
315 
316    return &desc_load->def;
317 }
318 
319 static struct vtn_type *
vtn_create_internal_pointer_type(struct vtn_builder * b,struct vtn_type * original,struct vtn_type * pointed)320 vtn_create_internal_pointer_type(struct vtn_builder *b,
321                                  struct vtn_type *original,
322                                  struct vtn_type *pointed)
323 {
324    assert(original->base_type == vtn_base_type_pointer);
325 
326    /* Create a vtn_type that is not present on the SPIR-V module but
327     * is useful for the compilation process.  Such type will have no id.
328     */
329    struct vtn_type *t = vtn_zalloc(b, struct vtn_type);
330    t->base_type = vtn_base_type_pointer;
331    t->pointed = pointed;
332    t->storage_class = original->storage_class;
333    t->type = original->type;
334    return t;
335 }
336 
337 static struct vtn_pointer *
vtn_pointer_dereference(struct vtn_builder * b,struct vtn_pointer * base,struct vtn_access_chain * deref_chain)338 vtn_pointer_dereference(struct vtn_builder *b,
339                         struct vtn_pointer *base,
340                         struct vtn_access_chain *deref_chain)
341 {
342    struct vtn_type *type = base->type->pointed;
343    enum gl_access_qualifier access = base->access | deref_chain->access;
344    unsigned idx = 0;
345 
346    nir_deref_instr *tail;
347    if (base->deref) {
348       tail = base->deref;
349    } else if (b->options->environment == NIR_SPIRV_VULKAN &&
350               (vtn_pointer_is_external_block(b, base) ||
351                base->mode == vtn_variable_mode_accel_struct)) {
352       nir_def *block_index = base->block_index;
353 
354       /* We dereferencing an external block pointer.  Correctness of this
355        * operation relies on one particular line in the SPIR-V spec, section
356        * entitled "Validation Rules for Shader Capabilities":
357        *
358        *    "Block and BufferBlock decorations cannot decorate a structure
359        *    type that is nested at any level inside another structure type
360        *    decorated with Block or BufferBlock."
361        *
362        * This means that we can detect the point where we cross over from
363        * descriptor indexing to buffer indexing by looking for the block
364        * decorated struct type.  Anything before the block decorated struct
365        * type is a descriptor indexing operation and anything after the block
366        * decorated struct is a buffer offset operation.
367        */
368 
369       /* Figure out the descriptor array index if any
370        *
371        * Some of the Vulkan CTS tests with hand-rolled SPIR-V have been known
372        * to forget the Block or BufferBlock decoration from time to time.
373        * It's more robust if we check for both !block_index and for the type
374        * to contain a block.  This way there's a decent chance that arrays of
375        * UBOs/SSBOs will work correctly even if variable pointers are
376        * completley toast.
377        */
378       nir_def *desc_arr_idx = NULL;
379       if (!block_index || vtn_type_contains_block(b, type) ||
380           base->mode == vtn_variable_mode_accel_struct) {
381          /* If our type contains a block, then we're still outside the block
382           * and we need to process enough levels of dereferences to get inside
383           * of it.  Same applies to acceleration structures.
384           */
385          if (deref_chain->ptr_as_array) {
386             unsigned aoa_size = glsl_get_aoa_size(type->type);
387             desc_arr_idx = vtn_access_link_as_ssa(b, deref_chain->link[idx],
388                                                   MAX2(aoa_size, 1), 32);
389             idx++;
390          }
391 
392          for (; idx < deref_chain->length; idx++) {
393             if (type->base_type != vtn_base_type_array) {
394                vtn_assert(type->base_type == vtn_base_type_struct);
395                break;
396             }
397 
398             unsigned aoa_size = glsl_get_aoa_size(type->array_element->type);
399             nir_def *arr_offset =
400                vtn_access_link_as_ssa(b, deref_chain->link[idx],
401                                       MAX2(aoa_size, 1), 32);
402             if (desc_arr_idx)
403                desc_arr_idx = nir_iadd(&b->nb, desc_arr_idx, arr_offset);
404             else
405                desc_arr_idx = arr_offset;
406 
407             type = type->array_element;
408             access |= type->access;
409          }
410       }
411 
412       if (!block_index) {
413          vtn_assert(base->var && base->type->pointed);
414          block_index = vtn_variable_resource_index(b, base->var, desc_arr_idx);
415       } else if (desc_arr_idx) {
416          block_index = vtn_resource_reindex(b, base->mode,
417                                             block_index, desc_arr_idx);
418       }
419 
420       if (idx == deref_chain->length) {
421          /* The entire deref was consumed in finding the block index.  Return
422           * a pointer which just has a block index and a later access chain
423           * will dereference deeper.
424           */
425          struct vtn_pointer *ptr = vtn_zalloc(b, struct vtn_pointer);
426          ptr->type = vtn_create_internal_pointer_type(b, base->type, type);
427          ptr->mode = base->mode;
428          ptr->block_index = block_index;
429          ptr->access = access;
430          return ptr;
431       }
432 
433       /* If we got here, there's more access chain to handle and we have the
434        * final block index.  Insert a descriptor load and cast to a deref to
435        * start the deref chain.
436        */
437       nir_def *desc = vtn_descriptor_load(b, base->mode, block_index);
438 
439       assert(base->mode == vtn_variable_mode_ssbo ||
440              base->mode == vtn_variable_mode_ubo);
441       nir_variable_mode nir_mode =
442          base->mode == vtn_variable_mode_ssbo ? nir_var_mem_ssbo : nir_var_mem_ubo;
443       const uint32_t align = base->mode == vtn_variable_mode_ssbo ?
444          b->options->min_ssbo_alignment : b->options->min_ubo_alignment;
445 
446       tail = nir_build_deref_cast(&b->nb, desc, nir_mode,
447                                   vtn_type_get_nir_type(b, type, base->mode),
448                                   base->type->stride);
449       tail->cast.align_mul = align;
450       tail->cast.align_offset = 0;
451 
452    } else if (base->mode == vtn_variable_mode_shader_record) {
453       /* For ShaderRecordBufferKHR variables, we don't have a nir_variable.
454        * It's just a fancy handle around a pointer to the shader record for
455        * the current shader.
456        */
457       tail = nir_build_deref_cast(&b->nb, nir_load_shader_record_ptr(&b->nb),
458                                   nir_var_mem_constant,
459                                   vtn_type_get_nir_type(b, base->type->pointed,
460                                                            base->mode),
461                                   0 /* ptr_as_array stride */);
462    } else {
463       assert(base->var && base->var->var);
464       tail = nir_build_deref_var(&b->nb, base->var->var);
465       if (base->type && base->type->type) {
466          tail->def.num_components =
467             glsl_get_vector_elements(base->type->type);
468          tail->def.bit_size = glsl_get_bit_size(base->type->type);
469       }
470    }
471 
472    if (idx == 0 && deref_chain->ptr_as_array) {
473       /* We start with a deref cast to get the stride.  Hopefully, we'll be
474        * able to delete that cast eventually.
475        */
476       tail = nir_build_deref_cast(&b->nb, &tail->def, tail->modes,
477                                   tail->type, base->type->stride);
478 
479       nir_def *index = vtn_access_link_as_ssa(b, deref_chain->link[0], 1,
480                                                   tail->def.bit_size);
481       tail = nir_build_deref_ptr_as_array(&b->nb, tail, index);
482       idx++;
483    }
484 
485    for (; idx < deref_chain->length; idx++) {
486       if (glsl_type_is_struct_or_ifc(type->type)) {
487          vtn_assert(deref_chain->link[idx].mode == vtn_access_mode_literal);
488          unsigned field = deref_chain->link[idx].id;
489          tail = nir_build_deref_struct(&b->nb, tail, field);
490          type = type->members[field];
491       } else {
492          nir_def *arr_index =
493             vtn_access_link_as_ssa(b, deref_chain->link[idx], 1,
494                                    tail->def.bit_size);
495          if (type->base_type == vtn_base_type_cooperative_matrix) {
496             const struct glsl_type *element_type = glsl_get_cmat_element(type->type);
497             tail = nir_build_deref_cast(&b->nb, &tail->def, tail->modes,
498                                         glsl_array_type(element_type, 0, 0), 0);
499             type = type->component_type;
500          } else {
501             type = type->array_element;
502          }
503          tail = nir_build_deref_array(&b->nb, tail, arr_index);
504       }
505       tail->arr.in_bounds = deref_chain->in_bounds;
506 
507       access |= type->access;
508    }
509 
510    struct vtn_pointer *ptr = vtn_zalloc(b, struct vtn_pointer);
511    ptr->type = vtn_create_internal_pointer_type(b, base->type, type);
512    ptr->mode = base->mode;
513    ptr->var = base->var;
514    ptr->deref = tail;
515    ptr->access = access;
516 
517    return ptr;
518 }
519 
520 nir_deref_instr *
vtn_pointer_to_deref(struct vtn_builder * b,struct vtn_pointer * ptr)521 vtn_pointer_to_deref(struct vtn_builder *b, struct vtn_pointer *ptr)
522 {
523    if (!ptr->deref) {
524       struct vtn_access_chain chain = {
525          .length = 0,
526       };
527       ptr = vtn_pointer_dereference(b, ptr, &chain);
528    }
529 
530    return ptr->deref;
531 }
532 
533 static void
_vtn_local_load_store(struct vtn_builder * b,bool load,nir_deref_instr * deref,struct vtn_ssa_value * inout,enum gl_access_qualifier access)534 _vtn_local_load_store(struct vtn_builder *b, bool load, nir_deref_instr *deref,
535                       struct vtn_ssa_value *inout,
536                       enum gl_access_qualifier access)
537 {
538    if (glsl_type_is_cmat(deref->type)) {
539       if (load) {
540          nir_deref_instr *temp = vtn_create_cmat_temporary(b, deref->type, "cmat_ssa");
541          nir_cmat_copy(&b->nb, &temp->def, &deref->def);
542          vtn_set_ssa_value_var(b, inout, temp->var);
543       } else {
544          nir_deref_instr *src_deref = vtn_get_deref_for_ssa_value(b, inout);
545          nir_cmat_copy(&b->nb, &deref->def, &src_deref->def);
546       }
547    } else if (glsl_type_is_vector_or_scalar(deref->type)) {
548       if (load) {
549          inout->def = nir_load_deref_with_access(&b->nb, deref, access);
550       } else {
551          nir_store_deref_with_access(&b->nb, deref, inout->def, ~0, access);
552       }
553    } else if (glsl_type_is_array(deref->type) ||
554               glsl_type_is_matrix(deref->type)) {
555       unsigned elems = glsl_get_length(deref->type);
556       for (unsigned i = 0; i < elems; i++) {
557          nir_deref_instr *child =
558             nir_build_deref_array_imm(&b->nb, deref, i);
559          _vtn_local_load_store(b, load, child, inout->elems[i], access);
560       }
561    } else {
562       vtn_assert(glsl_type_is_struct_or_ifc(deref->type));
563       unsigned elems = glsl_get_length(deref->type);
564       for (unsigned i = 0; i < elems; i++) {
565          nir_deref_instr *child = nir_build_deref_struct(&b->nb, deref, i);
566          _vtn_local_load_store(b, load, child, inout->elems[i], access);
567       }
568    }
569 }
570 
571 nir_deref_instr *
vtn_nir_deref(struct vtn_builder * b,uint32_t id)572 vtn_nir_deref(struct vtn_builder *b, uint32_t id)
573 {
574    struct vtn_pointer *ptr = vtn_pointer(b, id);
575    return vtn_pointer_to_deref(b, ptr);
576 }
577 
578 /*
579  * Gets the NIR-level deref tail, which may have as a child an array deref
580  * selecting which component due to OpAccessChain supporting per-component
581  * indexing in SPIR-V.
582  */
583 static nir_deref_instr *
get_deref_tail(nir_deref_instr * deref)584 get_deref_tail(nir_deref_instr *deref)
585 {
586    if (deref->deref_type != nir_deref_type_array)
587       return deref;
588 
589    nir_deref_instr *parent =
590       nir_instr_as_deref(deref->parent.ssa->parent_instr);
591 
592    if (parent->deref_type == nir_deref_type_cast &&
593        parent->parent.ssa->parent_instr->type == nir_instr_type_deref) {
594       nir_deref_instr *grandparent =
595          nir_instr_as_deref(parent->parent.ssa->parent_instr);
596 
597       if (glsl_type_is_cmat(grandparent->type))
598          return grandparent;
599    }
600 
601    if (glsl_type_is_vector(parent->type) ||
602        glsl_type_is_cmat(parent->type))
603       return parent;
604    else
605       return deref;
606 }
607 
608 struct vtn_ssa_value *
vtn_local_load(struct vtn_builder * b,nir_deref_instr * src,enum gl_access_qualifier access)609 vtn_local_load(struct vtn_builder *b, nir_deref_instr *src,
610                enum gl_access_qualifier access)
611 {
612    nir_deref_instr *src_tail = get_deref_tail(src);
613    struct vtn_ssa_value *val = vtn_create_ssa_value(b, src_tail->type);
614    _vtn_local_load_store(b, true, src_tail, val, access);
615 
616    if (src_tail != src) {
617       val->type = src->type;
618 
619       if (glsl_type_is_cmat(src_tail->type)) {
620          assert(val->is_variable);
621          nir_deref_instr *mat = vtn_get_deref_for_ssa_value(b, val);
622 
623          /* Reset is_variable because we are repurposing val. */
624          val->is_variable = false;
625          val->def = nir_cmat_extract(&b->nb,
626                                      glsl_get_bit_size(src->type),
627                                      &mat->def, src->arr.index.ssa);
628       } else {
629          val->def = nir_vector_extract(&b->nb, val->def, src->arr.index.ssa);
630       }
631    }
632 
633    return val;
634 }
635 
636 void
vtn_local_store(struct vtn_builder * b,struct vtn_ssa_value * src,nir_deref_instr * dest,enum gl_access_qualifier access)637 vtn_local_store(struct vtn_builder *b, struct vtn_ssa_value *src,
638                 nir_deref_instr *dest, enum gl_access_qualifier access)
639 {
640    nir_deref_instr *dest_tail = get_deref_tail(dest);
641 
642    if (dest_tail != dest) {
643       struct vtn_ssa_value *val = vtn_create_ssa_value(b, dest_tail->type);
644       _vtn_local_load_store(b, true, dest_tail, val, access);
645 
646       if (glsl_type_is_cmat(dest_tail->type)) {
647          nir_deref_instr *mat = vtn_get_deref_for_ssa_value(b, val);
648          nir_deref_instr *dst = vtn_create_cmat_temporary(b, dest_tail->type, "cmat_insert");
649          nir_cmat_insert(&b->nb, &dst->def, src->def, &mat->def, dest->arr.index.ssa);
650          vtn_set_ssa_value_var(b, val, dst->var);
651       } else {
652          val->def = nir_vector_insert(&b->nb, val->def, src->def,
653                                       dest->arr.index.ssa);
654       }
655 
656       _vtn_local_load_store(b, false, dest_tail, val, access);
657    } else {
658       _vtn_local_load_store(b, false, dest_tail, src, access);
659    }
660 }
661 
662 static nir_def *
vtn_pointer_to_descriptor(struct vtn_builder * b,struct vtn_pointer * ptr)663 vtn_pointer_to_descriptor(struct vtn_builder *b, struct vtn_pointer *ptr)
664 {
665    assert(ptr->mode == vtn_variable_mode_accel_struct);
666    if (!ptr->block_index) {
667       struct vtn_access_chain chain = {
668          .length = 0,
669       };
670       ptr = vtn_pointer_dereference(b, ptr, &chain);
671    }
672 
673    vtn_assert(ptr->deref == NULL && ptr->block_index != NULL);
674    return vtn_descriptor_load(b, ptr->mode, ptr->block_index);
675 }
676 
677 static void
_vtn_variable_load_store(struct vtn_builder * b,bool load,struct vtn_pointer * ptr,enum gl_access_qualifier access,struct vtn_ssa_value ** inout)678 _vtn_variable_load_store(struct vtn_builder *b, bool load,
679                          struct vtn_pointer *ptr,
680                          enum gl_access_qualifier access,
681                          struct vtn_ssa_value **inout)
682 {
683    if (ptr->mode == vtn_variable_mode_uniform ||
684        ptr->mode == vtn_variable_mode_image) {
685       if (ptr->type->pointed->base_type == vtn_base_type_image ||
686           ptr->type->pointed->base_type == vtn_base_type_sampler) {
687          /* See also our handling of OpTypeSampler and OpTypeImage */
688          vtn_assert(load);
689          (*inout)->def = vtn_pointer_to_ssa(b, ptr);
690          return;
691       } else if (ptr->type->pointed->base_type == vtn_base_type_sampled_image) {
692          /* See also our handling of OpTypeSampledImage */
693          vtn_assert(load);
694          struct vtn_sampled_image si = {
695             .image = vtn_pointer_to_deref(b, ptr),
696             .sampler = vtn_pointer_to_deref(b, ptr),
697          };
698          (*inout)->def = vtn_sampled_image_to_nir_ssa(b, si);
699          return;
700       }
701    } else if (ptr->mode == vtn_variable_mode_accel_struct) {
702       vtn_assert(load);
703       (*inout)->def = vtn_pointer_to_descriptor(b, ptr);
704       return;
705    }
706 
707    enum glsl_base_type base_type = glsl_get_base_type(ptr->type->pointed->type);
708    switch (base_type) {
709    case GLSL_TYPE_UINT:
710    case GLSL_TYPE_INT:
711    case GLSL_TYPE_UINT16:
712    case GLSL_TYPE_INT16:
713    case GLSL_TYPE_UINT8:
714    case GLSL_TYPE_INT8:
715    case GLSL_TYPE_UINT64:
716    case GLSL_TYPE_INT64:
717    case GLSL_TYPE_FLOAT:
718    case GLSL_TYPE_FLOAT16:
719    case GLSL_TYPE_BOOL:
720    case GLSL_TYPE_DOUBLE:
721    case GLSL_TYPE_COOPERATIVE_MATRIX:
722       if (glsl_type_is_vector_or_scalar(ptr->type->pointed->type)) {
723          /* We hit a vector or scalar; go ahead and emit the load[s] */
724          nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
725          if (vtn_mode_is_cross_invocation(b, ptr->mode)) {
726             /* If it's cross-invocation, we call nir_load/store_deref
727              * directly.  The vtn_local_load/store helpers are too clever and
728              * do magic to avoid array derefs of vectors.  That magic is both
729              * less efficient than the direct load/store and, in the case of
730              * stores, is broken because it creates a race condition if two
731              * threads are writing to different components of the same vector
732              * due to the load+insert+store it uses to emulate the array
733              * deref.
734              */
735             if (load) {
736                (*inout)->def = nir_load_deref_with_access(&b->nb, deref,
737                                                           ptr->type->pointed->access | access);
738             } else {
739                nir_store_deref_with_access(&b->nb, deref, (*inout)->def, ~0,
740                                            ptr->type->pointed->access | access);
741             }
742          } else {
743             if (load) {
744                *inout = vtn_local_load(b, deref, ptr->type->pointed->access | access);
745             } else {
746                vtn_local_store(b, *inout, deref, ptr->type->pointed->access | access);
747             }
748          }
749          return;
750       }
751       FALLTHROUGH;
752 
753    case GLSL_TYPE_INTERFACE:
754    case GLSL_TYPE_ARRAY:
755    case GLSL_TYPE_STRUCT: {
756       unsigned elems = glsl_get_length(ptr->type->pointed->type);
757       struct vtn_access_chain chain = {
758          .length = 1,
759          .link = {
760             { .mode = vtn_access_mode_literal, },
761          }
762       };
763       for (unsigned i = 0; i < elems; i++) {
764          chain.link[0].id = i;
765          struct vtn_pointer *elem = vtn_pointer_dereference(b, ptr, &chain);
766          _vtn_variable_load_store(b, load, elem, ptr->type->pointed->access | access,
767                                   &(*inout)->elems[i]);
768       }
769       return;
770    }
771 
772    default:
773       vtn_fail("Invalid access chain type");
774    }
775 }
776 
777 struct vtn_ssa_value *
vtn_variable_load(struct vtn_builder * b,struct vtn_pointer * src,enum gl_access_qualifier access)778 vtn_variable_load(struct vtn_builder *b, struct vtn_pointer *src,
779                   enum gl_access_qualifier access)
780 {
781    struct vtn_ssa_value *val = vtn_create_ssa_value(b, src->type->pointed->type);
782    _vtn_variable_load_store(b, true, src, src->access | access, &val);
783    return val;
784 }
785 
786 void
vtn_variable_store(struct vtn_builder * b,struct vtn_ssa_value * src,struct vtn_pointer * dest,enum gl_access_qualifier access)787 vtn_variable_store(struct vtn_builder *b, struct vtn_ssa_value *src,
788                    struct vtn_pointer *dest, enum gl_access_qualifier access)
789 {
790    _vtn_variable_load_store(b, false, dest, dest->access | access, &src);
791 }
792 
793 static void
_vtn_variable_copy(struct vtn_builder * b,struct vtn_pointer * dest,struct vtn_pointer * src,enum gl_access_qualifier dest_access,enum gl_access_qualifier src_access)794 _vtn_variable_copy(struct vtn_builder *b, struct vtn_pointer *dest,
795                    struct vtn_pointer *src, enum gl_access_qualifier dest_access,
796                    enum gl_access_qualifier src_access)
797 {
798    vtn_assert(glsl_get_bare_type(src->type->pointed->type) ==
799               glsl_get_bare_type(dest->type->pointed->type));
800    enum glsl_base_type base_type = glsl_get_base_type(src->type->pointed->type);
801    switch (base_type) {
802    case GLSL_TYPE_UINT:
803    case GLSL_TYPE_INT:
804    case GLSL_TYPE_UINT16:
805    case GLSL_TYPE_INT16:
806    case GLSL_TYPE_UINT8:
807    case GLSL_TYPE_INT8:
808    case GLSL_TYPE_UINT64:
809    case GLSL_TYPE_INT64:
810    case GLSL_TYPE_FLOAT:
811    case GLSL_TYPE_FLOAT16:
812    case GLSL_TYPE_DOUBLE:
813    case GLSL_TYPE_BOOL:
814       /* At this point, we have a scalar, vector, or matrix so we know that
815        * there cannot be any structure splitting still in the way.  By
816        * stopping at the matrix level rather than the vector level, we
817        * ensure that matrices get loaded in the optimal way even if they
818        * are storred row-major in a UBO.
819        */
820       vtn_variable_store(b, vtn_variable_load(b, src, src_access), dest, dest_access);
821       return;
822 
823    case GLSL_TYPE_INTERFACE:
824    case GLSL_TYPE_ARRAY:
825    case GLSL_TYPE_STRUCT: {
826       struct vtn_access_chain chain = {
827          .length = 1,
828          .link = {
829             { .mode = vtn_access_mode_literal, },
830          }
831       };
832       unsigned elems = glsl_get_length(src->type->pointed->type);
833       for (unsigned i = 0; i < elems; i++) {
834          chain.link[0].id = i;
835          struct vtn_pointer *src_elem =
836             vtn_pointer_dereference(b, src, &chain);
837          struct vtn_pointer *dest_elem =
838             vtn_pointer_dereference(b, dest, &chain);
839 
840          _vtn_variable_copy(b, dest_elem, src_elem, dest_access, src_access);
841       }
842       return;
843    }
844 
845    default:
846       vtn_fail("Invalid access chain type");
847    }
848 }
849 
850 static void
vtn_variable_copy(struct vtn_builder * b,struct vtn_pointer * dest,struct vtn_pointer * src,enum gl_access_qualifier dest_access,enum gl_access_qualifier src_access)851 vtn_variable_copy(struct vtn_builder *b, struct vtn_pointer *dest,
852                   struct vtn_pointer *src, enum gl_access_qualifier dest_access,
853                   enum gl_access_qualifier src_access)
854 {
855    /* TODO: At some point, we should add a special-case for when we can
856     * just emit a copy_var intrinsic.
857     */
858    _vtn_variable_copy(b, dest, src, dest_access, src_access);
859 }
860 
861 static void
set_mode_system_value(struct vtn_builder * b,nir_variable_mode * mode)862 set_mode_system_value(struct vtn_builder *b, nir_variable_mode *mode)
863 {
864    vtn_assert(*mode == nir_var_system_value || *mode == nir_var_shader_in ||
865               /* Hack for NV_mesh_shader due to lack of dedicated storage class. */
866               *mode == nir_var_mem_task_payload ||
867               /* Hack for DPCPP, see https://github.com/intel/llvm/issues/6703 */
868               *mode == nir_var_mem_global);
869    *mode = nir_var_system_value;
870 }
871 
872 static void
vtn_get_builtin_location(struct vtn_builder * b,SpvBuiltIn builtin,int * location,nir_variable_mode * mode)873 vtn_get_builtin_location(struct vtn_builder *b,
874                          SpvBuiltIn builtin, int *location,
875                          nir_variable_mode *mode)
876 {
877    switch (builtin) {
878    case SpvBuiltInPosition:
879    case SpvBuiltInPositionPerViewNV:
880       *location = VARYING_SLOT_POS;
881       break;
882    case SpvBuiltInPointSize:
883       *location = VARYING_SLOT_PSIZ;
884       break;
885    case SpvBuiltInClipDistance:
886    case SpvBuiltInClipDistancePerViewNV:
887       *location = VARYING_SLOT_CLIP_DIST0;
888       break;
889    case SpvBuiltInCullDistance:
890    case SpvBuiltInCullDistancePerViewNV:
891       *location = VARYING_SLOT_CULL_DIST0;
892       break;
893    case SpvBuiltInVertexId:
894    case SpvBuiltInVertexIndex:
895       /* The Vulkan spec defines VertexIndex to be non-zero-based and doesn't
896        * allow VertexId.  The ARB_gl_spirv spec defines VertexId to be the
897        * same as gl_VertexID, which is non-zero-based, and removes
898        * VertexIndex.  Since they're both defined to be non-zero-based, we use
899        * SYSTEM_VALUE_VERTEX_ID for both.
900        */
901       *location = SYSTEM_VALUE_VERTEX_ID;
902       set_mode_system_value(b, mode);
903       break;
904    case SpvBuiltInInstanceIndex:
905       *location = SYSTEM_VALUE_INSTANCE_INDEX;
906       set_mode_system_value(b, mode);
907       break;
908    case SpvBuiltInInstanceId:
909       *location = SYSTEM_VALUE_INSTANCE_ID;
910       set_mode_system_value(b, mode);
911       break;
912    case SpvBuiltInPrimitiveId:
913       if (b->shader->info.stage == MESA_SHADER_FRAGMENT) {
914          vtn_assert(*mode == nir_var_shader_in);
915          *location = VARYING_SLOT_PRIMITIVE_ID;
916       } else if (*mode == nir_var_shader_out) {
917          *location = VARYING_SLOT_PRIMITIVE_ID;
918       } else {
919          *location = SYSTEM_VALUE_PRIMITIVE_ID;
920          set_mode_system_value(b, mode);
921       }
922       break;
923    case SpvBuiltInInvocationId:
924       *location = SYSTEM_VALUE_INVOCATION_ID;
925       set_mode_system_value(b, mode);
926       break;
927    case SpvBuiltInLayer:
928    case SpvBuiltInLayerPerViewNV:
929       *location = VARYING_SLOT_LAYER;
930       if (b->shader->info.stage == MESA_SHADER_FRAGMENT)
931          *mode = nir_var_shader_in;
932       else if (b->shader->info.stage == MESA_SHADER_GEOMETRY)
933          *mode = nir_var_shader_out;
934       else if (b->supported_capabilities.ShaderViewportIndexLayerEXT &&
935                (b->shader->info.stage == MESA_SHADER_VERTEX ||
936                 b->shader->info.stage == MESA_SHADER_TESS_EVAL ||
937                 b->shader->info.stage == MESA_SHADER_MESH))
938          *mode = nir_var_shader_out;
939       else
940          vtn_fail("invalid stage for SpvBuiltInLayer");
941       break;
942    case SpvBuiltInViewportIndex:
943       *location = VARYING_SLOT_VIEWPORT;
944       if (b->shader->info.stage == MESA_SHADER_GEOMETRY)
945          *mode = nir_var_shader_out;
946       else if (b->supported_capabilities.ShaderViewportIndexLayerEXT &&
947                (b->shader->info.stage == MESA_SHADER_VERTEX ||
948                 b->shader->info.stage == MESA_SHADER_TESS_EVAL ||
949                 b->shader->info.stage == MESA_SHADER_MESH))
950          *mode = nir_var_shader_out;
951       else if (b->shader->info.stage == MESA_SHADER_FRAGMENT)
952          *mode = nir_var_shader_in;
953       else
954          vtn_fail("invalid stage for SpvBuiltInViewportIndex");
955       break;
956    case SpvBuiltInViewportMaskNV:
957    case SpvBuiltInViewportMaskPerViewNV:
958       *location = VARYING_SLOT_VIEWPORT_MASK;
959       *mode = nir_var_shader_out;
960       break;
961    case SpvBuiltInTessLevelOuter:
962       *location = VARYING_SLOT_TESS_LEVEL_OUTER;
963       break;
964    case SpvBuiltInTessLevelInner:
965       *location = VARYING_SLOT_TESS_LEVEL_INNER;
966       break;
967    case SpvBuiltInTessCoord:
968       *location = SYSTEM_VALUE_TESS_COORD;
969       set_mode_system_value(b, mode);
970       break;
971    case SpvBuiltInPatchVertices:
972       *location = SYSTEM_VALUE_VERTICES_IN;
973       set_mode_system_value(b, mode);
974       break;
975    case SpvBuiltInFragCoord:
976       vtn_assert(*mode == nir_var_shader_in);
977       *mode = nir_var_system_value;
978       *location = SYSTEM_VALUE_FRAG_COORD;
979       break;
980    case SpvBuiltInPointCoord:
981       vtn_assert(*mode == nir_var_shader_in);
982       set_mode_system_value(b, mode);
983       *location = SYSTEM_VALUE_POINT_COORD;
984       break;
985    case SpvBuiltInFrontFacing:
986       *location = SYSTEM_VALUE_FRONT_FACE;
987       set_mode_system_value(b, mode);
988       break;
989    case SpvBuiltInSampleId:
990       *location = SYSTEM_VALUE_SAMPLE_ID;
991       set_mode_system_value(b, mode);
992       break;
993    case SpvBuiltInSamplePosition:
994       *location = SYSTEM_VALUE_SAMPLE_POS;
995       set_mode_system_value(b, mode);
996       break;
997    case SpvBuiltInSampleMask:
998       if (*mode == nir_var_shader_out) {
999          *location = FRAG_RESULT_SAMPLE_MASK;
1000       } else {
1001          *location = SYSTEM_VALUE_SAMPLE_MASK_IN;
1002          set_mode_system_value(b, mode);
1003       }
1004       break;
1005    case SpvBuiltInFragDepth:
1006       *location = FRAG_RESULT_DEPTH;
1007       vtn_assert(*mode == nir_var_shader_out);
1008       break;
1009    case SpvBuiltInHelperInvocation:
1010       *location = SYSTEM_VALUE_HELPER_INVOCATION;
1011       set_mode_system_value(b, mode);
1012       break;
1013    case SpvBuiltInNumWorkgroups:
1014       *location = SYSTEM_VALUE_NUM_WORKGROUPS;
1015       set_mode_system_value(b, mode);
1016       break;
1017    case SpvBuiltInWorkgroupSize:
1018    case SpvBuiltInEnqueuedWorkgroupSize:
1019       *location = SYSTEM_VALUE_WORKGROUP_SIZE;
1020       set_mode_system_value(b, mode);
1021       break;
1022    case SpvBuiltInWorkgroupId:
1023       *location = SYSTEM_VALUE_WORKGROUP_ID;
1024       set_mode_system_value(b, mode);
1025       break;
1026    case SpvBuiltInLocalInvocationId:
1027       *location = SYSTEM_VALUE_LOCAL_INVOCATION_ID;
1028       set_mode_system_value(b, mode);
1029       break;
1030    case SpvBuiltInLocalInvocationIndex:
1031       *location = SYSTEM_VALUE_LOCAL_INVOCATION_INDEX;
1032       set_mode_system_value(b, mode);
1033       break;
1034    case SpvBuiltInGlobalInvocationId:
1035       *location = SYSTEM_VALUE_GLOBAL_INVOCATION_ID;
1036       set_mode_system_value(b, mode);
1037       break;
1038    case SpvBuiltInGlobalLinearId:
1039       *location = SYSTEM_VALUE_GLOBAL_INVOCATION_INDEX;
1040       set_mode_system_value(b, mode);
1041       break;
1042    case SpvBuiltInGlobalOffset:
1043       *location = SYSTEM_VALUE_BASE_GLOBAL_INVOCATION_ID;
1044       set_mode_system_value(b, mode);
1045       break;
1046    case SpvBuiltInBaseVertex:
1047       /* OpenGL gl_BaseVertex (SYSTEM_VALUE_BASE_VERTEX) is not the same
1048        * semantic as Vulkan BaseVertex (SYSTEM_VALUE_FIRST_VERTEX).
1049        */
1050       if (b->options->environment == NIR_SPIRV_OPENGL)
1051          *location = SYSTEM_VALUE_BASE_VERTEX;
1052       else
1053          *location = SYSTEM_VALUE_FIRST_VERTEX;
1054       set_mode_system_value(b, mode);
1055       break;
1056    case SpvBuiltInBaseInstance:
1057       *location = SYSTEM_VALUE_BASE_INSTANCE;
1058       set_mode_system_value(b, mode);
1059       break;
1060    case SpvBuiltInDrawIndex:
1061       *location = SYSTEM_VALUE_DRAW_ID;
1062       set_mode_system_value(b, mode);
1063       break;
1064    case SpvBuiltInSubgroupSize:
1065    /* TODO once we support non uniform work groups we have to fix this */
1066    case SpvBuiltInSubgroupMaxSize:
1067       *location = SYSTEM_VALUE_SUBGROUP_SIZE;
1068       set_mode_system_value(b, mode);
1069       break;
1070    case SpvBuiltInSubgroupId:
1071       *location = SYSTEM_VALUE_SUBGROUP_ID;
1072       set_mode_system_value(b, mode);
1073       break;
1074    case SpvBuiltInSubgroupLocalInvocationId:
1075       *location = SYSTEM_VALUE_SUBGROUP_INVOCATION;
1076       set_mode_system_value(b, mode);
1077       break;
1078    case SpvBuiltInNumSubgroups:
1079    /* TODO once we support non uniform work groups we have to fix this */
1080    case SpvBuiltInNumEnqueuedSubgroups:
1081       *location = SYSTEM_VALUE_NUM_SUBGROUPS;
1082       set_mode_system_value(b, mode);
1083       break;
1084    case SpvBuiltInDeviceIndex:
1085       *location = SYSTEM_VALUE_DEVICE_INDEX;
1086       set_mode_system_value(b, mode);
1087       break;
1088    case SpvBuiltInViewIndex:
1089       if (b->options && b->options->view_index_is_input) {
1090          *location = VARYING_SLOT_VIEW_INDEX;
1091          vtn_assert(*mode == nir_var_shader_in);
1092       } else {
1093          *location = SYSTEM_VALUE_VIEW_INDEX;
1094          set_mode_system_value(b, mode);
1095       }
1096       break;
1097    case SpvBuiltInSubgroupEqMask:
1098       *location = SYSTEM_VALUE_SUBGROUP_EQ_MASK,
1099       set_mode_system_value(b, mode);
1100       break;
1101    case SpvBuiltInSubgroupGeMask:
1102       *location = SYSTEM_VALUE_SUBGROUP_GE_MASK,
1103       set_mode_system_value(b, mode);
1104       break;
1105    case SpvBuiltInSubgroupGtMask:
1106       *location = SYSTEM_VALUE_SUBGROUP_GT_MASK,
1107       set_mode_system_value(b, mode);
1108       break;
1109    case SpvBuiltInSubgroupLeMask:
1110       *location = SYSTEM_VALUE_SUBGROUP_LE_MASK,
1111       set_mode_system_value(b, mode);
1112       break;
1113    case SpvBuiltInSubgroupLtMask:
1114       *location = SYSTEM_VALUE_SUBGROUP_LT_MASK,
1115       set_mode_system_value(b, mode);
1116       break;
1117    case SpvBuiltInFragStencilRefEXT:
1118       *location = FRAG_RESULT_STENCIL;
1119       vtn_assert(*mode == nir_var_shader_out);
1120       break;
1121    case SpvBuiltInWorkDim:
1122       *location = SYSTEM_VALUE_WORK_DIM;
1123       set_mode_system_value(b, mode);
1124       break;
1125    case SpvBuiltInGlobalSize:
1126       *location = SYSTEM_VALUE_GLOBAL_GROUP_SIZE;
1127       set_mode_system_value(b, mode);
1128       break;
1129    case SpvBuiltInBaryCoordNoPerspAMD:
1130       *location = SYSTEM_VALUE_BARYCENTRIC_LINEAR_PIXEL;
1131       set_mode_system_value(b, mode);
1132       break;
1133    case SpvBuiltInBaryCoordNoPerspCentroidAMD:
1134       *location = SYSTEM_VALUE_BARYCENTRIC_LINEAR_CENTROID;
1135       set_mode_system_value(b, mode);
1136       break;
1137    case SpvBuiltInBaryCoordNoPerspSampleAMD:
1138       *location = SYSTEM_VALUE_BARYCENTRIC_LINEAR_SAMPLE;
1139       set_mode_system_value(b, mode);
1140       break;
1141    case SpvBuiltInBaryCoordSmoothAMD:
1142       *location = SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL;
1143       set_mode_system_value(b, mode);
1144       break;
1145    case SpvBuiltInBaryCoordSmoothCentroidAMD:
1146       *location = SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTROID;
1147       set_mode_system_value(b, mode);
1148       break;
1149    case SpvBuiltInBaryCoordSmoothSampleAMD:
1150       *location = SYSTEM_VALUE_BARYCENTRIC_PERSP_SAMPLE;
1151       set_mode_system_value(b, mode);
1152       break;
1153    case SpvBuiltInBaryCoordPullModelAMD:
1154       *location = SYSTEM_VALUE_BARYCENTRIC_PULL_MODEL;
1155       set_mode_system_value(b, mode);
1156       break;
1157    case SpvBuiltInLaunchIdKHR:
1158       *location = SYSTEM_VALUE_RAY_LAUNCH_ID;
1159       set_mode_system_value(b, mode);
1160       break;
1161    case SpvBuiltInLaunchSizeKHR:
1162       *location = SYSTEM_VALUE_RAY_LAUNCH_SIZE;
1163       set_mode_system_value(b, mode);
1164       break;
1165    case SpvBuiltInWorldRayOriginKHR:
1166       *location = SYSTEM_VALUE_RAY_WORLD_ORIGIN;
1167       set_mode_system_value(b, mode);
1168       break;
1169    case SpvBuiltInWorldRayDirectionKHR:
1170       *location = SYSTEM_VALUE_RAY_WORLD_DIRECTION;
1171       set_mode_system_value(b, mode);
1172       break;
1173    case SpvBuiltInObjectRayOriginKHR:
1174       *location = SYSTEM_VALUE_RAY_OBJECT_ORIGIN;
1175       set_mode_system_value(b, mode);
1176       break;
1177    case SpvBuiltInObjectRayDirectionKHR:
1178       *location = SYSTEM_VALUE_RAY_OBJECT_DIRECTION;
1179       set_mode_system_value(b, mode);
1180       break;
1181    case SpvBuiltInObjectToWorldKHR:
1182       *location = SYSTEM_VALUE_RAY_OBJECT_TO_WORLD;
1183       set_mode_system_value(b, mode);
1184       break;
1185    case SpvBuiltInWorldToObjectKHR:
1186       *location = SYSTEM_VALUE_RAY_WORLD_TO_OBJECT;
1187       set_mode_system_value(b, mode);
1188       break;
1189    case SpvBuiltInRayTminKHR:
1190       *location = SYSTEM_VALUE_RAY_T_MIN;
1191       set_mode_system_value(b, mode);
1192       break;
1193    case SpvBuiltInRayTmaxKHR:
1194    case SpvBuiltInHitTNV:
1195       *location = SYSTEM_VALUE_RAY_T_MAX;
1196       set_mode_system_value(b, mode);
1197       break;
1198    case SpvBuiltInInstanceCustomIndexKHR:
1199       *location = SYSTEM_VALUE_RAY_INSTANCE_CUSTOM_INDEX;
1200       set_mode_system_value(b, mode);
1201       break;
1202    case SpvBuiltInHitKindKHR:
1203       *location = SYSTEM_VALUE_RAY_HIT_KIND;
1204       set_mode_system_value(b, mode);
1205       break;
1206    case SpvBuiltInIncomingRayFlagsKHR:
1207       *location = SYSTEM_VALUE_RAY_FLAGS;
1208       set_mode_system_value(b, mode);
1209       break;
1210    case SpvBuiltInRayGeometryIndexKHR:
1211       *location = SYSTEM_VALUE_RAY_GEOMETRY_INDEX;
1212       set_mode_system_value(b, mode);
1213       break;
1214    case SpvBuiltInCullMaskKHR:
1215       *location = SYSTEM_VALUE_CULL_MASK;
1216       set_mode_system_value(b, mode);
1217       break;
1218    case SpvBuiltInShadingRateKHR:
1219       *location = SYSTEM_VALUE_FRAG_SHADING_RATE;
1220       set_mode_system_value(b, mode);
1221       break;
1222    case SpvBuiltInPrimitiveShadingRateKHR:
1223       if (b->shader->info.stage == MESA_SHADER_VERTEX ||
1224           b->shader->info.stage == MESA_SHADER_GEOMETRY ||
1225           b->shader->info.stage == MESA_SHADER_MESH) {
1226          *location = VARYING_SLOT_PRIMITIVE_SHADING_RATE;
1227          *mode = nir_var_shader_out;
1228       } else {
1229          vtn_fail("invalid stage for SpvBuiltInPrimitiveShadingRateKHR");
1230       }
1231       break;
1232    case SpvBuiltInPrimitiveCountNV:
1233       *location = VARYING_SLOT_PRIMITIVE_COUNT;
1234       break;
1235    case SpvBuiltInPrimitivePointIndicesEXT:
1236    case SpvBuiltInPrimitiveLineIndicesEXT:
1237    case SpvBuiltInPrimitiveTriangleIndicesEXT:
1238    case SpvBuiltInPrimitiveIndicesNV:
1239       *location = VARYING_SLOT_PRIMITIVE_INDICES;
1240       break;
1241    case SpvBuiltInTaskCountNV:
1242       /* NV_mesh_shader only. */
1243       *location = VARYING_SLOT_TASK_COUNT;
1244       *mode = nir_var_shader_out;
1245       break;
1246    case SpvBuiltInMeshViewCountNV:
1247       *location = SYSTEM_VALUE_MESH_VIEW_COUNT;
1248       set_mode_system_value(b, mode);
1249       break;
1250    case SpvBuiltInMeshViewIndicesNV:
1251       *location = SYSTEM_VALUE_MESH_VIEW_INDICES;
1252       set_mode_system_value(b, mode);
1253       break;
1254    case SpvBuiltInCullPrimitiveEXT:
1255       *location = VARYING_SLOT_CULL_PRIMITIVE;
1256       break;
1257    case SpvBuiltInFullyCoveredEXT:
1258       *location = SYSTEM_VALUE_FULLY_COVERED;
1259       set_mode_system_value(b, mode);
1260       break;
1261    case SpvBuiltInFragSizeEXT:
1262       *location = SYSTEM_VALUE_FRAG_SIZE;
1263       set_mode_system_value(b, mode);
1264       break;
1265    case SpvBuiltInFragInvocationCountEXT:
1266       *location = SYSTEM_VALUE_FRAG_INVOCATION_COUNT;
1267       set_mode_system_value(b, mode);
1268       break;
1269    case SpvBuiltInHitTriangleVertexPositionsKHR:
1270       *location = SYSTEM_VALUE_RAY_TRIANGLE_VERTEX_POSITIONS;
1271       set_mode_system_value(b, mode);
1272       break;
1273    case SpvBuiltInBaryCoordKHR:
1274       *location = SYSTEM_VALUE_BARYCENTRIC_PERSP_COORD;
1275       set_mode_system_value(b, mode);
1276       break;
1277    case SpvBuiltInBaryCoordNoPerspKHR:
1278       *location = SYSTEM_VALUE_BARYCENTRIC_LINEAR_COORD;
1279       set_mode_system_value(b, mode);
1280       break;
1281    case SpvBuiltInShaderIndexAMDX:
1282       *location = SYSTEM_VALUE_SHADER_INDEX;
1283       set_mode_system_value(b, mode);
1284       break;
1285 
1286    case SpvBuiltInWarpsPerSMNV:
1287       *location = SYSTEM_VALUE_WARPS_PER_SM_NV;
1288       set_mode_system_value(b, mode);
1289       break;
1290 
1291    case SpvBuiltInSMCountNV:
1292       *location = SYSTEM_VALUE_SM_COUNT_NV;
1293       set_mode_system_value(b, mode);
1294       break;
1295 
1296    case SpvBuiltInWarpIDNV:
1297       *location = SYSTEM_VALUE_WARP_ID_NV;
1298       set_mode_system_value(b, mode);
1299       break;
1300 
1301    case SpvBuiltInSMIDNV:
1302       *location = SYSTEM_VALUE_SM_ID_NV;
1303       set_mode_system_value(b, mode);
1304       break;
1305 
1306    default:
1307       vtn_fail("Unsupported builtin: %s (%u)",
1308                spirv_builtin_to_string(builtin), builtin);
1309    }
1310 }
1311 
1312 static void
apply_var_decoration(struct vtn_builder * b,struct nir_variable_data * var_data,const struct vtn_decoration * dec)1313 apply_var_decoration(struct vtn_builder *b,
1314                      struct nir_variable_data *var_data,
1315                      const struct vtn_decoration *dec)
1316 {
1317    switch (dec->decoration) {
1318    case SpvDecorationRelaxedPrecision:
1319       var_data->precision = GLSL_PRECISION_MEDIUM;
1320       break;
1321    case SpvDecorationNoPerspective:
1322       var_data->interpolation = INTERP_MODE_NOPERSPECTIVE;
1323       break;
1324    case SpvDecorationFlat:
1325       var_data->interpolation = INTERP_MODE_FLAT;
1326       break;
1327    case SpvDecorationExplicitInterpAMD:
1328       var_data->interpolation = INTERP_MODE_EXPLICIT;
1329       break;
1330    case SpvDecorationCentroid:
1331       var_data->centroid = true;
1332       break;
1333    case SpvDecorationSample:
1334       var_data->sample = true;
1335       break;
1336    case SpvDecorationInvariant:
1337       var_data->invariant = true;
1338       break;
1339    case SpvDecorationConstant:
1340       var_data->read_only = true;
1341       break;
1342    case SpvDecorationNonReadable:
1343       var_data->access |= ACCESS_NON_READABLE;
1344       break;
1345    case SpvDecorationNonWritable:
1346       var_data->read_only = true;
1347       var_data->access |= ACCESS_NON_WRITEABLE;
1348       break;
1349    case SpvDecorationRestrict:
1350       var_data->access |= ACCESS_RESTRICT;
1351       break;
1352    case SpvDecorationAliased:
1353       var_data->access &= ~ACCESS_RESTRICT;
1354       break;
1355    case SpvDecorationVolatile:
1356       var_data->access |= ACCESS_VOLATILE;
1357       break;
1358    case SpvDecorationCoherent:
1359       var_data->access |= ACCESS_COHERENT;
1360       break;
1361    case SpvDecorationComponent:
1362       var_data->location_frac = dec->operands[0];
1363       break;
1364    case SpvDecorationIndex:
1365       var_data->index = dec->operands[0];
1366       break;
1367    case SpvDecorationBuiltIn: {
1368       SpvBuiltIn builtin = dec->operands[0];
1369 
1370       nir_variable_mode mode = var_data->mode;
1371       vtn_get_builtin_location(b, builtin, &var_data->location, &mode);
1372       var_data->mode = mode;
1373 
1374       switch (builtin) {
1375       case SpvBuiltInTessLevelOuter:
1376       case SpvBuiltInTessLevelInner:
1377       case SpvBuiltInClipDistance:
1378       case SpvBuiltInClipDistancePerViewNV:
1379       case SpvBuiltInCullDistance:
1380       case SpvBuiltInCullDistancePerViewNV:
1381          var_data->compact = true;
1382          break;
1383       case SpvBuiltInPrimitivePointIndicesEXT:
1384       case SpvBuiltInPrimitiveLineIndicesEXT:
1385       case SpvBuiltInPrimitiveTriangleIndicesEXT:
1386          /* Not defined as per-primitive in the EXT, but they behave
1387           * like per-primitive outputs so it's easier to treat them like that.
1388           * They may still require special treatment in the backend in order to
1389           * control where and how they are stored.
1390           *
1391           * EXT_mesh_shader: write-only array of vectors indexed by the primitive index
1392           * NV_mesh_shader: read/write flat array
1393           */
1394          var_data->per_primitive = true;
1395          break;
1396       default:
1397          break;
1398       }
1399 
1400       break;
1401    }
1402 
1403    case SpvDecorationSpecId:
1404    case SpvDecorationRowMajor:
1405    case SpvDecorationColMajor:
1406    case SpvDecorationMatrixStride:
1407    case SpvDecorationUniform:
1408    case SpvDecorationUniformId:
1409    case SpvDecorationLinkageAttributes:
1410       break; /* Do nothing with these here */
1411 
1412    case SpvDecorationPatch:
1413       var_data->patch = true;
1414       break;
1415 
1416    case SpvDecorationLocation:
1417       vtn_fail("Should be handled earlier by var_decoration_cb()");
1418 
1419    case SpvDecorationBlock:
1420    case SpvDecorationBufferBlock:
1421    case SpvDecorationArrayStride:
1422    case SpvDecorationGLSLShared:
1423    case SpvDecorationGLSLPacked:
1424       break; /* These can apply to a type but we don't care about them */
1425 
1426    case SpvDecorationBinding:
1427    case SpvDecorationDescriptorSet:
1428    case SpvDecorationNoContraction:
1429    case SpvDecorationInputAttachmentIndex:
1430       vtn_warn("Decoration not allowed for variable or structure member: %s",
1431                spirv_decoration_to_string(dec->decoration));
1432       break;
1433 
1434    case SpvDecorationXfbBuffer:
1435       var_data->explicit_xfb_buffer = true;
1436       var_data->xfb.buffer = dec->operands[0];
1437       var_data->always_active_io = true;
1438       break;
1439    case SpvDecorationXfbStride:
1440       var_data->explicit_xfb_stride = true;
1441       var_data->xfb.stride = dec->operands[0];
1442       break;
1443    case SpvDecorationOffset:
1444       var_data->explicit_offset = true;
1445       var_data->offset = dec->operands[0];
1446       break;
1447 
1448    case SpvDecorationStream:
1449       var_data->stream = dec->operands[0];
1450       break;
1451 
1452    case SpvDecorationCPacked:
1453    case SpvDecorationSaturatedConversion:
1454    case SpvDecorationFuncParamAttr:
1455    case SpvDecorationFPRoundingMode:
1456    case SpvDecorationAlignment:
1457       if (b->shader->info.stage != MESA_SHADER_KERNEL) {
1458          vtn_warn("Decoration only allowed for CL-style kernels: %s",
1459                   spirv_decoration_to_string(dec->decoration));
1460       }
1461       break;
1462 
1463    case SpvDecorationFPFastMathMode:
1464       /* See handle_fp_fast_math(). */
1465       break;
1466 
1467    case SpvDecorationUserSemantic:
1468    case SpvDecorationUserTypeGOOGLE:
1469       /* User semantic decorations can safely be ignored by the driver. */
1470       break;
1471 
1472    case SpvDecorationRestrictPointerEXT:
1473    case SpvDecorationAliasedPointerEXT:
1474       /* TODO: We should actually plumb alias information through NIR. */
1475       break;
1476 
1477    case SpvDecorationPerPrimitiveNV:
1478       vtn_fail_if(
1479          !(b->shader->info.stage == MESA_SHADER_MESH && var_data->mode == nir_var_shader_out) &&
1480          !(b->shader->info.stage == MESA_SHADER_FRAGMENT && var_data->mode == nir_var_shader_in),
1481          "PerPrimitiveNV decoration only allowed for Mesh shader outputs or Fragment shader inputs");
1482       var_data->per_primitive = true;
1483       break;
1484 
1485    case SpvDecorationPerTaskNV:
1486       vtn_fail_if(
1487          (b->shader->info.stage != MESA_SHADER_MESH &&
1488           b->shader->info.stage != MESA_SHADER_TASK) ||
1489          var_data->mode != nir_var_mem_task_payload,
1490          "PerTaskNV decoration only allowed on Task/Mesh payload variables.");
1491       break;
1492 
1493    case SpvDecorationPerViewNV:
1494       vtn_fail_if(b->shader->info.stage != MESA_SHADER_MESH,
1495                   "PerViewNV decoration only allowed in Mesh shaders");
1496       var_data->per_view = true;
1497       break;
1498 
1499    case SpvDecorationPerVertexKHR:
1500       vtn_fail_if(b->shader->info.stage != MESA_SHADER_FRAGMENT,
1501                   "PerVertexKHR decoration only allowed in Fragment shaders");
1502       var_data->per_vertex = true;
1503       break;
1504 
1505    case SpvDecorationNodeMaxPayloadsAMDX:
1506       vtn_fail_if(b->shader->info.stage != MESA_SHADER_COMPUTE,
1507                   "NodeMaxPayloadsAMDX decoration only allowed in compute shaders");
1508       break;
1509 
1510    case SpvDecorationNodeSharesPayloadLimitsWithAMDX:
1511       vtn_fail_if(b->shader->info.stage != MESA_SHADER_COMPUTE,
1512                   "NodeMaxPayloadsAMDX decoration only allowed in compute shaders");
1513       break;
1514 
1515    case SpvDecorationPayloadNodeNameAMDX:
1516       vtn_fail_if(b->shader->info.stage != MESA_SHADER_COMPUTE,
1517                   "NodeMaxPayloadsAMDX decoration only allowed in compute shaders");
1518       var_data->node_name = vtn_string_literal(b, dec->operands, dec->num_operands, NULL);
1519       break;
1520 
1521    case SpvDecorationTrackFinishWritingAMDX:
1522       vtn_fail_if(b->shader->info.stage != MESA_SHADER_COMPUTE,
1523                   "NodeMaxPayloadsAMDX decoration only allowed in compute shaders");
1524       break;
1525 
1526    default:
1527       vtn_fail_with_decoration("Unhandled decoration", dec->decoration);
1528    }
1529 }
1530 
1531 static void
gather_var_kind_cb(struct vtn_builder * b,struct vtn_value * val,int member,const struct vtn_decoration * dec,void * void_var)1532 gather_var_kind_cb(struct vtn_builder *b, struct vtn_value *val, int member,
1533                    const struct vtn_decoration *dec, void *void_var)
1534 {
1535    struct vtn_variable *vtn_var = void_var;
1536    switch (dec->decoration) {
1537    case SpvDecorationPatch:
1538       vtn_var->var->data.patch = true;
1539       break;
1540    case SpvDecorationPerPrimitiveNV:
1541       vtn_var->var->data.per_primitive = true;
1542       break;
1543    case SpvDecorationPerViewNV:
1544       vtn_var->var->data.per_view = true;
1545       break;
1546    default:
1547       /* Nothing to do. */
1548       break;
1549    }
1550 }
1551 
1552 static void
var_set_alignment(struct vtn_builder * b,struct vtn_variable * vtn_var,uint32_t alignment)1553 var_set_alignment(struct vtn_builder *b, struct vtn_variable *vtn_var,
1554                   uint32_t alignment)
1555 {
1556    if (alignment == 0) {
1557       vtn_warn("Specified alignment is zero, ignoring");
1558       return;
1559    }
1560 
1561    if (!util_is_power_of_two_or_zero(alignment)) {
1562       /* This isn't actually a requirement anywhere in any spec but it seems
1563        * reasonable to enforce.
1564        */
1565       unsigned real_align = 1 << (ffs(alignment) - 1);
1566       vtn_warn("Alignment of %u specified, which not a power of two, "
1567                "using %u instead", alignment, real_align);
1568       alignment = real_align;
1569    }
1570 
1571    vtn_var->var->data.alignment = alignment;
1572 }
1573 
1574 static void
var_decoration_cb(struct vtn_builder * b,struct vtn_value * val,int member,const struct vtn_decoration * dec,void * void_var)1575 var_decoration_cb(struct vtn_builder *b, struct vtn_value *val, int member,
1576                   const struct vtn_decoration *dec, void *void_var)
1577 {
1578    struct vtn_variable *vtn_var = void_var;
1579 
1580    /* Handle decorations that apply to a vtn_variable as a whole */
1581    switch (dec->decoration) {
1582    case SpvDecorationBinding:
1583       vtn_var->binding = dec->operands[0];
1584       vtn_var->explicit_binding = true;
1585       return;
1586    case SpvDecorationDescriptorSet:
1587       vtn_var->descriptor_set = dec->operands[0];
1588       return;
1589    case SpvDecorationInputAttachmentIndex:
1590       vtn_var->input_attachment_index = dec->operands[0];
1591       vtn_var->access |= ACCESS_NON_WRITEABLE;
1592       return;
1593    case SpvDecorationAlignment:
1594       var_set_alignment(b, vtn_var, dec->operands[0]);
1595       break;
1596    case SpvDecorationAlignmentId:
1597       var_set_alignment(b, vtn_var, vtn_constant_uint(b, dec->operands[0]));
1598       break;
1599    case SpvDecorationPatch:
1600       vtn_var->var->data.patch = true;
1601       break;
1602    case SpvDecorationOffset:
1603       vtn_var->offset = dec->operands[0];
1604       break;
1605    case SpvDecorationNonWritable:
1606       vtn_var->access |= ACCESS_NON_WRITEABLE;
1607       break;
1608    case SpvDecorationNonReadable:
1609       vtn_var->access |= ACCESS_NON_READABLE;
1610       break;
1611    case SpvDecorationVolatile:
1612       vtn_var->access |= ACCESS_VOLATILE;
1613       break;
1614    case SpvDecorationCoherent:
1615       vtn_var->access |= ACCESS_COHERENT;
1616       break;
1617    case SpvDecorationCounterBuffer:
1618       /* Counter buffer decorations can safely be ignored by the driver. */
1619       return;
1620    case SpvDecorationBuiltIn:
1621       /* Non-volatile gl_HelperInvocation after demote is undefined.
1622        * In order to avoid application bugs, make it volatile if we use demote.
1623        */
1624       if (dec->operands[0] == SpvBuiltInHelperInvocation &&
1625           (b->enabled_capabilities.DemoteToHelperInvocation ||
1626            b->convert_discard_to_demote))
1627          vtn_var->access |= ACCESS_VOLATILE;
1628       break;
1629    default:
1630       break;
1631    }
1632 
1633    if (val->value_type == vtn_value_type_pointer) {
1634       assert(val->pointer->var == void_var);
1635       assert(member == -1);
1636    } else {
1637       assert(val->value_type == vtn_value_type_type);
1638    }
1639 
1640    /* Location is odd.  If applied to a split structure, we have to walk the
1641     * whole thing and accumulate the location.  It's easier to handle as a
1642     * special case.
1643     */
1644    if (dec->decoration == SpvDecorationLocation) {
1645       unsigned location = dec->operands[0];
1646       if (b->shader->info.stage == MESA_SHADER_FRAGMENT &&
1647           vtn_var->mode == vtn_variable_mode_output) {
1648          location += FRAG_RESULT_DATA0;
1649       } else if (b->shader->info.stage == MESA_SHADER_VERTEX &&
1650                  vtn_var->mode == vtn_variable_mode_input) {
1651          location += VERT_ATTRIB_GENERIC0;
1652       } else if (vtn_var->mode == vtn_variable_mode_input ||
1653                  vtn_var->mode == vtn_variable_mode_output) {
1654          location += VARYING_SLOT_VAR0;
1655       } else if (vtn_var->mode == vtn_variable_mode_call_data ||
1656                  vtn_var->mode == vtn_variable_mode_ray_payload) {
1657          /* This location is fine as-is */
1658       } else if (vtn_var->mode != vtn_variable_mode_uniform &&
1659                  vtn_var->mode != vtn_variable_mode_image) {
1660          vtn_warn("Location must be on input, output, uniform, sampler or "
1661                   "image variable");
1662          return;
1663       }
1664 
1665       if (vtn_var->var->num_members == 0) {
1666          /* This handles the member and lone variable cases */
1667          vtn_var->var->data.location = location;
1668       } else {
1669          /* This handles the structure member case */
1670          assert(vtn_var->var->members);
1671 
1672          if (member == -1)
1673             vtn_var->base_location = location;
1674          else
1675             vtn_var->var->members[member].location = location;
1676       }
1677 
1678       return;
1679    } else {
1680       if (vtn_var->var) {
1681          if (vtn_var->var->num_members == 0) {
1682             /* We call this function on types as well as variables and not all
1683              * struct types get split so we can end up having stray member
1684              * decorations; just ignore them.
1685              */
1686             if (member == -1)
1687                apply_var_decoration(b, &vtn_var->var->data, dec);
1688          } else if (member >= 0) {
1689             /* Member decorations must come from a type */
1690             assert(val->value_type == vtn_value_type_type);
1691             apply_var_decoration(b, &vtn_var->var->members[member], dec);
1692          } else {
1693             unsigned length =
1694                glsl_get_length(glsl_without_array(vtn_var->type->type));
1695             for (unsigned i = 0; i < length; i++)
1696                apply_var_decoration(b, &vtn_var->var->members[i], dec);
1697          }
1698       } else {
1699          /* A few variables, those with external storage, have no actual
1700           * nir_variables associated with them.  Fortunately, all decorations
1701           * we care about for those variables are on the type only.
1702           */
1703          vtn_assert(vtn_var->mode == vtn_variable_mode_ubo ||
1704                     vtn_var->mode == vtn_variable_mode_ssbo ||
1705                     vtn_var->mode == vtn_variable_mode_push_constant);
1706       }
1707    }
1708 }
1709 
1710 enum vtn_variable_mode
vtn_storage_class_to_mode(struct vtn_builder * b,SpvStorageClass class,struct vtn_type * interface_type,nir_variable_mode * nir_mode_out)1711 vtn_storage_class_to_mode(struct vtn_builder *b,
1712                           SpvStorageClass class,
1713                           struct vtn_type *interface_type,
1714                           nir_variable_mode *nir_mode_out)
1715 {
1716    enum vtn_variable_mode mode;
1717    nir_variable_mode nir_mode;
1718    switch (class) {
1719    case SpvStorageClassUniform:
1720       /* Assume it's an UBO if we lack the interface_type. */
1721       if (!interface_type || interface_type->block) {
1722          mode = vtn_variable_mode_ubo;
1723          nir_mode = nir_var_mem_ubo;
1724       } else if (interface_type->buffer_block) {
1725          mode = vtn_variable_mode_ssbo;
1726          nir_mode = nir_var_mem_ssbo;
1727       } else {
1728          /* Default-block uniforms, coming from gl_spirv */
1729          mode = vtn_variable_mode_uniform;
1730          nir_mode = nir_var_uniform;
1731       }
1732       break;
1733    case SpvStorageClassStorageBuffer:
1734       mode = vtn_variable_mode_ssbo;
1735       nir_mode = nir_var_mem_ssbo;
1736       break;
1737    case SpvStorageClassPhysicalStorageBuffer:
1738       mode = vtn_variable_mode_phys_ssbo;
1739       nir_mode = nir_var_mem_global;
1740       break;
1741    case SpvStorageClassUniformConstant:
1742       /* interface_type is only NULL when OpTypeForwardPointer is used and
1743        * OpTypeForwardPointer can only be used for struct types, not images or
1744        * acceleration structures.
1745        */
1746       if (interface_type)
1747          interface_type = vtn_type_without_array(interface_type);
1748 
1749       if (interface_type &&
1750           interface_type->base_type == vtn_base_type_image &&
1751           glsl_type_is_image(interface_type->glsl_image)) {
1752          mode = vtn_variable_mode_image;
1753          nir_mode = nir_var_image;
1754       } else if (b->shader->info.stage == MESA_SHADER_KERNEL) {
1755          mode = vtn_variable_mode_constant;
1756          nir_mode = nir_var_mem_constant;
1757       } else {
1758          /* interface_type is only NULL when OpTypeForwardPointer is used and
1759           * OpTypeForwardPointer cannot be used with the UniformConstant
1760           * storage class.
1761           */
1762          assert(interface_type != NULL);
1763          if (interface_type->base_type == vtn_base_type_accel_struct) {
1764             mode = vtn_variable_mode_accel_struct;
1765             nir_mode = nir_var_uniform;
1766          } else {
1767             mode = vtn_variable_mode_uniform;
1768             nir_mode = nir_var_uniform;
1769          }
1770       }
1771       break;
1772    case SpvStorageClassPushConstant:
1773       mode = vtn_variable_mode_push_constant;
1774       nir_mode = nir_var_mem_push_const;
1775       break;
1776    case SpvStorageClassInput:
1777       mode = vtn_variable_mode_input;
1778       nir_mode = nir_var_shader_in;
1779 
1780       /* NV_mesh_shader: fixup due to lack of dedicated storage class */
1781       if (b->shader->info.stage == MESA_SHADER_MESH) {
1782          mode = vtn_variable_mode_task_payload;
1783          nir_mode = nir_var_mem_task_payload;
1784       }
1785       break;
1786    case SpvStorageClassOutput:
1787       mode = vtn_variable_mode_output;
1788       nir_mode = nir_var_shader_out;
1789 
1790       /* NV_mesh_shader: fixup due to lack of dedicated storage class */
1791       if (b->shader->info.stage == MESA_SHADER_TASK) {
1792          mode = vtn_variable_mode_task_payload;
1793          nir_mode = nir_var_mem_task_payload;
1794       }
1795       break;
1796    case SpvStorageClassPrivate:
1797       mode = vtn_variable_mode_private;
1798       nir_mode = nir_var_shader_temp;
1799       break;
1800    case SpvStorageClassFunction:
1801       mode = vtn_variable_mode_function;
1802       nir_mode = nir_var_function_temp;
1803       break;
1804    case SpvStorageClassWorkgroup:
1805       mode = vtn_variable_mode_workgroup;
1806       nir_mode = nir_var_mem_shared;
1807       break;
1808    case SpvStorageClassTaskPayloadWorkgroupEXT:
1809       mode = vtn_variable_mode_task_payload;
1810       nir_mode = nir_var_mem_task_payload;
1811       break;
1812    case SpvStorageClassAtomicCounter:
1813       mode = vtn_variable_mode_atomic_counter;
1814       nir_mode = nir_var_uniform;
1815       break;
1816    case SpvStorageClassCrossWorkgroup:
1817       mode = vtn_variable_mode_cross_workgroup;
1818       nir_mode = nir_var_mem_global;
1819       break;
1820    case SpvStorageClassImage:
1821       mode = vtn_variable_mode_image;
1822       nir_mode = nir_var_image;
1823       break;
1824    case SpvStorageClassCallableDataKHR:
1825       mode = vtn_variable_mode_call_data;
1826       nir_mode = nir_var_shader_temp;
1827       break;
1828    case SpvStorageClassIncomingCallableDataKHR:
1829       mode = vtn_variable_mode_call_data_in;
1830       nir_mode = nir_var_shader_call_data;
1831       break;
1832    case SpvStorageClassRayPayloadKHR:
1833       mode = vtn_variable_mode_ray_payload;
1834       nir_mode = nir_var_shader_temp;
1835       break;
1836    case SpvStorageClassIncomingRayPayloadKHR:
1837       mode = vtn_variable_mode_ray_payload_in;
1838       nir_mode = nir_var_shader_call_data;
1839       break;
1840    case SpvStorageClassHitAttributeKHR:
1841       mode = vtn_variable_mode_hit_attrib;
1842       nir_mode = nir_var_ray_hit_attrib;
1843       break;
1844    case SpvStorageClassShaderRecordBufferKHR:
1845       mode = vtn_variable_mode_shader_record;
1846       nir_mode = nir_var_mem_constant;
1847       break;
1848    case SpvStorageClassNodePayloadAMDX:
1849       mode = vtn_variable_mode_node_payload;
1850       nir_mode = nir_var_mem_node_payload_in;
1851       break;
1852 
1853    case SpvStorageClassGeneric:
1854       mode = vtn_variable_mode_generic;
1855       nir_mode = nir_var_mem_generic;
1856       break;
1857    default:
1858       vtn_fail("Unhandled variable storage class: %s (%u)",
1859                spirv_storageclass_to_string(class), class);
1860    }
1861 
1862    if (nir_mode_out)
1863       *nir_mode_out = nir_mode;
1864 
1865    return mode;
1866 }
1867 
1868 nir_address_format
vtn_mode_to_address_format(struct vtn_builder * b,enum vtn_variable_mode mode)1869 vtn_mode_to_address_format(struct vtn_builder *b, enum vtn_variable_mode mode)
1870 {
1871    switch (mode) {
1872    case vtn_variable_mode_ubo:
1873       return b->options->ubo_addr_format;
1874 
1875    case vtn_variable_mode_ssbo:
1876       return b->options->ssbo_addr_format;
1877 
1878    case vtn_variable_mode_phys_ssbo:
1879       return b->options->phys_ssbo_addr_format;
1880 
1881    case vtn_variable_mode_push_constant:
1882       return b->options->push_const_addr_format;
1883 
1884    case vtn_variable_mode_workgroup:
1885       return b->options->shared_addr_format;
1886 
1887    case vtn_variable_mode_generic:
1888    case vtn_variable_mode_cross_workgroup:
1889       return b->options->global_addr_format;
1890 
1891    case vtn_variable_mode_shader_record:
1892    case vtn_variable_mode_constant:
1893       return b->options->constant_addr_format;
1894 
1895    case vtn_variable_mode_accel_struct:
1896    case vtn_variable_mode_node_payload:
1897       return nir_address_format_64bit_global;
1898 
1899    case vtn_variable_mode_task_payload:
1900       return b->options->task_payload_addr_format;
1901 
1902    case vtn_variable_mode_function:
1903       if (b->physical_ptrs)
1904          return b->options->temp_addr_format;
1905       FALLTHROUGH;
1906 
1907    case vtn_variable_mode_private:
1908    case vtn_variable_mode_uniform:
1909    case vtn_variable_mode_atomic_counter:
1910    case vtn_variable_mode_input:
1911    case vtn_variable_mode_output:
1912    case vtn_variable_mode_image:
1913    case vtn_variable_mode_call_data:
1914    case vtn_variable_mode_call_data_in:
1915    case vtn_variable_mode_ray_payload:
1916    case vtn_variable_mode_ray_payload_in:
1917    case vtn_variable_mode_hit_attrib:
1918       return nir_address_format_logical;
1919    }
1920 
1921    unreachable("Invalid variable mode");
1922 }
1923 
1924 nir_def *
vtn_pointer_to_ssa(struct vtn_builder * b,struct vtn_pointer * ptr)1925 vtn_pointer_to_ssa(struct vtn_builder *b, struct vtn_pointer *ptr)
1926 {
1927    if ((vtn_pointer_is_external_block(b, ptr) &&
1928         vtn_type_contains_block(b, ptr->type->pointed) &&
1929         ptr->mode != vtn_variable_mode_phys_ssbo) ||
1930        ptr->mode == vtn_variable_mode_accel_struct) {
1931       /* In this case, we're looking for a block index and not an actual
1932        * deref.
1933        *
1934        * For PhysicalStorageBuffer pointers, we don't have a block index
1935        * at all because we get the pointer directly from the client.  This
1936        * assumes that there will never be a SSBO binding variable using the
1937        * PhysicalStorageBuffer storage class.  This assumption appears
1938        * to be correct according to the Vulkan spec because the table,
1939        * "Shader Resource and Storage Class Correspondence," the only the
1940        * Uniform storage class with BufferBlock or the StorageBuffer
1941        * storage class with Block can be used.
1942        */
1943       if (!ptr->block_index) {
1944          /* If we don't have a block_index then we must be a pointer to the
1945           * variable itself.
1946           */
1947          vtn_assert(!ptr->deref);
1948 
1949          struct vtn_access_chain chain = {
1950             .length = 0,
1951          };
1952          ptr = vtn_pointer_dereference(b, ptr, &chain);
1953       }
1954 
1955       return ptr->block_index;
1956    } else {
1957       return &vtn_pointer_to_deref(b, ptr)->def;
1958    }
1959 }
1960 
1961 struct vtn_pointer *
vtn_pointer_from_ssa(struct vtn_builder * b,nir_def * ssa,struct vtn_type * ptr_type)1962 vtn_pointer_from_ssa(struct vtn_builder *b, nir_def *ssa,
1963                      struct vtn_type *ptr_type)
1964 {
1965    vtn_assert(ptr_type->base_type == vtn_base_type_pointer);
1966 
1967    struct vtn_pointer *ptr = vtn_zalloc(b, struct vtn_pointer);
1968    struct vtn_type *without_array =
1969       vtn_type_without_array(ptr_type->pointed);
1970 
1971    nir_variable_mode nir_mode;
1972    ptr->mode = vtn_storage_class_to_mode(b, ptr_type->storage_class,
1973                                          without_array, &nir_mode);
1974    ptr->type = ptr_type;
1975 
1976    const struct glsl_type *deref_type =
1977       vtn_type_get_nir_type(b, ptr_type->pointed, ptr->mode);
1978    if (!vtn_pointer_is_external_block(b, ptr) &&
1979        ptr->mode != vtn_variable_mode_accel_struct) {
1980       ptr->deref = nir_build_deref_cast(&b->nb, ssa, nir_mode,
1981                                         deref_type, ptr_type->stride);
1982    } else if ((vtn_type_contains_block(b, ptr->type->pointed) &&
1983                ptr->mode != vtn_variable_mode_phys_ssbo) ||
1984               ptr->mode == vtn_variable_mode_accel_struct) {
1985       /* This is a pointer to somewhere in an array of blocks, not a
1986        * pointer to somewhere inside the block.  Set the block index
1987        * instead of making a cast.
1988        */
1989       ptr->block_index = ssa;
1990    } else {
1991       /* This is a pointer to something internal or a pointer inside a
1992        * block.  It's just a regular cast.
1993        *
1994        * For PhysicalStorageBuffer pointers, we don't have a block index
1995        * at all because we get the pointer directly from the client.  This
1996        * assumes that there will never be a SSBO binding variable using the
1997        * PhysicalStorageBuffer storage class.  This assumption appears
1998        * to be correct according to the Vulkan spec because the table,
1999        * "Shader Resource and Storage Class Correspondence," the only the
2000        * Uniform storage class with BufferBlock or the StorageBuffer
2001        * storage class with Block can be used.
2002        */
2003       ptr->deref = nir_build_deref_cast(&b->nb, ssa, nir_mode,
2004                                         deref_type, ptr_type->stride);
2005       ptr->deref->def.num_components =
2006          glsl_get_vector_elements(ptr_type->type);
2007       ptr->deref->def.bit_size = glsl_get_bit_size(ptr_type->type);
2008    }
2009 
2010    return ptr;
2011 }
2012 
2013 static void
assign_missing_member_locations(struct vtn_variable * var)2014 assign_missing_member_locations(struct vtn_variable *var)
2015 {
2016    unsigned length =
2017       glsl_get_length(glsl_without_array(var->type->type));
2018    int location = var->base_location;
2019 
2020    for (unsigned i = 0; i < length; i++) {
2021       /* From the Vulkan spec:
2022        *
2023        * “If the structure type is a Block but without a Location, then each
2024        *  of its members must have a Location decoration.”
2025        *
2026        */
2027       if (var->type->block) {
2028          assert(var->base_location != -1 ||
2029                 var->var->members[i].location != -1);
2030       }
2031 
2032       /* From the Vulkan spec:
2033        *
2034        * “Any member with its own Location decoration is assigned that
2035        *  location. Each remaining member is assigned the location after the
2036        *  immediately preceding member in declaration order.”
2037        */
2038       if (var->var->members[i].location != -1)
2039          location = var->var->members[i].location;
2040       else
2041          var->var->members[i].location = location;
2042 
2043       /* Below we use type instead of interface_type, because interface_type
2044        * is only available when it is a Block. This code also supports
2045        * input/outputs that are just structs
2046        */
2047       const struct glsl_type *member_type =
2048          glsl_get_struct_field(glsl_without_array(var->type->type), i);
2049 
2050       location +=
2051          glsl_count_attribute_slots(member_type,
2052                                     false /* is_gl_vertex_input */);
2053    }
2054 }
2055 
2056 static void
adjust_patch_locations(struct vtn_builder * b,struct vtn_variable * var)2057 adjust_patch_locations(struct vtn_builder *b, struct vtn_variable *var)
2058 {
2059    uint16_t num_data = 1;
2060    struct nir_variable_data *data = &var->var->data;
2061    if (var->var->members) {
2062       num_data = var->var->num_members;
2063       data = var->var->members;
2064    }
2065 
2066    for (uint16_t i = 0; i < num_data; i++) {
2067       vtn_assert(data[i].location < VARYING_SLOT_PATCH0);
2068       if (data[i].patch &&
2069           (data[i].mode == nir_var_shader_in || data[i].mode == nir_var_shader_out) &&
2070           data[i].location >= VARYING_SLOT_VAR0)
2071          data[i].location += VARYING_SLOT_PATCH0 - VARYING_SLOT_VAR0;
2072    }
2073 }
2074 
2075 nir_deref_instr *
vtn_get_call_payload_for_location(struct vtn_builder * b,uint32_t location_id)2076 vtn_get_call_payload_for_location(struct vtn_builder *b, uint32_t location_id)
2077 {
2078    uint32_t location = vtn_constant_uint(b, location_id);
2079    nir_foreach_variable_with_modes(var, b->nb.shader, nir_var_shader_temp) {
2080       if (var->data.explicit_location &&
2081           var->data.location == location)
2082          return nir_build_deref_var(&b->nb, var);
2083    }
2084    vtn_fail("Couldn't find variable with a storage class of CallableDataKHR "
2085             "or RayPayloadKHR and location %d", location);
2086 }
2087 
2088 static bool
vtn_type_is_ray_query(struct vtn_type * type)2089 vtn_type_is_ray_query(struct vtn_type *type)
2090 {
2091    return vtn_type_without_array(type)->base_type == vtn_base_type_ray_query;
2092 }
2093 
2094 static void
vtn_create_variable(struct vtn_builder * b,struct vtn_value * val,struct vtn_type * ptr_type,SpvStorageClass storage_class,struct vtn_value * initializer)2095 vtn_create_variable(struct vtn_builder *b, struct vtn_value *val,
2096                     struct vtn_type *ptr_type, SpvStorageClass storage_class,
2097                     struct vtn_value *initializer)
2098 {
2099    vtn_assert(ptr_type->base_type == vtn_base_type_pointer);
2100    struct vtn_type *type = ptr_type->pointed;
2101 
2102    struct vtn_type *without_array = vtn_type_without_array(ptr_type->pointed);
2103 
2104    enum vtn_variable_mode mode;
2105    nir_variable_mode nir_mode;
2106    mode = vtn_storage_class_to_mode(b, storage_class, without_array, &nir_mode);
2107 
2108    switch (mode) {
2109    case vtn_variable_mode_ubo:
2110       /* There's no other way to get vtn_variable_mode_ubo */
2111       vtn_assert(without_array->block);
2112       break;
2113    case vtn_variable_mode_ssbo:
2114       if (storage_class == SpvStorageClassStorageBuffer &&
2115           !without_array->block) {
2116          if (!b->enabled_capabilities.VariablePointers &&
2117              !b->enabled_capabilities.VariablePointersStorageBuffer) {
2118             vtn_fail("Variables in the StorageBuffer storage class must "
2119                      "have a struct type with the Block decoration");
2120          } else {
2121             /* If variable pointers are not present, it's still malformed
2122              * SPIR-V but we can parse it and do the right thing anyway.
2123              * Since some of the 8-bit storage tests have bugs in this are,
2124              * just make it a warning for now.
2125              */
2126             vtn_warn("Variables in the StorageBuffer storage class must "
2127                      "have a struct type with the Block decoration");
2128          }
2129       }
2130       break;
2131 
2132    case vtn_variable_mode_generic:
2133       vtn_fail("Cannot create a variable with the Generic storage class");
2134       break;
2135 
2136    case vtn_variable_mode_image:
2137       if (storage_class == SpvStorageClassImage)
2138          vtn_fail("Cannot create a variable with the Image storage class");
2139       else
2140          vtn_assert(storage_class == SpvStorageClassUniformConstant);
2141       break;
2142 
2143    case vtn_variable_mode_phys_ssbo:
2144       vtn_fail("Cannot create a variable with the "
2145                "PhysicalStorageBuffer storage class");
2146       break;
2147 
2148    default:
2149       /* No tallying is needed */
2150       break;
2151    }
2152 
2153    struct vtn_variable *var = vtn_zalloc(b, struct vtn_variable);
2154    var->type = type;
2155    var->mode = mode;
2156    var->base_location = -1;
2157    var->input_attachment_index = NIR_VARIABLE_NO_INDEX;
2158 
2159    val->pointer = vtn_zalloc(b, struct vtn_pointer);
2160    val->pointer->mode = var->mode;
2161    val->pointer->type = ptr_type;
2162    val->pointer->var = var;
2163    val->pointer->access = var->type->access;
2164 
2165    switch (var->mode) {
2166    case vtn_variable_mode_function:
2167    case vtn_variable_mode_private:
2168    case vtn_variable_mode_uniform:
2169    case vtn_variable_mode_atomic_counter:
2170    case vtn_variable_mode_constant:
2171    case vtn_variable_mode_call_data:
2172    case vtn_variable_mode_call_data_in:
2173    case vtn_variable_mode_image:
2174    case vtn_variable_mode_ray_payload:
2175    case vtn_variable_mode_ray_payload_in:
2176    case vtn_variable_mode_hit_attrib:
2177    case vtn_variable_mode_node_payload:
2178       /* For these, we create the variable normally */
2179       var->var = rzalloc(b->shader, nir_variable);
2180       var->var->name = ralloc_strdup(var->var, val->name);
2181       var->var->type = vtn_type_get_nir_type(b, var->type, var->mode);
2182 
2183       /* This is a total hack but we need some way to flag variables which are
2184        * going to be call payloads.  See get_call_payload_deref.
2185        */
2186       if (storage_class == SpvStorageClassCallableDataKHR ||
2187           storage_class == SpvStorageClassRayPayloadKHR)
2188          var->var->data.explicit_location = true;
2189 
2190       var->var->data.mode = nir_mode;
2191       var->var->data.location = -1;
2192       var->var->data.ray_query = vtn_type_is_ray_query(var->type);
2193       var->var->interface_type = NULL;
2194       break;
2195 
2196    case vtn_variable_mode_ubo:
2197    case vtn_variable_mode_ssbo:
2198    case vtn_variable_mode_push_constant:
2199    case vtn_variable_mode_accel_struct:
2200    case vtn_variable_mode_shader_record:
2201       var->var = rzalloc(b->shader, nir_variable);
2202       var->var->name = ralloc_strdup(var->var, val->name);
2203 
2204       var->var->type = vtn_type_get_nir_type(b, var->type, var->mode);
2205       var->var->interface_type = var->var->type;
2206 
2207       var->var->data.mode = nir_mode;
2208       var->var->data.location = -1;
2209       var->var->data.driver_location = 0;
2210       var->var->data.access = var->type->access;
2211       break;
2212 
2213    case vtn_variable_mode_workgroup:
2214    case vtn_variable_mode_cross_workgroup:
2215    case vtn_variable_mode_task_payload:
2216       /* Create the variable normally */
2217       var->var = rzalloc(b->shader, nir_variable);
2218       var->var->name = ralloc_strdup(var->var, val->name);
2219       var->var->type = vtn_type_get_nir_type(b, var->type, var->mode);
2220       var->var->data.mode = nir_mode;
2221       break;
2222 
2223    case vtn_variable_mode_input:
2224    case vtn_variable_mode_output: {
2225       var->var = rzalloc(b->shader, nir_variable);
2226       var->var->name = ralloc_strdup(var->var, val->name);
2227       var->var->type = vtn_type_get_nir_type(b, var->type, var->mode);
2228       var->var->data.mode = nir_mode;
2229 
2230       /* In order to know whether or not we're a per-vertex inout, we need
2231        * the patch qualifier.  This means walking the variable decorations
2232        * early before we actually create any variables.  Not a big deal.
2233        *
2234        * GLSLang really likes to place decorations in the most interior
2235        * thing it possibly can.  In particular, if you have a struct, it
2236        * will place the patch decorations on the struct members.  This
2237        * should be handled by the variable splitting below just fine.
2238        *
2239        * If you have an array-of-struct, things get even more weird as it
2240        * will place the patch decorations on the struct even though it's
2241        * inside an array and some of the members being patch and others not
2242        * makes no sense whatsoever.  Since the only sensible thing is for
2243        * it to be all or nothing, we'll call it patch if any of the members
2244        * are declared patch.
2245        */
2246       vtn_foreach_decoration(b, val, gather_var_kind_cb, var);
2247       if (glsl_type_is_array(var->type->type) &&
2248           glsl_type_is_struct_or_ifc(without_array->type)) {
2249          vtn_foreach_decoration(b, vtn_value(b, without_array->id,
2250                                              vtn_value_type_type),
2251                                 gather_var_kind_cb, var);
2252       }
2253 
2254       struct vtn_type *per_vertex_type = var->type;
2255       if (nir_is_arrayed_io(var->var, b->shader->info.stage))
2256          per_vertex_type = var->type->array_element;
2257 
2258       /* Figure out the interface block type. */
2259       struct vtn_type *iface_type = per_vertex_type;
2260       if (var->mode == vtn_variable_mode_output &&
2261           (b->shader->info.stage == MESA_SHADER_VERTEX ||
2262            b->shader->info.stage == MESA_SHADER_TESS_EVAL ||
2263            b->shader->info.stage == MESA_SHADER_GEOMETRY)) {
2264          /* For vertex data outputs, we can end up with arrays of blocks for
2265           * transform feedback where each array element corresponds to a
2266           * different XFB output buffer.
2267           */
2268          while (iface_type->base_type == vtn_base_type_array)
2269             iface_type = iface_type->array_element;
2270       }
2271       if (iface_type->base_type == vtn_base_type_struct && iface_type->block)
2272          var->var->interface_type = vtn_type_get_nir_type(b, iface_type,
2273                                                           var->mode);
2274 
2275       /* If it's a block, set it up as per-member so can be splitted later by
2276        * nir_split_per_member_structs.
2277        *
2278        * This is for a couple of reasons.  For one, builtins may all come in a
2279        * block and we really want those split out into separate variables.
2280        * For another, interpolation qualifiers can be applied to members of
2281        * the top-level struct and we need to be able to preserve that
2282        * information.
2283        */
2284       if (per_vertex_type->base_type == vtn_base_type_struct &&
2285           per_vertex_type->block) {
2286          var->var->num_members = glsl_get_length(per_vertex_type->type);
2287          var->var->members = rzalloc_array(var->var, struct nir_variable_data,
2288                                            var->var->num_members);
2289 
2290          for (unsigned i = 0; i < var->var->num_members; i++) {
2291             var->var->members[i].mode = nir_mode;
2292             var->var->members[i].patch = var->var->data.patch;
2293             var->var->members[i].location = -1;
2294          }
2295       }
2296 
2297       /* For inputs and outputs, we need to grab locations and builtin
2298        * information from the per-vertex type.
2299        */
2300       vtn_foreach_decoration(b, vtn_value(b, per_vertex_type->id,
2301                                           vtn_value_type_type),
2302                              var_decoration_cb, var);
2303 
2304       break;
2305    }
2306 
2307    case vtn_variable_mode_phys_ssbo:
2308    case vtn_variable_mode_generic:
2309       unreachable("Should have been caught before");
2310    }
2311 
2312    /* Ignore incorrectly generated Undef initializers. */
2313    if (b->wa_llvm_spirv_ignore_workgroup_initializer &&
2314        initializer &&
2315        storage_class == SpvStorageClassWorkgroup)
2316       initializer = NULL;
2317 
2318    /* Only initialize variable when there is an initializer and it's not
2319     * undef.
2320     */
2321    if (initializer && !initializer->is_undef_constant) {
2322       switch (storage_class) {
2323       case SpvStorageClassWorkgroup:
2324          /* VK_KHR_zero_initialize_workgroup_memory. */
2325          vtn_fail_if(b->options->environment != NIR_SPIRV_VULKAN,
2326                      "Only Vulkan supports variable initializer "
2327                      "for Workgroup variable %u",
2328                      vtn_id_for_value(b, val));
2329          vtn_fail_if(initializer->value_type != vtn_value_type_constant ||
2330                      !initializer->is_null_constant,
2331                      "Workgroup variable %u can only have OpConstantNull "
2332                      "as initializer, but have %u instead",
2333                      vtn_id_for_value(b, val),
2334                      vtn_id_for_value(b, initializer));
2335          b->shader->info.zero_initialize_shared_memory = true;
2336          break;
2337 
2338       case SpvStorageClassUniformConstant:
2339          vtn_fail_if(b->options->environment != NIR_SPIRV_OPENGL &&
2340                      b->options->environment != NIR_SPIRV_OPENCL,
2341                      "Only OpenGL and OpenCL support variable initializer "
2342                      "for UniformConstant variable %u\n",
2343                      vtn_id_for_value(b, val));
2344          vtn_fail_if(initializer->value_type != vtn_value_type_constant,
2345                      "UniformConstant variable %u can only have a constant "
2346                      "initializer, but have %u instead",
2347                      vtn_id_for_value(b, val),
2348                      vtn_id_for_value(b, initializer));
2349          break;
2350 
2351       case SpvStorageClassOutput:
2352       case SpvStorageClassPrivate:
2353          vtn_assert(b->options->environment != NIR_SPIRV_OPENCL);
2354          /* These can have any initializer. */
2355          break;
2356 
2357       case SpvStorageClassFunction:
2358          /* These can have any initializer. */
2359          break;
2360 
2361       case SpvStorageClassCrossWorkgroup:
2362          vtn_assert(b->options->environment == NIR_SPIRV_OPENCL);
2363          vtn_fail("Initializer for CrossWorkgroup variable %u "
2364                   "not yet supported in Mesa.",
2365                   vtn_id_for_value(b, val));
2366          break;
2367 
2368       default: {
2369          const enum nir_spirv_execution_environment env =
2370             b->options->environment;
2371          const char *env_name =
2372             env == NIR_SPIRV_VULKAN ? "Vulkan" :
2373             env == NIR_SPIRV_OPENCL ? "OpenCL" :
2374             env == NIR_SPIRV_OPENGL ? "OpenGL" :
2375             NULL;
2376          vtn_assert(env_name);
2377          vtn_fail("In %s, any OpVariable with an Initializer operand "
2378                   "must have %s%s%s, or Function as "
2379                   "its Storage Class operand.  Variable %u has an "
2380                   "Initializer but its Storage Class is %s.",
2381                   env_name,
2382                   env == NIR_SPIRV_VULKAN ? "Private, Output, Workgroup" : "",
2383                   env == NIR_SPIRV_OPENCL ? "CrossWorkgroup, UniformConstant" : "",
2384                   env == NIR_SPIRV_OPENGL ? "Private, Output, UniformConstant" : "",
2385                   vtn_id_for_value(b, val),
2386                   spirv_storageclass_to_string(storage_class));
2387          }
2388       }
2389 
2390       switch (initializer->value_type) {
2391       case vtn_value_type_constant:
2392          var->var->constant_initializer =
2393             nir_constant_clone(initializer->constant, var->var);
2394          break;
2395       case vtn_value_type_pointer:
2396          var->var->pointer_initializer = initializer->pointer->var->var;
2397          break;
2398       default:
2399          vtn_fail("SPIR-V variable initializer %u must be constant or pointer",
2400                   vtn_id_for_value(b, initializer));
2401       }
2402    }
2403 
2404    if (var->mode == vtn_variable_mode_uniform ||
2405        var->mode == vtn_variable_mode_image ||
2406        var->mode == vtn_variable_mode_ssbo) {
2407       /* SSBOs and images are assumed to not alias in the Simple, GLSL and Vulkan memory models */
2408       var->var->data.access |= b->mem_model != SpvMemoryModelOpenCL ? ACCESS_RESTRICT : 0;
2409    }
2410 
2411    vtn_foreach_decoration(b, val, var_decoration_cb, var);
2412    vtn_foreach_decoration(b, val, ptr_decoration_cb, val->pointer);
2413 
2414    /* Propagate access flags from the OpVariable decorations. */
2415    val->pointer->access |= var->access;
2416 
2417    if ((var->mode == vtn_variable_mode_input ||
2418         var->mode == vtn_variable_mode_output) &&
2419        var->var->members) {
2420       assign_missing_member_locations(var);
2421    }
2422 
2423    if ((b->shader->info.stage == MESA_SHADER_TESS_CTRL &&
2424         var->mode == vtn_variable_mode_output) ||
2425        (b->shader->info.stage == MESA_SHADER_TESS_EVAL &&
2426         var->mode == vtn_variable_mode_input))
2427       adjust_patch_locations(b, var);
2428 
2429    if (var->mode == vtn_variable_mode_uniform ||
2430        var->mode == vtn_variable_mode_image ||
2431        var->mode == vtn_variable_mode_ubo ||
2432        var->mode == vtn_variable_mode_ssbo ||
2433        var->mode == vtn_variable_mode_atomic_counter) {
2434       /* XXX: We still need the binding information in the nir_variable
2435        * for these. We should fix that.
2436        */
2437       var->var->data.binding = var->binding;
2438       var->var->data.explicit_binding = var->explicit_binding;
2439       var->var->data.descriptor_set = var->descriptor_set;
2440       var->var->data.index = var->input_attachment_index;
2441       var->var->data.offset = var->offset;
2442 
2443       if (glsl_type_is_image(glsl_without_array(var->var->type)))
2444          var->var->data.image.format = without_array->image_format;
2445    }
2446 
2447    if (var->mode == vtn_variable_mode_function) {
2448       vtn_assert(var->var != NULL && var->var->members == NULL);
2449       nir_function_impl_add_variable(b->nb.impl, var->var);
2450    } else if (var->var) {
2451       nir_shader_add_variable(b->shader, var->var);
2452    } else {
2453       vtn_assert(vtn_pointer_is_external_block(b, val->pointer) ||
2454                  var->mode == vtn_variable_mode_accel_struct ||
2455                  var->mode == vtn_variable_mode_shader_record);
2456    }
2457 }
2458 
2459 static void
vtn_assert_types_equal(struct vtn_builder * b,SpvOp opcode,struct vtn_type * dst_type,struct vtn_type * src_type)2460 vtn_assert_types_equal(struct vtn_builder *b, SpvOp opcode,
2461                        struct vtn_type *dst_type,
2462                        struct vtn_type *src_type)
2463 {
2464    if (!dst_type->id || !src_type->id) {
2465       /* Either of those are internal types, so just check for compatibility. */
2466       vtn_assert(vtn_types_compatible(b, dst_type, src_type));
2467       return;
2468    }
2469 
2470    if (dst_type->id == src_type->id)
2471       return;
2472 
2473    if (vtn_types_compatible(b, dst_type, src_type)) {
2474       /* Early versions of GLSLang would re-emit types unnecessarily and you
2475        * would end up with OpLoad, OpStore, or OpCopyMemory opcodes which have
2476        * mismatched source and destination types.
2477        *
2478        * https://github.com/KhronosGroup/glslang/issues/304
2479        * https://github.com/KhronosGroup/glslang/issues/307
2480        * https://bugs.freedesktop.org/show_bug.cgi?id=104338
2481        * https://bugs.freedesktop.org/show_bug.cgi?id=104424
2482        */
2483       vtn_warn("Source and destination types of %s do not have the same "
2484                "ID (but are compatible): %u vs %u",
2485                 spirv_op_to_string(opcode), dst_type->id, src_type->id);
2486       return;
2487    }
2488 
2489    vtn_fail("Source and destination types of %s do not match: %s (%%%u) vs. %s (%%%u)",
2490             spirv_op_to_string(opcode),
2491             glsl_get_type_name(dst_type->type), dst_type->id,
2492             glsl_get_type_name(src_type->type), src_type->id);
2493 }
2494 
2495 static nir_def *
nir_shrink_zero_pad_vec(nir_builder * b,nir_def * val,unsigned num_components)2496 nir_shrink_zero_pad_vec(nir_builder *b, nir_def *val,
2497                         unsigned num_components)
2498 {
2499    if (val->num_components == num_components)
2500       return val;
2501 
2502    nir_def *comps[NIR_MAX_VEC_COMPONENTS];
2503    for (unsigned i = 0; i < num_components; i++) {
2504       if (i < val->num_components)
2505          comps[i] = nir_channel(b, val, i);
2506       else
2507          comps[i] = nir_imm_intN_t(b, 0, val->bit_size);
2508    }
2509    return nir_vec(b, comps, num_components);
2510 }
2511 
2512 static nir_def *
nir_sloppy_bitcast(nir_builder * b,nir_def * val,const struct glsl_type * type)2513 nir_sloppy_bitcast(nir_builder *b, nir_def *val,
2514                    const struct glsl_type *type)
2515 {
2516    const unsigned num_components = glsl_get_vector_elements(type);
2517    const unsigned bit_size = glsl_get_bit_size(type);
2518 
2519    /* First, zero-pad to ensure that the value is big enough that when we
2520     * bit-cast it, we don't loose anything.
2521     */
2522    if (val->bit_size < bit_size) {
2523       const unsigned src_num_components_needed =
2524          vtn_align_u32(val->num_components, bit_size / val->bit_size);
2525       val = nir_shrink_zero_pad_vec(b, val, src_num_components_needed);
2526    }
2527 
2528    val = nir_bitcast_vector(b, val, bit_size);
2529 
2530    return nir_shrink_zero_pad_vec(b, val, num_components);
2531 }
2532 
2533 bool
vtn_get_mem_operands(struct vtn_builder * b,const uint32_t * w,unsigned count,unsigned * idx,SpvMemoryAccessMask * access,unsigned * alignment,SpvScope * dest_scope,SpvScope * src_scope)2534 vtn_get_mem_operands(struct vtn_builder *b, const uint32_t *w, unsigned count,
2535                      unsigned *idx, SpvMemoryAccessMask *access, unsigned *alignment,
2536                      SpvScope *dest_scope, SpvScope *src_scope)
2537 {
2538    *access = 0;
2539    *alignment = 0;
2540    if (*idx >= count)
2541       return false;
2542 
2543    *access = w[(*idx)++];
2544    if (*access & SpvMemoryAccessAlignedMask) {
2545       vtn_assert(*idx < count);
2546       *alignment = w[(*idx)++];
2547    }
2548 
2549    if (*access & SpvMemoryAccessMakePointerAvailableMask) {
2550       vtn_assert(*idx < count);
2551       vtn_assert(dest_scope);
2552       *dest_scope = vtn_constant_uint(b, w[(*idx)++]);
2553    }
2554 
2555    if (*access & SpvMemoryAccessMakePointerVisibleMask) {
2556       vtn_assert(*idx < count);
2557       vtn_assert(src_scope);
2558       *src_scope = vtn_constant_uint(b, w[(*idx)++]);
2559    }
2560 
2561    return true;
2562 }
2563 
2564 static enum gl_access_qualifier
spv_access_to_gl_access(SpvMemoryAccessMask access)2565 spv_access_to_gl_access(SpvMemoryAccessMask access)
2566 {
2567    unsigned result = 0;
2568 
2569    if (access & SpvMemoryAccessVolatileMask)
2570       result |= ACCESS_VOLATILE;
2571    if (access & SpvMemoryAccessNontemporalMask)
2572       result |= ACCESS_NON_TEMPORAL;
2573 
2574    return result;
2575 }
2576 
2577 
2578 SpvMemorySemanticsMask
vtn_mode_to_memory_semantics(enum vtn_variable_mode mode)2579 vtn_mode_to_memory_semantics(enum vtn_variable_mode mode)
2580 {
2581    switch (mode) {
2582    case vtn_variable_mode_ssbo:
2583    case vtn_variable_mode_phys_ssbo:
2584       return SpvMemorySemanticsUniformMemoryMask;
2585    case vtn_variable_mode_workgroup:
2586       return SpvMemorySemanticsWorkgroupMemoryMask;
2587    case vtn_variable_mode_cross_workgroup:
2588       return SpvMemorySemanticsCrossWorkgroupMemoryMask;
2589    case vtn_variable_mode_atomic_counter:
2590       return SpvMemorySemanticsAtomicCounterMemoryMask;
2591    case vtn_variable_mode_image:
2592       return SpvMemorySemanticsImageMemoryMask;
2593    case vtn_variable_mode_output:
2594       return SpvMemorySemanticsOutputMemoryMask;
2595    default:
2596       return SpvMemorySemanticsMaskNone;
2597    }
2598 }
2599 
2600 void
vtn_emit_make_visible_barrier(struct vtn_builder * b,SpvMemoryAccessMask access,SpvScope scope,enum vtn_variable_mode mode)2601 vtn_emit_make_visible_barrier(struct vtn_builder *b, SpvMemoryAccessMask access,
2602                               SpvScope scope, enum vtn_variable_mode mode)
2603 {
2604    if (!(access & SpvMemoryAccessMakePointerVisibleMask))
2605       return;
2606 
2607    vtn_emit_memory_barrier(b, scope, SpvMemorySemanticsMakeVisibleMask |
2608                                      SpvMemorySemanticsAcquireMask |
2609                                      vtn_mode_to_memory_semantics(mode));
2610 }
2611 
2612 void
vtn_emit_make_available_barrier(struct vtn_builder * b,SpvMemoryAccessMask access,SpvScope scope,enum vtn_variable_mode mode)2613 vtn_emit_make_available_barrier(struct vtn_builder *b, SpvMemoryAccessMask access,
2614                                 SpvScope scope, enum vtn_variable_mode mode)
2615 {
2616    if (!(access & SpvMemoryAccessMakePointerAvailableMask))
2617       return;
2618 
2619    vtn_emit_memory_barrier(b, scope, SpvMemorySemanticsMakeAvailableMask |
2620                                      SpvMemorySemanticsReleaseMask |
2621                                      vtn_mode_to_memory_semantics(mode));
2622 }
2623 
2624 static void
ptr_nonuniform_workaround_cb(struct vtn_builder * b,struct vtn_value * val,int member,const struct vtn_decoration * dec,void * void_ptr)2625 ptr_nonuniform_workaround_cb(struct vtn_builder *b, struct vtn_value *val,
2626                   int member, const struct vtn_decoration *dec, void *void_ptr)
2627 {
2628    enum gl_access_qualifier *access = void_ptr;
2629 
2630    switch (dec->decoration) {
2631    case SpvDecorationNonUniformEXT:
2632       *access |= ACCESS_NON_UNIFORM;
2633       break;
2634 
2635    default:
2636       break;
2637    }
2638 }
2639 
2640 void
vtn_handle_variables(struct vtn_builder * b,SpvOp opcode,const uint32_t * w,unsigned count)2641 vtn_handle_variables(struct vtn_builder *b, SpvOp opcode,
2642                      const uint32_t *w, unsigned count)
2643 {
2644    switch (opcode) {
2645    case SpvOpUndef: {
2646       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
2647       val->type = vtn_get_type(b, w[1]);
2648       val->is_undef_constant = true;
2649       break;
2650    }
2651 
2652    case SpvOpVariable: {
2653       struct vtn_type *ptr_type = vtn_get_type(b, w[1]);
2654 
2655       SpvStorageClass storage_class = w[3];
2656 
2657       const bool is_global = storage_class != SpvStorageClassFunction;
2658       const bool is_io = storage_class == SpvStorageClassInput ||
2659                          storage_class == SpvStorageClassOutput;
2660 
2661       /* Skip global variables that are not used by the entrypoint.  Before
2662        * SPIR-V 1.4 the interface is only used for I/O variables, so extra
2663        * variables will still need to be removed later.
2664        */
2665       if (!b->options->create_library &&
2666           (is_io || (b->version >= 0x10400 && is_global))) {
2667          if (!bsearch(&w[2], b->interface_ids, b->interface_ids_count, 4, cmp_uint32_t))
2668             break;
2669       }
2670 
2671       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
2672       struct vtn_value *initializer = count > 4 ? vtn_untyped_value(b, w[4]) : NULL;
2673 
2674       vtn_create_variable(b, val, ptr_type, storage_class, initializer);
2675 
2676       break;
2677    }
2678 
2679    case SpvOpConstantSampler: {
2680       /* Synthesize a pointer-to-sampler type, create a variable of that type,
2681        * and give the variable a constant initializer with the sampler params */
2682       struct vtn_type *sampler_type = vtn_value(b, w[1], vtn_value_type_type)->type;
2683       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
2684 
2685       struct vtn_type *ptr_type = vtn_zalloc(b, struct vtn_type);
2686       ptr_type->base_type = vtn_base_type_pointer;
2687       ptr_type->pointed = sampler_type;
2688       ptr_type->storage_class = SpvStorageClassUniform;
2689 
2690       ptr_type->type = nir_address_format_to_glsl_type(
2691          vtn_mode_to_address_format(b, vtn_variable_mode_function));
2692 
2693       vtn_create_variable(b, val, ptr_type, ptr_type->storage_class, NULL);
2694 
2695       nir_variable *nir_var = val->pointer->var->var;
2696       nir_var->data.sampler.is_inline_sampler = true;
2697       nir_var->data.sampler.addressing_mode = w[3];
2698       nir_var->data.sampler.normalized_coordinates = w[4];
2699       nir_var->data.sampler.filter_mode = w[5];
2700 
2701       break;
2702    }
2703 
2704    case SpvOpAccessChain:
2705    case SpvOpPtrAccessChain:
2706    case SpvOpInBoundsAccessChain:
2707    case SpvOpInBoundsPtrAccessChain: {
2708       struct vtn_access_chain *chain = vtn_access_chain_create(b, count - 4);
2709       enum gl_access_qualifier access = 0;
2710       chain->ptr_as_array = (opcode == SpvOpPtrAccessChain || opcode == SpvOpInBoundsPtrAccessChain);
2711 
2712       unsigned idx = 0;
2713       for (int i = 4; i < count; i++) {
2714          struct vtn_value *link_val = vtn_untyped_value(b, w[i]);
2715          if (link_val->value_type == vtn_value_type_constant) {
2716             chain->link[idx].mode = vtn_access_mode_literal;
2717             chain->link[idx].id = vtn_constant_int(b, w[i]);
2718          } else {
2719             chain->link[idx].mode = vtn_access_mode_id;
2720             chain->link[idx].id = w[i];
2721          }
2722 
2723          /* Workaround for https://gitlab.freedesktop.org/mesa/mesa/-/issues/3406 */
2724          vtn_foreach_decoration(b, link_val, ptr_nonuniform_workaround_cb, &access);
2725 
2726          idx++;
2727       }
2728 
2729       struct vtn_type *ptr_type = vtn_get_type(b, w[1]);
2730 
2731       struct vtn_pointer *base = vtn_pointer(b, w[3]);
2732 
2733       chain->in_bounds = (opcode == SpvOpInBoundsAccessChain || opcode == SpvOpInBoundsPtrAccessChain);
2734 
2735       /* Workaround for https://gitlab.freedesktop.org/mesa/mesa/-/issues/3406 */
2736       access |= base->access & ACCESS_NON_UNIFORM;
2737 
2738       if (base->mode == vtn_variable_mode_ssbo && b->options->force_ssbo_non_uniform)
2739          access |= ACCESS_NON_UNIFORM;
2740 
2741       struct vtn_pointer *ptr = vtn_pointer_dereference(b, base, chain);
2742       ptr->type = ptr_type;
2743       ptr->access |= access;
2744       vtn_push_pointer(b, w[2], ptr);
2745       break;
2746    }
2747 
2748    case SpvOpCopyMemory: {
2749       struct vtn_value *dest_val = vtn_pointer_value(b, w[1]);
2750       struct vtn_value *src_val = vtn_pointer_value(b, w[2]);
2751       struct vtn_pointer *dest = vtn_value_to_pointer(b, dest_val);
2752       struct vtn_pointer *src = vtn_value_to_pointer(b, src_val);
2753 
2754       vtn_assert_types_equal(b, opcode, dest_val->type->pointed,
2755                                         src_val->type->pointed);
2756 
2757       unsigned idx = 3, dest_alignment, src_alignment;
2758       SpvMemoryAccessMask dest_access, src_access;
2759       SpvScope dest_scope, src_scope;
2760       vtn_get_mem_operands(b, w, count, &idx, &dest_access, &dest_alignment,
2761                            &dest_scope, &src_scope);
2762       if (!vtn_get_mem_operands(b, w, count, &idx, &src_access, &src_alignment,
2763                                 NULL, &src_scope)) {
2764          src_alignment = dest_alignment;
2765          src_access = dest_access;
2766       }
2767       src = vtn_align_pointer(b, src, src_alignment);
2768       dest = vtn_align_pointer(b, dest, dest_alignment);
2769 
2770       vtn_emit_make_visible_barrier(b, src_access, src_scope, src->mode);
2771 
2772       vtn_variable_copy(b, dest, src,
2773                         spv_access_to_gl_access(dest_access),
2774                         spv_access_to_gl_access(src_access));
2775 
2776       vtn_emit_make_available_barrier(b, dest_access, dest_scope, dest->mode);
2777       break;
2778    }
2779 
2780    case SpvOpCopyMemorySized: {
2781       struct vtn_value *dest_val = vtn_pointer_value(b, w[1]);
2782       struct vtn_value *src_val = vtn_pointer_value(b, w[2]);
2783       nir_def *size = vtn_get_nir_ssa(b, w[3]);
2784       struct vtn_pointer *dest = vtn_value_to_pointer(b, dest_val);
2785       struct vtn_pointer *src = vtn_value_to_pointer(b, src_val);
2786 
2787       unsigned idx = 4, dest_alignment, src_alignment;
2788       SpvMemoryAccessMask dest_access, src_access;
2789       SpvScope dest_scope, src_scope;
2790       vtn_get_mem_operands(b, w, count, &idx, &dest_access, &dest_alignment,
2791                            &dest_scope, &src_scope);
2792       if (!vtn_get_mem_operands(b, w, count, &idx, &src_access, &src_alignment,
2793                                 NULL, &src_scope)) {
2794          src_alignment = dest_alignment;
2795          src_access = dest_access;
2796       }
2797       src = vtn_align_pointer(b, src, src_alignment);
2798       dest = vtn_align_pointer(b, dest, dest_alignment);
2799 
2800       vtn_emit_make_visible_barrier(b, src_access, src_scope, src->mode);
2801 
2802       nir_memcpy_deref_with_access(&b->nb,
2803                                    vtn_pointer_to_deref(b, dest),
2804                                    vtn_pointer_to_deref(b, src),
2805                                    size,
2806                                    spv_access_to_gl_access(dest_access),
2807                                    spv_access_to_gl_access(src_access));
2808 
2809       vtn_emit_make_available_barrier(b, dest_access, dest_scope, dest->mode);
2810       break;
2811    }
2812 
2813    case SpvOpLoad: {
2814       struct vtn_type *res_type = vtn_get_type(b, w[1]);
2815       struct vtn_value *src_val = vtn_value(b, w[3], vtn_value_type_pointer);
2816       struct vtn_pointer *src = vtn_value_to_pointer(b, src_val);
2817 
2818       vtn_assert_types_equal(b, opcode, res_type, src_val->type->pointed);
2819 
2820       unsigned idx = 4, alignment;
2821       SpvMemoryAccessMask access;
2822       SpvScope scope;
2823       vtn_get_mem_operands(b, w, count, &idx, &access, &alignment, NULL, &scope);
2824       src = vtn_align_pointer(b, src, alignment);
2825 
2826       vtn_emit_make_visible_barrier(b, access, scope, src->mode);
2827 
2828       vtn_push_ssa_value(b, w[2], vtn_variable_load(b, src, spv_access_to_gl_access(access)));
2829       break;
2830    }
2831 
2832    case SpvOpStore: {
2833       struct vtn_value *dest_val = vtn_pointer_value(b, w[1]);
2834       struct vtn_pointer *dest = vtn_value_to_pointer(b, dest_val);
2835       struct vtn_value *src_val = vtn_untyped_value(b, w[2]);
2836 
2837       /* OpStore requires us to actually have a storage type */
2838       vtn_fail_if(dest->type->pointed->type == NULL,
2839                   "Invalid destination type for OpStore");
2840 
2841       if (glsl_get_base_type(dest->type->pointed->type) == GLSL_TYPE_BOOL &&
2842           glsl_get_base_type(src_val->type->type) == GLSL_TYPE_UINT) {
2843          /* Early versions of GLSLang would use uint types for UBOs/SSBOs but
2844           * would then store them to a local variable as bool.  Work around
2845           * the issue by doing an implicit conversion.
2846           *
2847           * https://github.com/KhronosGroup/glslang/issues/170
2848           * https://bugs.freedesktop.org/show_bug.cgi?id=104424
2849           */
2850          vtn_warn("OpStore of value of type OpTypeInt to a pointer to type "
2851                   "OpTypeBool.  Doing an implicit conversion to work around "
2852                   "the problem.");
2853          struct vtn_ssa_value *bool_ssa =
2854             vtn_create_ssa_value(b, dest->type->pointed->type);
2855          bool_ssa->def = nir_i2b(&b->nb, vtn_ssa_value(b, w[2])->def);
2856          vtn_variable_store(b, bool_ssa, dest, 0);
2857          break;
2858       }
2859 
2860       vtn_assert_types_equal(b, opcode, dest_val->type->pointed, src_val->type);
2861 
2862       unsigned idx = 3, alignment;
2863       SpvMemoryAccessMask access;
2864       SpvScope scope;
2865       vtn_get_mem_operands(b, w, count, &idx, &access, &alignment, &scope, NULL);
2866       dest = vtn_align_pointer(b, dest, alignment);
2867 
2868       struct vtn_ssa_value *src = vtn_ssa_value(b, w[2]);
2869       vtn_variable_store(b, src, dest, spv_access_to_gl_access(access));
2870 
2871       vtn_emit_make_available_barrier(b, access, scope, dest->mode);
2872       break;
2873    }
2874 
2875    case SpvOpArrayLength: {
2876       struct vtn_pointer *ptr = vtn_pointer(b, w[3]);
2877       const uint32_t field = w[4];
2878 
2879       vtn_fail_if(ptr->type->pointed->base_type != vtn_base_type_struct,
2880                   "OpArrayLength must take a pointer to a structure type");
2881       vtn_fail_if(field != ptr->type->pointed->length - 1 ||
2882                   ptr->type->pointed->members[field]->base_type != vtn_base_type_array,
2883                   "OpArrayLength must reference the last member of the "
2884                   "structure and that must be an array");
2885 
2886       struct vtn_access_chain chain = {
2887          .length = 1,
2888          .link = {
2889             { .mode = vtn_access_mode_literal, .id = field },
2890          }
2891       };
2892       struct vtn_pointer *array = vtn_pointer_dereference(b, ptr, &chain);
2893 
2894       nir_def *array_length =
2895          nir_deref_buffer_array_length(&b->nb, 32,
2896                                        vtn_pointer_to_ssa(b, array),
2897                                        .access=ptr->access | ptr->type->pointed->access);
2898 
2899       vtn_push_nir_ssa(b, w[2], array_length);
2900       break;
2901    }
2902 
2903    case SpvOpConvertPtrToU: {
2904       struct vtn_type *u_type = vtn_get_type(b, w[1]);
2905       struct vtn_type *ptr_type = vtn_get_value_type(b, w[3]);
2906 
2907       vtn_fail_if(ptr_type->base_type != vtn_base_type_pointer ||
2908                   ptr_type->type == NULL,
2909                   "OpConvertPtrToU can only be used on physical pointers");
2910 
2911       vtn_fail_if(u_type->base_type != vtn_base_type_vector &&
2912                   u_type->base_type != vtn_base_type_scalar,
2913                   "OpConvertPtrToU can only be used to cast to a vector or "
2914                   "scalar type");
2915 
2916       /* The pointer will be converted to an SSA value automatically */
2917       nir_def *ptr = vtn_get_nir_ssa(b, w[3]);
2918       nir_def *u = nir_sloppy_bitcast(&b->nb, ptr, u_type->type);
2919       vtn_push_nir_ssa(b, w[2], u);
2920       break;
2921    }
2922 
2923    case SpvOpConvertUToPtr: {
2924       struct vtn_type *ptr_type = vtn_get_type(b, w[1]);
2925       struct vtn_type *u_type = vtn_get_value_type(b, w[3]);
2926 
2927       vtn_fail_if(ptr_type->base_type != vtn_base_type_pointer ||
2928                   ptr_type->type == NULL,
2929                   "OpConvertUToPtr can only be used on physical pointers");
2930 
2931       vtn_fail_if(u_type->base_type != vtn_base_type_vector &&
2932                   u_type->base_type != vtn_base_type_scalar,
2933                   "OpConvertUToPtr can only be used to cast from a vector or "
2934                   "scalar type");
2935 
2936       nir_def *u = vtn_get_nir_ssa(b, w[3]);
2937       nir_def *ptr = nir_sloppy_bitcast(&b->nb, u, ptr_type->type);
2938       vtn_push_pointer(b, w[2], vtn_pointer_from_ssa(b, ptr, ptr_type));
2939       break;
2940    }
2941 
2942    case SpvOpGenericCastToPtrExplicit: {
2943       struct vtn_type *dst_type = vtn_get_type(b, w[1]);
2944       struct vtn_type *src_type = vtn_get_value_type(b, w[3]);
2945       SpvStorageClass storage_class = w[4];
2946 
2947       vtn_fail_if(dst_type->base_type != vtn_base_type_pointer ||
2948                   dst_type->storage_class != storage_class,
2949                   "Result type of an SpvOpGenericCastToPtrExplicit must be "
2950                   "an OpTypePointer. Its Storage Class must match the "
2951                   "storage class specified in the instruction");
2952 
2953       vtn_fail_if(src_type->base_type != vtn_base_type_pointer ||
2954                   src_type->pointed->id != dst_type->pointed->id,
2955                   "Source pointer of an SpvOpGenericCastToPtrExplicit must "
2956                   "have a type of OpTypePointer whose Type is the same as "
2957                   "the Type of Result Type");
2958 
2959       vtn_fail_if(src_type->storage_class != SpvStorageClassGeneric,
2960                   "Source pointer of an SpvOpGenericCastToPtrExplicit must "
2961                   "point to the Generic Storage Class.");
2962 
2963       vtn_fail_if(storage_class != SpvStorageClassWorkgroup &&
2964                   storage_class != SpvStorageClassCrossWorkgroup &&
2965                   storage_class != SpvStorageClassFunction,
2966                   "Storage must be one of the following literal values from "
2967                   "Storage Class: Workgroup, CrossWorkgroup, or Function.");
2968 
2969       nir_deref_instr *src_deref = vtn_nir_deref(b, w[3]);
2970 
2971       nir_variable_mode nir_mode;
2972       enum vtn_variable_mode mode =
2973          vtn_storage_class_to_mode(b, storage_class, dst_type->pointed, &nir_mode);
2974       nir_address_format addr_format = vtn_mode_to_address_format(b, mode);
2975 
2976       nir_def *null_value =
2977          nir_build_imm(&b->nb, nir_address_format_num_components(addr_format),
2978                                nir_address_format_bit_size(addr_format),
2979                                nir_address_format_null_value(addr_format));
2980 
2981       nir_def *valid = nir_build_deref_mode_is(&b->nb, 1, &src_deref->def, nir_mode);
2982       vtn_push_nir_ssa(b, w[2], nir_bcsel(&b->nb, valid,
2983                                                   &src_deref->def,
2984                                                   null_value));
2985       break;
2986    }
2987 
2988    case SpvOpGenericPtrMemSemantics: {
2989       struct vtn_type *dst_type = vtn_get_type(b, w[1]);
2990       struct vtn_type *src_type = vtn_get_value_type(b, w[3]);
2991 
2992       vtn_fail_if(dst_type->base_type != vtn_base_type_scalar ||
2993                   dst_type->type != glsl_uint_type(),
2994                   "Result type of an SpvOpGenericPtrMemSemantics must be "
2995                   "an OpTypeInt with 32-bit Width and 0 Signedness.");
2996 
2997       vtn_fail_if(src_type->base_type != vtn_base_type_pointer ||
2998                   src_type->storage_class != SpvStorageClassGeneric,
2999                   "Source pointer of an SpvOpGenericPtrMemSemantics must "
3000                   "point to the Generic Storage Class");
3001 
3002       nir_deref_instr *src_deref = vtn_nir_deref(b, w[3]);
3003 
3004       nir_def *global_bit =
3005          nir_bcsel(&b->nb, nir_build_deref_mode_is(&b->nb, 1, &src_deref->def,
3006                                                    nir_var_mem_global),
3007                    nir_imm_int(&b->nb, SpvMemorySemanticsCrossWorkgroupMemoryMask),
3008                    nir_imm_int(&b->nb, 0));
3009 
3010       nir_def *shared_bit =
3011          nir_bcsel(&b->nb, nir_build_deref_mode_is(&b->nb, 1, &src_deref->def,
3012                                                    nir_var_mem_shared),
3013                    nir_imm_int(&b->nb, SpvMemorySemanticsWorkgroupMemoryMask),
3014                    nir_imm_int(&b->nb, 0));
3015 
3016       vtn_push_nir_ssa(b, w[2], nir_iand(&b->nb, global_bit, shared_bit));
3017       break;
3018    }
3019 
3020    case SpvOpSubgroupBlockReadINTEL: {
3021       struct vtn_type *res_type = vtn_get_type(b, w[1]);
3022       nir_deref_instr *src = vtn_nir_deref(b, w[3]);
3023 
3024       nir_intrinsic_instr *load =
3025          nir_intrinsic_instr_create(b->nb.shader,
3026                                     nir_intrinsic_load_deref_block_intel);
3027       load->src[0] = nir_src_for_ssa(&src->def);
3028       nir_def_init_for_type(&load->instr, &load->def, res_type->type);
3029       load->num_components = load->def.num_components;
3030       nir_builder_instr_insert(&b->nb, &load->instr);
3031 
3032       vtn_push_nir_ssa(b, w[2], &load->def);
3033       break;
3034    }
3035 
3036    case SpvOpSubgroupBlockWriteINTEL: {
3037       nir_deref_instr *dest = vtn_nir_deref(b, w[1]);
3038       nir_def *data = vtn_ssa_value(b, w[2])->def;
3039 
3040       nir_intrinsic_instr *store =
3041          nir_intrinsic_instr_create(b->nb.shader,
3042                                     nir_intrinsic_store_deref_block_intel);
3043       store->src[0] = nir_src_for_ssa(&dest->def);
3044       store->src[1] = nir_src_for_ssa(data);
3045       store->num_components = data->num_components;
3046       nir_builder_instr_insert(&b->nb, &store->instr);
3047       break;
3048    }
3049 
3050    case SpvOpConvertUToAccelerationStructureKHR: {
3051       struct vtn_type *as_type = vtn_get_type(b, w[1]);
3052       struct vtn_type *u_type = vtn_get_value_type(b, w[3]);
3053       vtn_fail_if(!((u_type->base_type == vtn_base_type_vector &&
3054                      u_type->type == glsl_vector_type(GLSL_TYPE_UINT, 2)) ||
3055                     (u_type->base_type == vtn_base_type_scalar &&
3056                      u_type->type == glsl_uint64_t_type())),
3057                   "OpConvertUToAccelerationStructure may only be used to "
3058                   "cast from a 64-bit scalar integer or a 2-component vector "
3059                   "of 32-bit integers");
3060       vtn_fail_if(as_type->base_type != vtn_base_type_accel_struct,
3061                   "The result type of an OpConvertUToAccelerationStructure "
3062                   "must be OpTypeAccelerationStructure");
3063 
3064       nir_def *u = vtn_get_nir_ssa(b, w[3]);
3065       vtn_push_nir_ssa(b, w[2], nir_sloppy_bitcast(&b->nb, u, as_type->type));
3066       break;
3067    }
3068 
3069    default:
3070       vtn_fail_with_opcode("Unhandled opcode", opcode);
3071    }
3072 }
3073