OSDN Git Service

nir/spirv: Add support for device groups
[android-x86/external-mesa.git] / src / compiler / spirv / spirv_to_nir.c
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  * Authors:
24  *    Jason Ekstrand (jason@jlekstrand.net)
25  *
26  */
27
28 #include "vtn_private.h"
29 #include "nir/nir_vla.h"
30 #include "nir/nir_control_flow.h"
31 #include "nir/nir_constant_expressions.h"
32 #include "spirv_info.h"
33
34 #include <stdio.h>
35
36 void
37 vtn_log(struct vtn_builder *b, enum nir_spirv_debug_level level,
38         size_t spirv_offset, const char *message)
39 {
40    if (b->options->debug.func) {
41       b->options->debug.func(b->options->debug.private_data,
42                              level, spirv_offset, message);
43    }
44
45 #ifndef NDEBUG
46    if (level >= NIR_SPIRV_DEBUG_LEVEL_WARNING)
47       fprintf(stderr, "%s\n", message);
48 #endif
49 }
50
51 void
52 vtn_logf(struct vtn_builder *b, enum nir_spirv_debug_level level,
53          size_t spirv_offset, const char *fmt, ...)
54 {
55    va_list args;
56    char *msg;
57
58    va_start(args, fmt);
59    msg = ralloc_vasprintf(NULL, fmt, args);
60    va_end(args);
61
62    vtn_log(b, level, spirv_offset, msg);
63
64    ralloc_free(msg);
65 }
66
67 static void
68 vtn_log_err(struct vtn_builder *b,
69             enum nir_spirv_debug_level level, const char *prefix,
70             const char *file, unsigned line,
71             const char *fmt, va_list args)
72 {
73    char *msg;
74
75    msg = ralloc_strdup(NULL, prefix);
76
77 #ifndef NDEBUG
78    ralloc_asprintf_append(&msg, "    In file %s:%u\n", file, line);
79 #endif
80
81    ralloc_asprintf_append(&msg, "    ");
82
83    ralloc_vasprintf_append(&msg, fmt, args);
84
85    ralloc_asprintf_append(&msg, "\n    %zu bytes into the SPIR-V binary",
86                           b->spirv_offset);
87
88    if (b->file) {
89       ralloc_asprintf_append(&msg,
90                              "\n    in SPIR-V source file %s, line %d, col %d",
91                              b->file, b->line, b->col);
92    }
93
94    vtn_log(b, level, b->spirv_offset, msg);
95
96    ralloc_free(msg);
97 }
98
99 static void
100 vtn_dump_shader(struct vtn_builder *b, const char *path, const char *prefix)
101 {
102    static int idx = 0;
103
104    char filename[1024];
105    int len = snprintf(filename, sizeof(filename), "%s/%s-%d.spirv",
106                       path, prefix, idx++);
107    if (len < 0 || len >= sizeof(filename))
108       return;
109
110    FILE *f = fopen(filename, "w");
111    if (f == NULL)
112       return;
113
114    fwrite(b->spirv, sizeof(*b->spirv), b->spirv_word_count, f);
115    fclose(f);
116
117    vtn_info("SPIR-V shader dumped to %s", filename);
118 }
119
120 void
121 _vtn_warn(struct vtn_builder *b, const char *file, unsigned line,
122           const char *fmt, ...)
123 {
124    va_list args;
125
126    va_start(args, fmt);
127    vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_WARNING, "SPIR-V WARNING:\n",
128                file, line, fmt, args);
129    va_end(args);
130 }
131
132 void
133 _vtn_fail(struct vtn_builder *b, const char *file, unsigned line,
134           const char *fmt, ...)
135 {
136    va_list args;
137
138    va_start(args, fmt);
139    vtn_log_err(b, NIR_SPIRV_DEBUG_LEVEL_ERROR, "SPIR-V parsing FAILED:\n",
140                file, line, fmt, args);
141    va_end(args);
142
143    const char *dump_path = getenv("MESA_SPIRV_FAIL_DUMP_PATH");
144    if (dump_path)
145       vtn_dump_shader(b, dump_path, "fail");
146
147    longjmp(b->fail_jump, 1);
148 }
149
150 struct spec_constant_value {
151    bool is_double;
152    union {
153       uint32_t data32;
154       uint64_t data64;
155    };
156 };
157
158 static struct vtn_ssa_value *
159 vtn_undef_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
160 {
161    struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
162    val->type = type;
163
164    if (glsl_type_is_vector_or_scalar(type)) {
165       unsigned num_components = glsl_get_vector_elements(val->type);
166       unsigned bit_size = glsl_get_bit_size(val->type);
167       val->def = nir_ssa_undef(&b->nb, num_components, bit_size);
168    } else {
169       unsigned elems = glsl_get_length(val->type);
170       val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
171       if (glsl_type_is_matrix(type)) {
172          const struct glsl_type *elem_type =
173             glsl_vector_type(glsl_get_base_type(type),
174                              glsl_get_vector_elements(type));
175
176          for (unsigned i = 0; i < elems; i++)
177             val->elems[i] = vtn_undef_ssa_value(b, elem_type);
178       } else if (glsl_type_is_array(type)) {
179          const struct glsl_type *elem_type = glsl_get_array_element(type);
180          for (unsigned i = 0; i < elems; i++)
181             val->elems[i] = vtn_undef_ssa_value(b, elem_type);
182       } else {
183          for (unsigned i = 0; i < elems; i++) {
184             const struct glsl_type *elem_type = glsl_get_struct_field(type, i);
185             val->elems[i] = vtn_undef_ssa_value(b, elem_type);
186          }
187       }
188    }
189
190    return val;
191 }
192
193 static struct vtn_ssa_value *
194 vtn_const_ssa_value(struct vtn_builder *b, nir_constant *constant,
195                     const struct glsl_type *type)
196 {
197    struct hash_entry *entry = _mesa_hash_table_search(b->const_table, constant);
198
199    if (entry)
200       return entry->data;
201
202    struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
203    val->type = type;
204
205    switch (glsl_get_base_type(type)) {
206    case GLSL_TYPE_INT:
207    case GLSL_TYPE_UINT:
208    case GLSL_TYPE_INT16:
209    case GLSL_TYPE_UINT16:
210    case GLSL_TYPE_INT64:
211    case GLSL_TYPE_UINT64:
212    case GLSL_TYPE_BOOL:
213    case GLSL_TYPE_FLOAT:
214    case GLSL_TYPE_FLOAT16:
215    case GLSL_TYPE_DOUBLE: {
216       int bit_size = glsl_get_bit_size(type);
217       if (glsl_type_is_vector_or_scalar(type)) {
218          unsigned num_components = glsl_get_vector_elements(val->type);
219          nir_load_const_instr *load =
220             nir_load_const_instr_create(b->shader, num_components, bit_size);
221
222          load->value = constant->values[0];
223
224          nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
225          val->def = &load->def;
226       } else {
227          assert(glsl_type_is_matrix(type));
228          unsigned rows = glsl_get_vector_elements(val->type);
229          unsigned columns = glsl_get_matrix_columns(val->type);
230          val->elems = ralloc_array(b, struct vtn_ssa_value *, columns);
231
232          for (unsigned i = 0; i < columns; i++) {
233             struct vtn_ssa_value *col_val = rzalloc(b, struct vtn_ssa_value);
234             col_val->type = glsl_get_column_type(val->type);
235             nir_load_const_instr *load =
236                nir_load_const_instr_create(b->shader, rows, bit_size);
237
238             load->value = constant->values[i];
239
240             nir_instr_insert_before_cf_list(&b->nb.impl->body, &load->instr);
241             col_val->def = &load->def;
242
243             val->elems[i] = col_val;
244          }
245       }
246       break;
247    }
248
249    case GLSL_TYPE_ARRAY: {
250       unsigned elems = glsl_get_length(val->type);
251       val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
252       const struct glsl_type *elem_type = glsl_get_array_element(val->type);
253       for (unsigned i = 0; i < elems; i++)
254          val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
255                                              elem_type);
256       break;
257    }
258
259    case GLSL_TYPE_STRUCT: {
260       unsigned elems = glsl_get_length(val->type);
261       val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
262       for (unsigned i = 0; i < elems; i++) {
263          const struct glsl_type *elem_type =
264             glsl_get_struct_field(val->type, i);
265          val->elems[i] = vtn_const_ssa_value(b, constant->elements[i],
266                                              elem_type);
267       }
268       break;
269    }
270
271    default:
272       vtn_fail("bad constant type");
273    }
274
275    return val;
276 }
277
278 struct vtn_ssa_value *
279 vtn_ssa_value(struct vtn_builder *b, uint32_t value_id)
280 {
281    struct vtn_value *val = vtn_untyped_value(b, value_id);
282    switch (val->value_type) {
283    case vtn_value_type_undef:
284       return vtn_undef_ssa_value(b, val->type->type);
285
286    case vtn_value_type_constant:
287       return vtn_const_ssa_value(b, val->constant, val->type->type);
288
289    case vtn_value_type_ssa:
290       return val->ssa;
291
292    case vtn_value_type_pointer:
293       vtn_assert(val->pointer->ptr_type && val->pointer->ptr_type->type);
294       struct vtn_ssa_value *ssa =
295          vtn_create_ssa_value(b, val->pointer->ptr_type->type);
296       ssa->def = vtn_pointer_to_ssa(b, val->pointer);
297       return ssa;
298
299    default:
300       vtn_fail("Invalid type for an SSA value");
301    }
302 }
303
304 static char *
305 vtn_string_literal(struct vtn_builder *b, const uint32_t *words,
306                    unsigned word_count, unsigned *words_used)
307 {
308    char *dup = ralloc_strndup(b, (char *)words, word_count * sizeof(*words));
309    if (words_used) {
310       /* Ammount of space taken by the string (including the null) */
311       unsigned len = strlen(dup) + 1;
312       *words_used = DIV_ROUND_UP(len, sizeof(*words));
313    }
314    return dup;
315 }
316
317 const uint32_t *
318 vtn_foreach_instruction(struct vtn_builder *b, const uint32_t *start,
319                         const uint32_t *end, vtn_instruction_handler handler)
320 {
321    b->file = NULL;
322    b->line = -1;
323    b->col = -1;
324
325    const uint32_t *w = start;
326    while (w < end) {
327       SpvOp opcode = w[0] & SpvOpCodeMask;
328       unsigned count = w[0] >> SpvWordCountShift;
329       vtn_assert(count >= 1 && w + count <= end);
330
331       b->spirv_offset = (uint8_t *)w - (uint8_t *)b->spirv;
332
333       switch (opcode) {
334       case SpvOpNop:
335          break; /* Do nothing */
336
337       case SpvOpLine:
338          b->file = vtn_value(b, w[1], vtn_value_type_string)->str;
339          b->line = w[2];
340          b->col = w[3];
341          break;
342
343       case SpvOpNoLine:
344          b->file = NULL;
345          b->line = -1;
346          b->col = -1;
347          break;
348
349       default:
350          if (!handler(b, opcode, w, count))
351             return w;
352          break;
353       }
354
355       w += count;
356    }
357
358    b->spirv_offset = 0;
359    b->file = NULL;
360    b->line = -1;
361    b->col = -1;
362
363    assert(w == end);
364    return w;
365 }
366
367 static void
368 vtn_handle_extension(struct vtn_builder *b, SpvOp opcode,
369                      const uint32_t *w, unsigned count)
370 {
371    switch (opcode) {
372    case SpvOpExtInstImport: {
373       struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_extension);
374       if (strcmp((const char *)&w[2], "GLSL.std.450") == 0) {
375          val->ext_handler = vtn_handle_glsl450_instruction;
376       } else {
377          vtn_fail("Unsupported extension");
378       }
379       break;
380    }
381
382    case SpvOpExtInst: {
383       struct vtn_value *val = vtn_value(b, w[3], vtn_value_type_extension);
384       bool handled = val->ext_handler(b, w[4], w, count);
385       vtn_assert(handled);
386       break;
387    }
388
389    default:
390       vtn_fail("Unhandled opcode");
391    }
392 }
393
394 static void
395 _foreach_decoration_helper(struct vtn_builder *b,
396                            struct vtn_value *base_value,
397                            int parent_member,
398                            struct vtn_value *value,
399                            vtn_decoration_foreach_cb cb, void *data)
400 {
401    for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
402       int member;
403       if (dec->scope == VTN_DEC_DECORATION) {
404          member = parent_member;
405       } else if (dec->scope >= VTN_DEC_STRUCT_MEMBER0) {
406          vtn_fail_if(value->value_type != vtn_value_type_type ||
407                      value->type->base_type != vtn_base_type_struct,
408                      "OpMemberDecorate and OpGroupMemberDecorate are only "
409                      "allowed on OpTypeStruct");
410          /* This means we haven't recursed yet */
411          assert(value == base_value);
412
413          member = dec->scope - VTN_DEC_STRUCT_MEMBER0;
414
415          vtn_fail_if(member >= base_value->type->length,
416                      "OpMemberDecorate specifies member %d but the "
417                      "OpTypeStruct has only %u members",
418                      member, base_value->type->length);
419       } else {
420          /* Not a decoration */
421          assert(dec->scope == VTN_DEC_EXECUTION_MODE);
422          continue;
423       }
424
425       if (dec->group) {
426          assert(dec->group->value_type == vtn_value_type_decoration_group);
427          _foreach_decoration_helper(b, base_value, member, dec->group,
428                                     cb, data);
429       } else {
430          cb(b, base_value, member, dec, data);
431       }
432    }
433 }
434
435 /** Iterates (recursively if needed) over all of the decorations on a value
436  *
437  * This function iterates over all of the decorations applied to a given
438  * value.  If it encounters a decoration group, it recurses into the group
439  * and iterates over all of those decorations as well.
440  */
441 void
442 vtn_foreach_decoration(struct vtn_builder *b, struct vtn_value *value,
443                        vtn_decoration_foreach_cb cb, void *data)
444 {
445    _foreach_decoration_helper(b, value, -1, value, cb, data);
446 }
447
448 void
449 vtn_foreach_execution_mode(struct vtn_builder *b, struct vtn_value *value,
450                            vtn_execution_mode_foreach_cb cb, void *data)
451 {
452    for (struct vtn_decoration *dec = value->decoration; dec; dec = dec->next) {
453       if (dec->scope != VTN_DEC_EXECUTION_MODE)
454          continue;
455
456       assert(dec->group == NULL);
457       cb(b, value, dec, data);
458    }
459 }
460
461 static void
462 vtn_handle_decoration(struct vtn_builder *b, SpvOp opcode,
463                       const uint32_t *w, unsigned count)
464 {
465    const uint32_t *w_end = w + count;
466    const uint32_t target = w[1];
467    w += 2;
468
469    switch (opcode) {
470    case SpvOpDecorationGroup:
471       vtn_push_value(b, target, vtn_value_type_decoration_group);
472       break;
473
474    case SpvOpDecorate:
475    case SpvOpMemberDecorate:
476    case SpvOpExecutionMode: {
477       struct vtn_value *val = vtn_untyped_value(b, target);
478
479       struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
480       switch (opcode) {
481       case SpvOpDecorate:
482          dec->scope = VTN_DEC_DECORATION;
483          break;
484       case SpvOpMemberDecorate:
485          dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(w++);
486          vtn_fail_if(dec->scope < VTN_DEC_STRUCT_MEMBER0, /* overflow */
487                      "Member argument of OpMemberDecorate too large");
488          break;
489       case SpvOpExecutionMode:
490          dec->scope = VTN_DEC_EXECUTION_MODE;
491          break;
492       default:
493          unreachable("Invalid decoration opcode");
494       }
495       dec->decoration = *(w++);
496       dec->literals = w;
497
498       /* Link into the list */
499       dec->next = val->decoration;
500       val->decoration = dec;
501       break;
502    }
503
504    case SpvOpGroupMemberDecorate:
505    case SpvOpGroupDecorate: {
506       struct vtn_value *group =
507          vtn_value(b, target, vtn_value_type_decoration_group);
508
509       for (; w < w_end; w++) {
510          struct vtn_value *val = vtn_untyped_value(b, *w);
511          struct vtn_decoration *dec = rzalloc(b, struct vtn_decoration);
512
513          dec->group = group;
514          if (opcode == SpvOpGroupDecorate) {
515             dec->scope = VTN_DEC_DECORATION;
516          } else {
517             dec->scope = VTN_DEC_STRUCT_MEMBER0 + *(++w);
518             vtn_fail_if(dec->scope < 0, /* Check for overflow */
519                         "Member argument of OpGroupMemberDecorate too large");
520          }
521
522          /* Link into the list */
523          dec->next = val->decoration;
524          val->decoration = dec;
525       }
526       break;
527    }
528
529    default:
530       unreachable("Unhandled opcode");
531    }
532 }
533
534 struct member_decoration_ctx {
535    unsigned num_fields;
536    struct glsl_struct_field *fields;
537    struct vtn_type *type;
538 };
539
540 /** Returns true if two types are "compatible", i.e. you can do an OpLoad,
541  * OpStore, or OpCopyMemory between them without breaking anything.
542  * Technically, the SPIR-V rules require the exact same type ID but this lets
543  * us internally be a bit looser.
544  */
545 bool
546 vtn_types_compatible(struct vtn_builder *b,
547                      struct vtn_type *t1, struct vtn_type *t2)
548 {
549    if (t1->id == t2->id)
550       return true;
551
552    if (t1->base_type != t2->base_type)
553       return false;
554
555    switch (t1->base_type) {
556    case vtn_base_type_void:
557    case vtn_base_type_scalar:
558    case vtn_base_type_vector:
559    case vtn_base_type_matrix:
560    case vtn_base_type_image:
561    case vtn_base_type_sampler:
562    case vtn_base_type_sampled_image:
563       return t1->type == t2->type;
564
565    case vtn_base_type_array:
566       return t1->length == t2->length &&
567              vtn_types_compatible(b, t1->array_element, t2->array_element);
568
569    case vtn_base_type_pointer:
570       return vtn_types_compatible(b, t1->deref, t2->deref);
571
572    case vtn_base_type_struct:
573       if (t1->length != t2->length)
574          return false;
575
576       for (unsigned i = 0; i < t1->length; i++) {
577          if (!vtn_types_compatible(b, t1->members[i], t2->members[i]))
578             return false;
579       }
580       return true;
581
582    case vtn_base_type_function:
583       /* This case shouldn't get hit since you can't copy around function
584        * types.  Just require them to be identical.
585        */
586       return false;
587    }
588
589    vtn_fail("Invalid base type");
590 }
591
592 /* does a shallow copy of a vtn_type */
593
594 static struct vtn_type *
595 vtn_type_copy(struct vtn_builder *b, struct vtn_type *src)
596 {
597    struct vtn_type *dest = ralloc(b, struct vtn_type);
598    *dest = *src;
599
600    switch (src->base_type) {
601    case vtn_base_type_void:
602    case vtn_base_type_scalar:
603    case vtn_base_type_vector:
604    case vtn_base_type_matrix:
605    case vtn_base_type_array:
606    case vtn_base_type_pointer:
607    case vtn_base_type_image:
608    case vtn_base_type_sampler:
609    case vtn_base_type_sampled_image:
610       /* Nothing more to do */
611       break;
612
613    case vtn_base_type_struct:
614       dest->members = ralloc_array(b, struct vtn_type *, src->length);
615       memcpy(dest->members, src->members,
616              src->length * sizeof(src->members[0]));
617
618       dest->offsets = ralloc_array(b, unsigned, src->length);
619       memcpy(dest->offsets, src->offsets,
620              src->length * sizeof(src->offsets[0]));
621       break;
622
623    case vtn_base_type_function:
624       dest->params = ralloc_array(b, struct vtn_type *, src->length);
625       memcpy(dest->params, src->params, src->length * sizeof(src->params[0]));
626       break;
627    }
628
629    return dest;
630 }
631
632 static struct vtn_type *
633 mutable_matrix_member(struct vtn_builder *b, struct vtn_type *type, int member)
634 {
635    type->members[member] = vtn_type_copy(b, type->members[member]);
636    type = type->members[member];
637
638    /* We may have an array of matrices.... Oh, joy! */
639    while (glsl_type_is_array(type->type)) {
640       type->array_element = vtn_type_copy(b, type->array_element);
641       type = type->array_element;
642    }
643
644    vtn_assert(glsl_type_is_matrix(type->type));
645
646    return type;
647 }
648
649 static void
650 struct_member_decoration_cb(struct vtn_builder *b,
651                             struct vtn_value *val, int member,
652                             const struct vtn_decoration *dec, void *void_ctx)
653 {
654    struct member_decoration_ctx *ctx = void_ctx;
655
656    if (member < 0)
657       return;
658
659    assert(member < ctx->num_fields);
660
661    switch (dec->decoration) {
662    case SpvDecorationNonWritable:
663    case SpvDecorationNonReadable:
664    case SpvDecorationRelaxedPrecision:
665    case SpvDecorationVolatile:
666    case SpvDecorationCoherent:
667    case SpvDecorationUniform:
668       break; /* FIXME: Do nothing with this for now. */
669    case SpvDecorationNoPerspective:
670       ctx->fields[member].interpolation = INTERP_MODE_NOPERSPECTIVE;
671       break;
672    case SpvDecorationFlat:
673       ctx->fields[member].interpolation = INTERP_MODE_FLAT;
674       break;
675    case SpvDecorationCentroid:
676       ctx->fields[member].centroid = true;
677       break;
678    case SpvDecorationSample:
679       ctx->fields[member].sample = true;
680       break;
681    case SpvDecorationStream:
682       /* Vulkan only allows one GS stream */
683       vtn_assert(dec->literals[0] == 0);
684       break;
685    case SpvDecorationLocation:
686       ctx->fields[member].location = dec->literals[0];
687       break;
688    case SpvDecorationComponent:
689       break; /* FIXME: What should we do with these? */
690    case SpvDecorationBuiltIn:
691       ctx->type->members[member] = vtn_type_copy(b, ctx->type->members[member]);
692       ctx->type->members[member]->is_builtin = true;
693       ctx->type->members[member]->builtin = dec->literals[0];
694       ctx->type->builtin_block = true;
695       break;
696    case SpvDecorationOffset:
697       ctx->type->offsets[member] = dec->literals[0];
698       break;
699    case SpvDecorationMatrixStride:
700       /* Handled as a second pass */
701       break;
702    case SpvDecorationColMajor:
703       break; /* Nothing to do here.  Column-major is the default. */
704    case SpvDecorationRowMajor:
705       mutable_matrix_member(b, ctx->type, member)->row_major = true;
706       break;
707
708    case SpvDecorationPatch:
709       break;
710
711    case SpvDecorationSpecId:
712    case SpvDecorationBlock:
713    case SpvDecorationBufferBlock:
714    case SpvDecorationArrayStride:
715    case SpvDecorationGLSLShared:
716    case SpvDecorationGLSLPacked:
717    case SpvDecorationInvariant:
718    case SpvDecorationRestrict:
719    case SpvDecorationAliased:
720    case SpvDecorationConstant:
721    case SpvDecorationIndex:
722    case SpvDecorationBinding:
723    case SpvDecorationDescriptorSet:
724    case SpvDecorationLinkageAttributes:
725    case SpvDecorationNoContraction:
726    case SpvDecorationInputAttachmentIndex:
727       vtn_warn("Decoration not allowed on struct members: %s",
728                spirv_decoration_to_string(dec->decoration));
729       break;
730
731    case SpvDecorationXfbBuffer:
732    case SpvDecorationXfbStride:
733       vtn_warn("Vulkan does not have transform feedback");
734       break;
735
736    case SpvDecorationCPacked:
737    case SpvDecorationSaturatedConversion:
738    case SpvDecorationFuncParamAttr:
739    case SpvDecorationFPRoundingMode:
740    case SpvDecorationFPFastMathMode:
741    case SpvDecorationAlignment:
742       vtn_warn("Decoration only allowed for CL-style kernels: %s",
743                spirv_decoration_to_string(dec->decoration));
744       break;
745
746    default:
747       vtn_fail("Unhandled decoration");
748    }
749 }
750
751 /* Matrix strides are handled as a separate pass because we need to know
752  * whether the matrix is row-major or not first.
753  */
754 static void
755 struct_member_matrix_stride_cb(struct vtn_builder *b,
756                                struct vtn_value *val, int member,
757                                const struct vtn_decoration *dec,
758                                void *void_ctx)
759 {
760    if (dec->decoration != SpvDecorationMatrixStride)
761       return;
762
763    vtn_fail_if(member < 0,
764                "The MatrixStride decoration is only allowed on members "
765                "of OpTypeStruct");
766
767    struct member_decoration_ctx *ctx = void_ctx;
768
769    struct vtn_type *mat_type = mutable_matrix_member(b, ctx->type, member);
770    if (mat_type->row_major) {
771       mat_type->array_element = vtn_type_copy(b, mat_type->array_element);
772       mat_type->stride = mat_type->array_element->stride;
773       mat_type->array_element->stride = dec->literals[0];
774    } else {
775       vtn_assert(mat_type->array_element->stride > 0);
776       mat_type->stride = dec->literals[0];
777    }
778 }
779
780 static void
781 type_decoration_cb(struct vtn_builder *b,
782                    struct vtn_value *val, int member,
783                     const struct vtn_decoration *dec, void *ctx)
784 {
785    struct vtn_type *type = val->type;
786
787    if (member != -1) {
788       /* This should have been handled by OpTypeStruct */
789       assert(val->type->base_type == vtn_base_type_struct);
790       assert(member >= 0 && member < val->type->length);
791       return;
792    }
793
794    switch (dec->decoration) {
795    case SpvDecorationArrayStride:
796       vtn_assert(type->base_type == vtn_base_type_matrix ||
797                  type->base_type == vtn_base_type_array ||
798                  type->base_type == vtn_base_type_pointer);
799       type->stride = dec->literals[0];
800       break;
801    case SpvDecorationBlock:
802       vtn_assert(type->base_type == vtn_base_type_struct);
803       type->block = true;
804       break;
805    case SpvDecorationBufferBlock:
806       vtn_assert(type->base_type == vtn_base_type_struct);
807       type->buffer_block = true;
808       break;
809    case SpvDecorationGLSLShared:
810    case SpvDecorationGLSLPacked:
811       /* Ignore these, since we get explicit offsets anyways */
812       break;
813
814    case SpvDecorationRowMajor:
815    case SpvDecorationColMajor:
816    case SpvDecorationMatrixStride:
817    case SpvDecorationBuiltIn:
818    case SpvDecorationNoPerspective:
819    case SpvDecorationFlat:
820    case SpvDecorationPatch:
821    case SpvDecorationCentroid:
822    case SpvDecorationSample:
823    case SpvDecorationVolatile:
824    case SpvDecorationCoherent:
825    case SpvDecorationNonWritable:
826    case SpvDecorationNonReadable:
827    case SpvDecorationUniform:
828    case SpvDecorationStream:
829    case SpvDecorationLocation:
830    case SpvDecorationComponent:
831    case SpvDecorationOffset:
832    case SpvDecorationXfbBuffer:
833    case SpvDecorationXfbStride:
834       vtn_warn("Decoration only allowed for struct members: %s",
835                spirv_decoration_to_string(dec->decoration));
836       break;
837
838    case SpvDecorationRelaxedPrecision:
839    case SpvDecorationSpecId:
840    case SpvDecorationInvariant:
841    case SpvDecorationRestrict:
842    case SpvDecorationAliased:
843    case SpvDecorationConstant:
844    case SpvDecorationIndex:
845    case SpvDecorationBinding:
846    case SpvDecorationDescriptorSet:
847    case SpvDecorationLinkageAttributes:
848    case SpvDecorationNoContraction:
849    case SpvDecorationInputAttachmentIndex:
850       vtn_warn("Decoration not allowed on types: %s",
851                spirv_decoration_to_string(dec->decoration));
852       break;
853
854    case SpvDecorationCPacked:
855    case SpvDecorationSaturatedConversion:
856    case SpvDecorationFuncParamAttr:
857    case SpvDecorationFPRoundingMode:
858    case SpvDecorationFPFastMathMode:
859    case SpvDecorationAlignment:
860       vtn_warn("Decoration only allowed for CL-style kernels: %s",
861                spirv_decoration_to_string(dec->decoration));
862       break;
863
864    default:
865       vtn_fail("Unhandled decoration");
866    }
867 }
868
869 static unsigned
870 translate_image_format(struct vtn_builder *b, SpvImageFormat format)
871 {
872    switch (format) {
873    case SpvImageFormatUnknown:      return 0;      /* GL_NONE */
874    case SpvImageFormatRgba32f:      return 0x8814; /* GL_RGBA32F */
875    case SpvImageFormatRgba16f:      return 0x881A; /* GL_RGBA16F */
876    case SpvImageFormatR32f:         return 0x822E; /* GL_R32F */
877    case SpvImageFormatRgba8:        return 0x8058; /* GL_RGBA8 */
878    case SpvImageFormatRgba8Snorm:   return 0x8F97; /* GL_RGBA8_SNORM */
879    case SpvImageFormatRg32f:        return 0x8230; /* GL_RG32F */
880    case SpvImageFormatRg16f:        return 0x822F; /* GL_RG16F */
881    case SpvImageFormatR11fG11fB10f: return 0x8C3A; /* GL_R11F_G11F_B10F */
882    case SpvImageFormatR16f:         return 0x822D; /* GL_R16F */
883    case SpvImageFormatRgba16:       return 0x805B; /* GL_RGBA16 */
884    case SpvImageFormatRgb10A2:      return 0x8059; /* GL_RGB10_A2 */
885    case SpvImageFormatRg16:         return 0x822C; /* GL_RG16 */
886    case SpvImageFormatRg8:          return 0x822B; /* GL_RG8 */
887    case SpvImageFormatR16:          return 0x822A; /* GL_R16 */
888    case SpvImageFormatR8:           return 0x8229; /* GL_R8 */
889    case SpvImageFormatRgba16Snorm:  return 0x8F9B; /* GL_RGBA16_SNORM */
890    case SpvImageFormatRg16Snorm:    return 0x8F99; /* GL_RG16_SNORM */
891    case SpvImageFormatRg8Snorm:     return 0x8F95; /* GL_RG8_SNORM */
892    case SpvImageFormatR16Snorm:     return 0x8F98; /* GL_R16_SNORM */
893    case SpvImageFormatR8Snorm:      return 0x8F94; /* GL_R8_SNORM */
894    case SpvImageFormatRgba32i:      return 0x8D82; /* GL_RGBA32I */
895    case SpvImageFormatRgba16i:      return 0x8D88; /* GL_RGBA16I */
896    case SpvImageFormatRgba8i:       return 0x8D8E; /* GL_RGBA8I */
897    case SpvImageFormatR32i:         return 0x8235; /* GL_R32I */
898    case SpvImageFormatRg32i:        return 0x823B; /* GL_RG32I */
899    case SpvImageFormatRg16i:        return 0x8239; /* GL_RG16I */
900    case SpvImageFormatRg8i:         return 0x8237; /* GL_RG8I */
901    case SpvImageFormatR16i:         return 0x8233; /* GL_R16I */
902    case SpvImageFormatR8i:          return 0x8231; /* GL_R8I */
903    case SpvImageFormatRgba32ui:     return 0x8D70; /* GL_RGBA32UI */
904    case SpvImageFormatRgba16ui:     return 0x8D76; /* GL_RGBA16UI */
905    case SpvImageFormatRgba8ui:      return 0x8D7C; /* GL_RGBA8UI */
906    case SpvImageFormatR32ui:        return 0x8236; /* GL_R32UI */
907    case SpvImageFormatRgb10a2ui:    return 0x906F; /* GL_RGB10_A2UI */
908    case SpvImageFormatRg32ui:       return 0x823C; /* GL_RG32UI */
909    case SpvImageFormatRg16ui:       return 0x823A; /* GL_RG16UI */
910    case SpvImageFormatRg8ui:        return 0x8238; /* GL_RG8UI */
911    case SpvImageFormatR16ui:        return 0x8234; /* GL_R16UI */
912    case SpvImageFormatR8ui:         return 0x8232; /* GL_R8UI */
913    default:
914       vtn_fail("Invalid image format");
915    }
916 }
917
918 static struct vtn_type *
919 vtn_type_layout_std430(struct vtn_builder *b, struct vtn_type *type,
920                        uint32_t *size_out, uint32_t *align_out)
921 {
922    switch (type->base_type) {
923    case vtn_base_type_scalar: {
924       uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
925       *size_out = comp_size;
926       *align_out = comp_size;
927       return type;
928    }
929
930    case vtn_base_type_vector: {
931       uint32_t comp_size = glsl_get_bit_size(type->type) / 8;
932       assert(type->length > 0 && type->length <= 4);
933       unsigned align_comps = type->length == 3 ? 4 : type->length;
934       *size_out = comp_size * type->length,
935       *align_out = comp_size * align_comps;
936       return type;
937    }
938
939    case vtn_base_type_matrix:
940    case vtn_base_type_array: {
941       /* We're going to add an array stride */
942       type = vtn_type_copy(b, type);
943       uint32_t elem_size, elem_align;
944       type->array_element = vtn_type_layout_std430(b, type->array_element,
945                                                    &elem_size, &elem_align);
946       type->stride = vtn_align_u32(elem_size, elem_align);
947       *size_out = type->stride * type->length;
948       *align_out = elem_align;
949       return type;
950    }
951
952    case vtn_base_type_struct: {
953       /* We're going to add member offsets */
954       type = vtn_type_copy(b, type);
955       uint32_t offset = 0;
956       uint32_t align = 0;
957       for (unsigned i = 0; i < type->length; i++) {
958          uint32_t mem_size, mem_align;
959          type->members[i] = vtn_type_layout_std430(b, type->members[i],
960                                                    &mem_size, &mem_align);
961          offset = vtn_align_u32(offset, mem_align);
962          type->offsets[i] = offset;
963          offset += mem_size;
964          align = MAX2(align, mem_align);
965       }
966       *size_out = offset;
967       *align_out = align;
968       return type;
969    }
970
971    default:
972       unreachable("Invalid SPIR-V type for std430");
973    }
974 }
975
976 static void
977 vtn_handle_type(struct vtn_builder *b, SpvOp opcode,
978                 const uint32_t *w, unsigned count)
979 {
980    struct vtn_value *val = vtn_push_value(b, w[1], vtn_value_type_type);
981
982    val->type = rzalloc(b, struct vtn_type);
983    val->type->id = w[1];
984
985    switch (opcode) {
986    case SpvOpTypeVoid:
987       val->type->base_type = vtn_base_type_void;
988       val->type->type = glsl_void_type();
989       break;
990    case SpvOpTypeBool:
991       val->type->base_type = vtn_base_type_scalar;
992       val->type->type = glsl_bool_type();
993       val->type->length = 1;
994       break;
995    case SpvOpTypeInt: {
996       int bit_size = w[2];
997       const bool signedness = w[3];
998       val->type->base_type = vtn_base_type_scalar;
999       switch (bit_size) {
1000       case 64:
1001          val->type->type = (signedness ? glsl_int64_t_type() : glsl_uint64_t_type());
1002          break;
1003       case 32:
1004          val->type->type = (signedness ? glsl_int_type() : glsl_uint_type());
1005          break;
1006       case 16:
1007          val->type->type = (signedness ? glsl_int16_t_type() : glsl_uint16_t_type());
1008          break;
1009       default:
1010          vtn_fail("Invalid int bit size");
1011       }
1012       val->type->length = 1;
1013       break;
1014    }
1015
1016    case SpvOpTypeFloat: {
1017       int bit_size = w[2];
1018       val->type->base_type = vtn_base_type_scalar;
1019       switch (bit_size) {
1020       case 16:
1021          val->type->type = glsl_float16_t_type();
1022          break;
1023       case 32:
1024          val->type->type = glsl_float_type();
1025          break;
1026       case 64:
1027          val->type->type = glsl_double_type();
1028          break;
1029       default:
1030          vtn_fail("Invalid float bit size");
1031       }
1032       val->type->length = 1;
1033       break;
1034    }
1035
1036    case SpvOpTypeVector: {
1037       struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1038       unsigned elems = w[3];
1039
1040       vtn_fail_if(base->base_type != vtn_base_type_scalar,
1041                   "Base type for OpTypeVector must be a scalar");
1042       vtn_fail_if(elems < 2 || elems > 4,
1043                   "Invalid component count for OpTypeVector");
1044
1045       val->type->base_type = vtn_base_type_vector;
1046       val->type->type = glsl_vector_type(glsl_get_base_type(base->type), elems);
1047       val->type->length = elems;
1048       val->type->stride = glsl_get_bit_size(base->type) / 8;
1049       val->type->array_element = base;
1050       break;
1051    }
1052
1053    case SpvOpTypeMatrix: {
1054       struct vtn_type *base = vtn_value(b, w[2], vtn_value_type_type)->type;
1055       unsigned columns = w[3];
1056
1057       vtn_fail_if(base->base_type != vtn_base_type_vector,
1058                   "Base type for OpTypeMatrix must be a vector");
1059       vtn_fail_if(columns < 2 || columns > 4,
1060                   "Invalid column count for OpTypeMatrix");
1061
1062       val->type->base_type = vtn_base_type_matrix;
1063       val->type->type = glsl_matrix_type(glsl_get_base_type(base->type),
1064                                          glsl_get_vector_elements(base->type),
1065                                          columns);
1066       vtn_fail_if(glsl_type_is_error(val->type->type),
1067                   "Unsupported base type for OpTypeMatrix");
1068       assert(!glsl_type_is_error(val->type->type));
1069       val->type->length = columns;
1070       val->type->array_element = base;
1071       val->type->row_major = false;
1072       val->type->stride = 0;
1073       break;
1074    }
1075
1076    case SpvOpTypeRuntimeArray:
1077    case SpvOpTypeArray: {
1078       struct vtn_type *array_element =
1079          vtn_value(b, w[2], vtn_value_type_type)->type;
1080
1081       if (opcode == SpvOpTypeRuntimeArray) {
1082          /* A length of 0 is used to denote unsized arrays */
1083          val->type->length = 0;
1084       } else {
1085          val->type->length =
1086             vtn_value(b, w[3], vtn_value_type_constant)->constant->values[0].u32[0];
1087       }
1088
1089       val->type->base_type = vtn_base_type_array;
1090       val->type->type = glsl_array_type(array_element->type, val->type->length);
1091       val->type->array_element = array_element;
1092       val->type->stride = 0;
1093       break;
1094    }
1095
1096    case SpvOpTypeStruct: {
1097       unsigned num_fields = count - 2;
1098       val->type->base_type = vtn_base_type_struct;
1099       val->type->length = num_fields;
1100       val->type->members = ralloc_array(b, struct vtn_type *, num_fields);
1101       val->type->offsets = ralloc_array(b, unsigned, num_fields);
1102
1103       NIR_VLA(struct glsl_struct_field, fields, count);
1104       for (unsigned i = 0; i < num_fields; i++) {
1105          val->type->members[i] =
1106             vtn_value(b, w[i + 2], vtn_value_type_type)->type;
1107          fields[i] = (struct glsl_struct_field) {
1108             .type = val->type->members[i]->type,
1109             .name = ralloc_asprintf(b, "field%d", i),
1110             .location = -1,
1111          };
1112       }
1113
1114       struct member_decoration_ctx ctx = {
1115          .num_fields = num_fields,
1116          .fields = fields,
1117          .type = val->type
1118       };
1119
1120       vtn_foreach_decoration(b, val, struct_member_decoration_cb, &ctx);
1121       vtn_foreach_decoration(b, val, struct_member_matrix_stride_cb, &ctx);
1122
1123       const char *name = val->name ? val->name : "struct";
1124
1125       val->type->type = glsl_struct_type(fields, num_fields, name);
1126       break;
1127    }
1128
1129    case SpvOpTypeFunction: {
1130       val->type->base_type = vtn_base_type_function;
1131       val->type->type = NULL;
1132
1133       val->type->return_type = vtn_value(b, w[2], vtn_value_type_type)->type;
1134
1135       const unsigned num_params = count - 3;
1136       val->type->length = num_params;
1137       val->type->params = ralloc_array(b, struct vtn_type *, num_params);
1138       for (unsigned i = 0; i < count - 3; i++) {
1139          val->type->params[i] =
1140             vtn_value(b, w[i + 3], vtn_value_type_type)->type;
1141       }
1142       break;
1143    }
1144
1145    case SpvOpTypePointer: {
1146       SpvStorageClass storage_class = w[2];
1147       struct vtn_type *deref_type =
1148          vtn_value(b, w[3], vtn_value_type_type)->type;
1149
1150       val->type->base_type = vtn_base_type_pointer;
1151       val->type->storage_class = storage_class;
1152       val->type->deref = deref_type;
1153
1154       if (storage_class == SpvStorageClassUniform ||
1155           storage_class == SpvStorageClassStorageBuffer) {
1156          /* These can actually be stored to nir_variables and used as SSA
1157           * values so they need a real glsl_type.
1158           */
1159          val->type->type = glsl_vector_type(GLSL_TYPE_UINT, 2);
1160       }
1161
1162       if (storage_class == SpvStorageClassWorkgroup &&
1163           b->options->lower_workgroup_access_to_offsets) {
1164          uint32_t size, align;
1165          val->type->deref = vtn_type_layout_std430(b, val->type->deref,
1166                                                    &size, &align);
1167          val->type->length = size;
1168          val->type->align = align;
1169          /* These can actually be stored to nir_variables and used as SSA
1170           * values so they need a real glsl_type.
1171           */
1172          val->type->type = glsl_uint_type();
1173       }
1174       break;
1175    }
1176
1177    case SpvOpTypeImage: {
1178       val->type->base_type = vtn_base_type_image;
1179
1180       const struct vtn_type *sampled_type =
1181          vtn_value(b, w[2], vtn_value_type_type)->type;
1182
1183       vtn_fail_if(sampled_type->base_type != vtn_base_type_scalar ||
1184                   glsl_get_bit_size(sampled_type->type) != 32,
1185                   "Sampled type of OpTypeImage must be a 32-bit scalar");
1186
1187       enum glsl_sampler_dim dim;
1188       switch ((SpvDim)w[3]) {
1189       case SpvDim1D:       dim = GLSL_SAMPLER_DIM_1D;    break;
1190       case SpvDim2D:       dim = GLSL_SAMPLER_DIM_2D;    break;
1191       case SpvDim3D:       dim = GLSL_SAMPLER_DIM_3D;    break;
1192       case SpvDimCube:     dim = GLSL_SAMPLER_DIM_CUBE;  break;
1193       case SpvDimRect:     dim = GLSL_SAMPLER_DIM_RECT;  break;
1194       case SpvDimBuffer:   dim = GLSL_SAMPLER_DIM_BUF;   break;
1195       case SpvDimSubpassData: dim = GLSL_SAMPLER_DIM_SUBPASS; break;
1196       default:
1197          vtn_fail("Invalid SPIR-V image dimensionality");
1198       }
1199
1200       bool is_shadow = w[4];
1201       bool is_array = w[5];
1202       bool multisampled = w[6];
1203       unsigned sampled = w[7];
1204       SpvImageFormat format = w[8];
1205
1206       if (count > 9)
1207          val->type->access_qualifier = w[9];
1208       else
1209          val->type->access_qualifier = SpvAccessQualifierReadWrite;
1210
1211       if (multisampled) {
1212          if (dim == GLSL_SAMPLER_DIM_2D)
1213             dim = GLSL_SAMPLER_DIM_MS;
1214          else if (dim == GLSL_SAMPLER_DIM_SUBPASS)
1215             dim = GLSL_SAMPLER_DIM_SUBPASS_MS;
1216          else
1217             vtn_fail("Unsupported multisampled image type");
1218       }
1219
1220       val->type->image_format = translate_image_format(b, format);
1221
1222       enum glsl_base_type sampled_base_type =
1223          glsl_get_base_type(sampled_type->type);
1224       if (sampled == 1) {
1225          val->type->sampled = true;
1226          val->type->type = glsl_sampler_type(dim, is_shadow, is_array,
1227                                              sampled_base_type);
1228       } else if (sampled == 2) {
1229          vtn_assert(!is_shadow);
1230          val->type->sampled = false;
1231          val->type->type = glsl_image_type(dim, is_array, sampled_base_type);
1232       } else {
1233          vtn_fail("We need to know if the image will be sampled");
1234       }
1235       break;
1236    }
1237
1238    case SpvOpTypeSampledImage:
1239       val->type->base_type = vtn_base_type_sampled_image;
1240       val->type->image = vtn_value(b, w[2], vtn_value_type_type)->type;
1241       val->type->type = val->type->image->type;
1242       break;
1243
1244    case SpvOpTypeSampler:
1245       /* The actual sampler type here doesn't really matter.  It gets
1246        * thrown away the moment you combine it with an image.  What really
1247        * matters is that it's a sampler type as opposed to an integer type
1248        * so the backend knows what to do.
1249        */
1250       val->type->base_type = vtn_base_type_sampler;
1251       val->type->type = glsl_bare_sampler_type();
1252       break;
1253
1254    case SpvOpTypeOpaque:
1255    case SpvOpTypeEvent:
1256    case SpvOpTypeDeviceEvent:
1257    case SpvOpTypeReserveId:
1258    case SpvOpTypeQueue:
1259    case SpvOpTypePipe:
1260    default:
1261       vtn_fail("Unhandled opcode");
1262    }
1263
1264    vtn_foreach_decoration(b, val, type_decoration_cb, NULL);
1265 }
1266
1267 static nir_constant *
1268 vtn_null_constant(struct vtn_builder *b, const struct glsl_type *type)
1269 {
1270    nir_constant *c = rzalloc(b, nir_constant);
1271
1272    /* For pointers and other typeless things, we have to return something but
1273     * it doesn't matter what.
1274     */
1275    if (!type)
1276       return c;
1277
1278    switch (glsl_get_base_type(type)) {
1279    case GLSL_TYPE_INT:
1280    case GLSL_TYPE_UINT:
1281    case GLSL_TYPE_INT16:
1282    case GLSL_TYPE_UINT16:
1283    case GLSL_TYPE_INT64:
1284    case GLSL_TYPE_UINT64:
1285    case GLSL_TYPE_BOOL:
1286    case GLSL_TYPE_FLOAT:
1287    case GLSL_TYPE_FLOAT16:
1288    case GLSL_TYPE_DOUBLE:
1289       /* Nothing to do here.  It's already initialized to zero */
1290       break;
1291
1292    case GLSL_TYPE_ARRAY:
1293       vtn_assert(glsl_get_length(type) > 0);
1294       c->num_elements = glsl_get_length(type);
1295       c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1296
1297       c->elements[0] = vtn_null_constant(b, glsl_get_array_element(type));
1298       for (unsigned i = 1; i < c->num_elements; i++)
1299          c->elements[i] = c->elements[0];
1300       break;
1301
1302    case GLSL_TYPE_STRUCT:
1303       c->num_elements = glsl_get_length(type);
1304       c->elements = ralloc_array(b, nir_constant *, c->num_elements);
1305
1306       for (unsigned i = 0; i < c->num_elements; i++) {
1307          c->elements[i] = vtn_null_constant(b, glsl_get_struct_field(type, i));
1308       }
1309       break;
1310
1311    default:
1312       vtn_fail("Invalid type for null constant");
1313    }
1314
1315    return c;
1316 }
1317
1318 static void
1319 spec_constant_decoration_cb(struct vtn_builder *b, struct vtn_value *v,
1320                              int member, const struct vtn_decoration *dec,
1321                              void *data)
1322 {
1323    vtn_assert(member == -1);
1324    if (dec->decoration != SpvDecorationSpecId)
1325       return;
1326
1327    struct spec_constant_value *const_value = data;
1328
1329    for (unsigned i = 0; i < b->num_specializations; i++) {
1330       if (b->specializations[i].id == dec->literals[0]) {
1331          if (const_value->is_double)
1332             const_value->data64 = b->specializations[i].data64;
1333          else
1334             const_value->data32 = b->specializations[i].data32;
1335          return;
1336       }
1337    }
1338 }
1339
1340 static uint32_t
1341 get_specialization(struct vtn_builder *b, struct vtn_value *val,
1342                    uint32_t const_value)
1343 {
1344    struct spec_constant_value data;
1345    data.is_double = false;
1346    data.data32 = const_value;
1347    vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1348    return data.data32;
1349 }
1350
1351 static uint64_t
1352 get_specialization64(struct vtn_builder *b, struct vtn_value *val,
1353                    uint64_t const_value)
1354 {
1355    struct spec_constant_value data;
1356    data.is_double = true;
1357    data.data64 = const_value;
1358    vtn_foreach_decoration(b, val, spec_constant_decoration_cb, &data);
1359    return data.data64;
1360 }
1361
1362 static void
1363 handle_workgroup_size_decoration_cb(struct vtn_builder *b,
1364                                     struct vtn_value *val,
1365                                     int member,
1366                                     const struct vtn_decoration *dec,
1367                                     void *data)
1368 {
1369    vtn_assert(member == -1);
1370    if (dec->decoration != SpvDecorationBuiltIn ||
1371        dec->literals[0] != SpvBuiltInWorkgroupSize)
1372       return;
1373
1374    vtn_assert(val->type->type == glsl_vector_type(GLSL_TYPE_UINT, 3));
1375
1376    b->shader->info.cs.local_size[0] = val->constant->values[0].u32[0];
1377    b->shader->info.cs.local_size[1] = val->constant->values[0].u32[1];
1378    b->shader->info.cs.local_size[2] = val->constant->values[0].u32[2];
1379 }
1380
1381 static void
1382 vtn_handle_constant(struct vtn_builder *b, SpvOp opcode,
1383                     const uint32_t *w, unsigned count)
1384 {
1385    struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_constant);
1386    val->constant = rzalloc(b, nir_constant);
1387    switch (opcode) {
1388    case SpvOpConstantTrue:
1389    case SpvOpConstantFalse:
1390    case SpvOpSpecConstantTrue:
1391    case SpvOpSpecConstantFalse: {
1392       vtn_fail_if(val->type->type != glsl_bool_type(),
1393                   "Result type of %s must be OpTypeBool",
1394                   spirv_op_to_string(opcode));
1395
1396       uint32_t int_val = (opcode == SpvOpConstantTrue ||
1397                           opcode == SpvOpSpecConstantTrue);
1398
1399       if (opcode == SpvOpSpecConstantTrue ||
1400           opcode == SpvOpSpecConstantFalse)
1401          int_val = get_specialization(b, val, int_val);
1402
1403       val->constant->values[0].u32[0] = int_val ? NIR_TRUE : NIR_FALSE;
1404       break;
1405    }
1406
1407    case SpvOpConstant: {
1408       vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1409                   "Result type of %s must be a scalar",
1410                   spirv_op_to_string(opcode));
1411       int bit_size = glsl_get_bit_size(val->type->type);
1412       switch (bit_size) {
1413       case 64:
1414          val->constant->values->u64[0] = vtn_u64_literal(&w[3]);
1415          break;
1416       case 32:
1417          val->constant->values->u32[0] = w[3];
1418          break;
1419       case 16:
1420          val->constant->values->u16[0] = w[3];
1421          break;
1422       default:
1423          vtn_fail("Unsupported SpvOpConstant bit size");
1424       }
1425       break;
1426    }
1427
1428    case SpvOpSpecConstant: {
1429       vtn_fail_if(val->type->base_type != vtn_base_type_scalar,
1430                   "Result type of %s must be a scalar",
1431                   spirv_op_to_string(opcode));
1432       int bit_size = glsl_get_bit_size(val->type->type);
1433       switch (bit_size) {
1434       case 64:
1435          val->constant->values[0].u64[0] =
1436             get_specialization64(b, val, vtn_u64_literal(&w[3]));
1437          break;
1438       case 32:
1439          val->constant->values[0].u32[0] = get_specialization(b, val, w[3]);
1440          break;
1441       case 16:
1442          val->constant->values[0].u16[0] = get_specialization(b, val, w[3]);
1443          break;
1444       default:
1445          vtn_fail("Unsupported SpvOpSpecConstant bit size");
1446       }
1447       break;
1448    }
1449
1450    case SpvOpSpecConstantComposite:
1451    case SpvOpConstantComposite: {
1452       unsigned elem_count = count - 3;
1453       vtn_fail_if(elem_count != val->type->length,
1454                   "%s has %u constituents, expected %u",
1455                   spirv_op_to_string(opcode), elem_count, val->type->length);
1456
1457       nir_constant **elems = ralloc_array(b, nir_constant *, elem_count);
1458       for (unsigned i = 0; i < elem_count; i++)
1459          elems[i] = vtn_value(b, w[i + 3], vtn_value_type_constant)->constant;
1460
1461       switch (val->type->base_type) {
1462       case vtn_base_type_vector: {
1463          assert(glsl_type_is_vector(val->type->type));
1464          int bit_size = glsl_get_bit_size(val->type->type);
1465          for (unsigned i = 0; i < elem_count; i++) {
1466             switch (bit_size) {
1467             case 64:
1468                val->constant->values[0].u64[i] = elems[i]->values[0].u64[0];
1469                break;
1470             case 32:
1471                val->constant->values[0].u32[i] = elems[i]->values[0].u32[0];
1472                break;
1473             case 16:
1474                val->constant->values[0].u16[i] = elems[i]->values[0].u16[0];
1475                break;
1476             default:
1477                vtn_fail("Invalid SpvOpConstantComposite bit size");
1478             }
1479          }
1480          break;
1481       }
1482
1483       case vtn_base_type_matrix:
1484          assert(glsl_type_is_matrix(val->type->type));
1485          for (unsigned i = 0; i < elem_count; i++)
1486             val->constant->values[i] = elems[i]->values[0];
1487          break;
1488
1489       case vtn_base_type_struct:
1490       case vtn_base_type_array:
1491          ralloc_steal(val->constant, elems);
1492          val->constant->num_elements = elem_count;
1493          val->constant->elements = elems;
1494          break;
1495
1496       default:
1497          vtn_fail("Result type of %s must be a composite type",
1498                   spirv_op_to_string(opcode));
1499       }
1500       break;
1501    }
1502
1503    case SpvOpSpecConstantOp: {
1504       SpvOp opcode = get_specialization(b, val, w[3]);
1505       switch (opcode) {
1506       case SpvOpVectorShuffle: {
1507          struct vtn_value *v0 = &b->values[w[4]];
1508          struct vtn_value *v1 = &b->values[w[5]];
1509
1510          vtn_assert(v0->value_type == vtn_value_type_constant ||
1511                     v0->value_type == vtn_value_type_undef);
1512          vtn_assert(v1->value_type == vtn_value_type_constant ||
1513                     v1->value_type == vtn_value_type_undef);
1514
1515          unsigned len0 = glsl_get_vector_elements(v0->type->type);
1516          unsigned len1 = glsl_get_vector_elements(v1->type->type);
1517
1518          vtn_assert(len0 + len1 < 16);
1519
1520          unsigned bit_size = glsl_get_bit_size(val->type->type);
1521          unsigned bit_size0 = glsl_get_bit_size(v0->type->type);
1522          unsigned bit_size1 = glsl_get_bit_size(v1->type->type);
1523
1524          vtn_assert(bit_size == bit_size0 && bit_size == bit_size1);
1525          (void)bit_size0; (void)bit_size1;
1526
1527          if (bit_size == 64) {
1528             uint64_t u64[8];
1529             if (v0->value_type == vtn_value_type_constant) {
1530                for (unsigned i = 0; i < len0; i++)
1531                   u64[i] = v0->constant->values[0].u64[i];
1532             }
1533             if (v1->value_type == vtn_value_type_constant) {
1534                for (unsigned i = 0; i < len1; i++)
1535                   u64[len0 + i] = v1->constant->values[0].u64[i];
1536             }
1537
1538             for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1539                uint32_t comp = w[i + 6];
1540                /* If component is not used, set the value to a known constant
1541                 * to detect if it is wrongly used.
1542                 */
1543                if (comp == (uint32_t)-1)
1544                   val->constant->values[0].u64[j] = 0xdeadbeefdeadbeef;
1545                else
1546                   val->constant->values[0].u64[j] = u64[comp];
1547             }
1548          } else {
1549             /* This is for both 32-bit and 16-bit values */
1550             uint32_t u32[8];
1551             if (v0->value_type == vtn_value_type_constant) {
1552                for (unsigned i = 0; i < len0; i++)
1553                   u32[i] = v0->constant->values[0].u32[i];
1554             }
1555             if (v1->value_type == vtn_value_type_constant) {
1556                for (unsigned i = 0; i < len1; i++)
1557                   u32[len0 + i] = v1->constant->values[0].u32[i];
1558             }
1559
1560             for (unsigned i = 0, j = 0; i < count - 6; i++, j++) {
1561                uint32_t comp = w[i + 6];
1562                /* If component is not used, set the value to a known constant
1563                 * to detect if it is wrongly used.
1564                 */
1565                if (comp == (uint32_t)-1)
1566                   val->constant->values[0].u32[j] = 0xdeadbeef;
1567                else
1568                   val->constant->values[0].u32[j] = u32[comp];
1569             }
1570          }
1571          break;
1572       }
1573
1574       case SpvOpCompositeExtract:
1575       case SpvOpCompositeInsert: {
1576          struct vtn_value *comp;
1577          unsigned deref_start;
1578          struct nir_constant **c;
1579          if (opcode == SpvOpCompositeExtract) {
1580             comp = vtn_value(b, w[4], vtn_value_type_constant);
1581             deref_start = 5;
1582             c = &comp->constant;
1583          } else {
1584             comp = vtn_value(b, w[5], vtn_value_type_constant);
1585             deref_start = 6;
1586             val->constant = nir_constant_clone(comp->constant,
1587                                                (nir_variable *)b);
1588             c = &val->constant;
1589          }
1590
1591          int elem = -1;
1592          int col = 0;
1593          const struct vtn_type *type = comp->type;
1594          for (unsigned i = deref_start; i < count; i++) {
1595             vtn_fail_if(w[i] > type->length,
1596                         "%uth index of %s is %u but the type has only "
1597                         "%u elements", i - deref_start,
1598                         spirv_op_to_string(opcode), w[i], type->length);
1599
1600             switch (type->base_type) {
1601             case vtn_base_type_vector:
1602                elem = w[i];
1603                type = type->array_element;
1604                break;
1605
1606             case vtn_base_type_matrix:
1607                assert(col == 0 && elem == -1);
1608                col = w[i];
1609                elem = 0;
1610                type = type->array_element;
1611                break;
1612
1613             case vtn_base_type_array:
1614                c = &(*c)->elements[w[i]];
1615                type = type->array_element;
1616                break;
1617
1618             case vtn_base_type_struct:
1619                c = &(*c)->elements[w[i]];
1620                type = type->members[w[i]];
1621                break;
1622
1623             default:
1624                vtn_fail("%s must only index into composite types",
1625                         spirv_op_to_string(opcode));
1626             }
1627          }
1628
1629          if (opcode == SpvOpCompositeExtract) {
1630             if (elem == -1) {
1631                val->constant = *c;
1632             } else {
1633                unsigned num_components = type->length;
1634                unsigned bit_size = glsl_get_bit_size(type->type);
1635                for (unsigned i = 0; i < num_components; i++)
1636                   switch(bit_size) {
1637                   case 64:
1638                      val->constant->values[0].u64[i] = (*c)->values[col].u64[elem + i];
1639                      break;
1640                   case 32:
1641                      val->constant->values[0].u32[i] = (*c)->values[col].u32[elem + i];
1642                      break;
1643                   case 16:
1644                      val->constant->values[0].u16[i] = (*c)->values[col].u16[elem + i];
1645                      break;
1646                   default:
1647                      vtn_fail("Invalid SpvOpCompositeExtract bit size");
1648                   }
1649             }
1650          } else {
1651             struct vtn_value *insert =
1652                vtn_value(b, w[4], vtn_value_type_constant);
1653             vtn_assert(insert->type == type);
1654             if (elem == -1) {
1655                *c = insert->constant;
1656             } else {
1657                unsigned num_components = type->length;
1658                unsigned bit_size = glsl_get_bit_size(type->type);
1659                for (unsigned i = 0; i < num_components; i++)
1660                   switch (bit_size) {
1661                   case 64:
1662                      (*c)->values[col].u64[elem + i] = insert->constant->values[0].u64[i];
1663                      break;
1664                   case 32:
1665                      (*c)->values[col].u32[elem + i] = insert->constant->values[0].u32[i];
1666                      break;
1667                   case 16:
1668                      (*c)->values[col].u16[elem + i] = insert->constant->values[0].u16[i];
1669                      break;
1670                   default:
1671                      vtn_fail("Invalid SpvOpCompositeInsert bit size");
1672                   }
1673             }
1674          }
1675          break;
1676       }
1677
1678       default: {
1679          bool swap;
1680          nir_alu_type dst_alu_type = nir_get_nir_type_for_glsl_type(val->type->type);
1681          nir_alu_type src_alu_type = dst_alu_type;
1682          unsigned num_components = glsl_get_vector_elements(val->type->type);
1683          unsigned bit_size;
1684
1685          vtn_assert(count <= 7);
1686
1687          switch (opcode) {
1688          case SpvOpSConvert:
1689          case SpvOpFConvert:
1690             /* We have a source in a conversion */
1691             src_alu_type =
1692                nir_get_nir_type_for_glsl_type(
1693                   vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1694             /* We use the bitsize of the conversion source to evaluate the opcode later */
1695             bit_size = glsl_get_bit_size(
1696                vtn_value(b, w[4], vtn_value_type_constant)->type->type);
1697             break;
1698          default:
1699             bit_size = glsl_get_bit_size(val->type->type);
1700          };
1701
1702          nir_op op = vtn_nir_alu_op_for_spirv_opcode(b, opcode, &swap,
1703                                                      src_alu_type,
1704                                                      dst_alu_type);
1705          nir_const_value src[4];
1706
1707          for (unsigned i = 0; i < count - 4; i++) {
1708             nir_constant *c =
1709                vtn_value(b, w[4 + i], vtn_value_type_constant)->constant;
1710
1711             unsigned j = swap ? 1 - i : i;
1712             src[j] = c->values[0];
1713          }
1714
1715          val->constant->values[0] =
1716             nir_eval_const_opcode(op, num_components, bit_size, src);
1717          break;
1718       } /* default */
1719       }
1720       break;
1721    }
1722
1723    case SpvOpConstantNull:
1724       val->constant = vtn_null_constant(b, val->type->type);
1725       break;
1726
1727    case SpvOpConstantSampler:
1728       vtn_fail("OpConstantSampler requires Kernel Capability");
1729       break;
1730
1731    default:
1732       vtn_fail("Unhandled opcode");
1733    }
1734
1735    /* Now that we have the value, update the workgroup size if needed */
1736    vtn_foreach_decoration(b, val, handle_workgroup_size_decoration_cb, NULL);
1737 }
1738
1739 static void
1740 vtn_handle_function_call(struct vtn_builder *b, SpvOp opcode,
1741                          const uint32_t *w, unsigned count)
1742 {
1743    struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1744    struct vtn_function *vtn_callee =
1745       vtn_value(b, w[3], vtn_value_type_function)->func;
1746    struct nir_function *callee = vtn_callee->impl->function;
1747
1748    vtn_callee->referenced = true;
1749
1750    nir_call_instr *call = nir_call_instr_create(b->nb.shader, callee);
1751    for (unsigned i = 0; i < call->num_params; i++) {
1752       unsigned arg_id = w[4 + i];
1753       struct vtn_value *arg = vtn_untyped_value(b, arg_id);
1754       if (arg->value_type == vtn_value_type_pointer &&
1755           arg->pointer->ptr_type->type == NULL) {
1756          nir_deref_var *d = vtn_pointer_to_deref(b, arg->pointer);
1757          call->params[i] = nir_deref_var_clone(d, call);
1758       } else {
1759          struct vtn_ssa_value *arg_ssa = vtn_ssa_value(b, arg_id);
1760
1761          /* Make a temporary to store the argument in */
1762          nir_variable *tmp =
1763             nir_local_variable_create(b->nb.impl, arg_ssa->type, "arg_tmp");
1764          call->params[i] = nir_deref_var_create(call, tmp);
1765
1766          vtn_local_store(b, arg_ssa, call->params[i]);
1767       }
1768    }
1769
1770    nir_variable *out_tmp = NULL;
1771    vtn_assert(res_type->type == callee->return_type);
1772    if (!glsl_type_is_void(callee->return_type)) {
1773       out_tmp = nir_local_variable_create(b->nb.impl, callee->return_type,
1774                                           "out_tmp");
1775       call->return_deref = nir_deref_var_create(call, out_tmp);
1776    }
1777
1778    nir_builder_instr_insert(&b->nb, &call->instr);
1779
1780    if (glsl_type_is_void(callee->return_type)) {
1781       vtn_push_value(b, w[2], vtn_value_type_undef);
1782    } else {
1783       vtn_push_ssa(b, w[2], res_type, vtn_local_load(b, call->return_deref));
1784    }
1785 }
1786
1787 struct vtn_ssa_value *
1788 vtn_create_ssa_value(struct vtn_builder *b, const struct glsl_type *type)
1789 {
1790    struct vtn_ssa_value *val = rzalloc(b, struct vtn_ssa_value);
1791    val->type = type;
1792
1793    if (!glsl_type_is_vector_or_scalar(type)) {
1794       unsigned elems = glsl_get_length(type);
1795       val->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
1796       for (unsigned i = 0; i < elems; i++) {
1797          const struct glsl_type *child_type;
1798
1799          switch (glsl_get_base_type(type)) {
1800          case GLSL_TYPE_INT:
1801          case GLSL_TYPE_UINT:
1802          case GLSL_TYPE_INT16:
1803          case GLSL_TYPE_UINT16:
1804          case GLSL_TYPE_INT64:
1805          case GLSL_TYPE_UINT64:
1806          case GLSL_TYPE_BOOL:
1807          case GLSL_TYPE_FLOAT:
1808          case GLSL_TYPE_FLOAT16:
1809          case GLSL_TYPE_DOUBLE:
1810             child_type = glsl_get_column_type(type);
1811             break;
1812          case GLSL_TYPE_ARRAY:
1813             child_type = glsl_get_array_element(type);
1814             break;
1815          case GLSL_TYPE_STRUCT:
1816             child_type = glsl_get_struct_field(type, i);
1817             break;
1818          default:
1819             vtn_fail("unkown base type");
1820          }
1821
1822          val->elems[i] = vtn_create_ssa_value(b, child_type);
1823       }
1824    }
1825
1826    return val;
1827 }
1828
1829 static nir_tex_src
1830 vtn_tex_src(struct vtn_builder *b, unsigned index, nir_tex_src_type type)
1831 {
1832    nir_tex_src src;
1833    src.src = nir_src_for_ssa(vtn_ssa_value(b, index)->def);
1834    src.src_type = type;
1835    return src;
1836 }
1837
1838 static void
1839 vtn_handle_texture(struct vtn_builder *b, SpvOp opcode,
1840                    const uint32_t *w, unsigned count)
1841 {
1842    if (opcode == SpvOpSampledImage) {
1843       struct vtn_value *val =
1844          vtn_push_value(b, w[2], vtn_value_type_sampled_image);
1845       val->sampled_image = ralloc(b, struct vtn_sampled_image);
1846       val->sampled_image->type =
1847          vtn_value(b, w[1], vtn_value_type_type)->type;
1848       val->sampled_image->image =
1849          vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
1850       val->sampled_image->sampler =
1851          vtn_value(b, w[4], vtn_value_type_pointer)->pointer;
1852       return;
1853    } else if (opcode == SpvOpImage) {
1854       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_pointer);
1855       struct vtn_value *src_val = vtn_untyped_value(b, w[3]);
1856       if (src_val->value_type == vtn_value_type_sampled_image) {
1857          val->pointer = src_val->sampled_image->image;
1858       } else {
1859          vtn_assert(src_val->value_type == vtn_value_type_pointer);
1860          val->pointer = src_val->pointer;
1861       }
1862       return;
1863    }
1864
1865    struct vtn_type *ret_type = vtn_value(b, w[1], vtn_value_type_type)->type;
1866    struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
1867
1868    struct vtn_sampled_image sampled;
1869    struct vtn_value *sampled_val = vtn_untyped_value(b, w[3]);
1870    if (sampled_val->value_type == vtn_value_type_sampled_image) {
1871       sampled = *sampled_val->sampled_image;
1872    } else {
1873       vtn_assert(sampled_val->value_type == vtn_value_type_pointer);
1874       sampled.type = sampled_val->pointer->type;
1875       sampled.image = NULL;
1876       sampled.sampler = sampled_val->pointer;
1877    }
1878
1879    const struct glsl_type *image_type = sampled.type->type;
1880    const enum glsl_sampler_dim sampler_dim = glsl_get_sampler_dim(image_type);
1881    const bool is_array = glsl_sampler_type_is_array(image_type);
1882    const bool is_shadow = glsl_sampler_type_is_shadow(image_type);
1883
1884    /* Figure out the base texture operation */
1885    nir_texop texop;
1886    switch (opcode) {
1887    case SpvOpImageSampleImplicitLod:
1888    case SpvOpImageSampleDrefImplicitLod:
1889    case SpvOpImageSampleProjImplicitLod:
1890    case SpvOpImageSampleProjDrefImplicitLod:
1891       texop = nir_texop_tex;
1892       break;
1893
1894    case SpvOpImageSampleExplicitLod:
1895    case SpvOpImageSampleDrefExplicitLod:
1896    case SpvOpImageSampleProjExplicitLod:
1897    case SpvOpImageSampleProjDrefExplicitLod:
1898       texop = nir_texop_txl;
1899       break;
1900
1901    case SpvOpImageFetch:
1902       if (glsl_get_sampler_dim(image_type) == GLSL_SAMPLER_DIM_MS) {
1903          texop = nir_texop_txf_ms;
1904       } else {
1905          texop = nir_texop_txf;
1906       }
1907       break;
1908
1909    case SpvOpImageGather:
1910    case SpvOpImageDrefGather:
1911       texop = nir_texop_tg4;
1912       break;
1913
1914    case SpvOpImageQuerySizeLod:
1915    case SpvOpImageQuerySize:
1916       texop = nir_texop_txs;
1917       break;
1918
1919    case SpvOpImageQueryLod:
1920       texop = nir_texop_lod;
1921       break;
1922
1923    case SpvOpImageQueryLevels:
1924       texop = nir_texop_query_levels;
1925       break;
1926
1927    case SpvOpImageQuerySamples:
1928       texop = nir_texop_texture_samples;
1929       break;
1930
1931    default:
1932       vtn_fail("Unhandled opcode");
1933    }
1934
1935    nir_tex_src srcs[8]; /* 8 should be enough */
1936    nir_tex_src *p = srcs;
1937
1938    unsigned idx = 4;
1939
1940    struct nir_ssa_def *coord;
1941    unsigned coord_components;
1942    switch (opcode) {
1943    case SpvOpImageSampleImplicitLod:
1944    case SpvOpImageSampleExplicitLod:
1945    case SpvOpImageSampleDrefImplicitLod:
1946    case SpvOpImageSampleDrefExplicitLod:
1947    case SpvOpImageSampleProjImplicitLod:
1948    case SpvOpImageSampleProjExplicitLod:
1949    case SpvOpImageSampleProjDrefImplicitLod:
1950    case SpvOpImageSampleProjDrefExplicitLod:
1951    case SpvOpImageFetch:
1952    case SpvOpImageGather:
1953    case SpvOpImageDrefGather:
1954    case SpvOpImageQueryLod: {
1955       /* All these types have the coordinate as their first real argument */
1956       switch (sampler_dim) {
1957       case GLSL_SAMPLER_DIM_1D:
1958       case GLSL_SAMPLER_DIM_BUF:
1959          coord_components = 1;
1960          break;
1961       case GLSL_SAMPLER_DIM_2D:
1962       case GLSL_SAMPLER_DIM_RECT:
1963       case GLSL_SAMPLER_DIM_MS:
1964          coord_components = 2;
1965          break;
1966       case GLSL_SAMPLER_DIM_3D:
1967       case GLSL_SAMPLER_DIM_CUBE:
1968          coord_components = 3;
1969          break;
1970       default:
1971          vtn_fail("Invalid sampler type");
1972       }
1973
1974       if (is_array && texop != nir_texop_lod)
1975          coord_components++;
1976
1977       coord = vtn_ssa_value(b, w[idx++])->def;
1978       p->src = nir_src_for_ssa(nir_channels(&b->nb, coord,
1979                                             (1 << coord_components) - 1));
1980       p->src_type = nir_tex_src_coord;
1981       p++;
1982       break;
1983    }
1984
1985    default:
1986       coord = NULL;
1987       coord_components = 0;
1988       break;
1989    }
1990
1991    switch (opcode) {
1992    case SpvOpImageSampleProjImplicitLod:
1993    case SpvOpImageSampleProjExplicitLod:
1994    case SpvOpImageSampleProjDrefImplicitLod:
1995    case SpvOpImageSampleProjDrefExplicitLod:
1996       /* These have the projector as the last coordinate component */
1997       p->src = nir_src_for_ssa(nir_channel(&b->nb, coord, coord_components));
1998       p->src_type = nir_tex_src_projector;
1999       p++;
2000       break;
2001
2002    default:
2003       break;
2004    }
2005
2006    unsigned gather_component = 0;
2007    switch (opcode) {
2008    case SpvOpImageSampleDrefImplicitLod:
2009    case SpvOpImageSampleDrefExplicitLod:
2010    case SpvOpImageSampleProjDrefImplicitLod:
2011    case SpvOpImageSampleProjDrefExplicitLod:
2012    case SpvOpImageDrefGather:
2013       /* These all have an explicit depth value as their next source */
2014       (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_comparator);
2015       break;
2016
2017    case SpvOpImageGather:
2018       /* This has a component as its next source */
2019       gather_component =
2020          vtn_value(b, w[idx++], vtn_value_type_constant)->constant->values[0].u32[0];
2021       break;
2022
2023    default:
2024       break;
2025    }
2026
2027    /* For OpImageQuerySizeLod, we always have an LOD */
2028    if (opcode == SpvOpImageQuerySizeLod)
2029       (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2030
2031    /* Now we need to handle some number of optional arguments */
2032    const struct vtn_ssa_value *gather_offsets = NULL;
2033    if (idx < count) {
2034       uint32_t operands = w[idx++];
2035
2036       if (operands & SpvImageOperandsBiasMask) {
2037          vtn_assert(texop == nir_texop_tex);
2038          texop = nir_texop_txb;
2039          (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_bias);
2040       }
2041
2042       if (operands & SpvImageOperandsLodMask) {
2043          vtn_assert(texop == nir_texop_txl || texop == nir_texop_txf ||
2044                     texop == nir_texop_txs);
2045          (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_lod);
2046       }
2047
2048       if (operands & SpvImageOperandsGradMask) {
2049          vtn_assert(texop == nir_texop_txl);
2050          texop = nir_texop_txd;
2051          (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddx);
2052          (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ddy);
2053       }
2054
2055       if (operands & SpvImageOperandsOffsetMask ||
2056           operands & SpvImageOperandsConstOffsetMask)
2057          (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_offset);
2058
2059       if (operands & SpvImageOperandsConstOffsetsMask) {
2060          gather_offsets = vtn_ssa_value(b, w[idx++]);
2061          (*p++) = (nir_tex_src){};
2062       }
2063
2064       if (operands & SpvImageOperandsSampleMask) {
2065          vtn_assert(texop == nir_texop_txf_ms);
2066          texop = nir_texop_txf_ms;
2067          (*p++) = vtn_tex_src(b, w[idx++], nir_tex_src_ms_index);
2068       }
2069    }
2070    /* We should have now consumed exactly all of the arguments */
2071    vtn_assert(idx == count);
2072
2073    nir_tex_instr *instr = nir_tex_instr_create(b->shader, p - srcs);
2074    instr->op = texop;
2075
2076    memcpy(instr->src, srcs, instr->num_srcs * sizeof(*instr->src));
2077
2078    instr->coord_components = coord_components;
2079    instr->sampler_dim = sampler_dim;
2080    instr->is_array = is_array;
2081    instr->is_shadow = is_shadow;
2082    instr->is_new_style_shadow =
2083       is_shadow && glsl_get_components(ret_type->type) == 1;
2084    instr->component = gather_component;
2085
2086    switch (glsl_get_sampler_result_type(image_type)) {
2087    case GLSL_TYPE_FLOAT:   instr->dest_type = nir_type_float;     break;
2088    case GLSL_TYPE_INT:     instr->dest_type = nir_type_int;       break;
2089    case GLSL_TYPE_UINT:    instr->dest_type = nir_type_uint;  break;
2090    case GLSL_TYPE_BOOL:    instr->dest_type = nir_type_bool;      break;
2091    default:
2092       vtn_fail("Invalid base type for sampler result");
2093    }
2094
2095    nir_deref_var *sampler = vtn_pointer_to_deref(b, sampled.sampler);
2096    nir_deref_var *texture;
2097    if (sampled.image) {
2098       nir_deref_var *image = vtn_pointer_to_deref(b, sampled.image);
2099       texture = image;
2100    } else {
2101       texture = sampler;
2102    }
2103
2104    instr->texture = nir_deref_var_clone(texture, instr);
2105
2106    switch (instr->op) {
2107    case nir_texop_tex:
2108    case nir_texop_txb:
2109    case nir_texop_txl:
2110    case nir_texop_txd:
2111    case nir_texop_tg4:
2112       /* These operations require a sampler */
2113       instr->sampler = nir_deref_var_clone(sampler, instr);
2114       break;
2115    case nir_texop_txf:
2116    case nir_texop_txf_ms:
2117    case nir_texop_txs:
2118    case nir_texop_lod:
2119    case nir_texop_query_levels:
2120    case nir_texop_texture_samples:
2121    case nir_texop_samples_identical:
2122       /* These don't */
2123       instr->sampler = NULL;
2124       break;
2125    case nir_texop_txf_ms_mcs:
2126       vtn_fail("unexpected nir_texop_txf_ms_mcs");
2127    }
2128
2129    nir_ssa_dest_init(&instr->instr, &instr->dest,
2130                      nir_tex_instr_dest_size(instr), 32, NULL);
2131
2132    vtn_assert(glsl_get_vector_elements(ret_type->type) ==
2133               nir_tex_instr_dest_size(instr));
2134
2135    nir_ssa_def *def;
2136    nir_instr *instruction;
2137    if (gather_offsets) {
2138       vtn_assert(glsl_get_base_type(gather_offsets->type) == GLSL_TYPE_ARRAY);
2139       vtn_assert(glsl_get_length(gather_offsets->type) == 4);
2140       nir_tex_instr *instrs[4] = {instr, NULL, NULL, NULL};
2141
2142       /* Copy the current instruction 4x */
2143       for (uint32_t i = 1; i < 4; i++) {
2144          instrs[i] = nir_tex_instr_create(b->shader, instr->num_srcs);
2145          instrs[i]->op = instr->op;
2146          instrs[i]->coord_components = instr->coord_components;
2147          instrs[i]->sampler_dim = instr->sampler_dim;
2148          instrs[i]->is_array = instr->is_array;
2149          instrs[i]->is_shadow = instr->is_shadow;
2150          instrs[i]->is_new_style_shadow = instr->is_new_style_shadow;
2151          instrs[i]->component = instr->component;
2152          instrs[i]->dest_type = instr->dest_type;
2153          instrs[i]->texture = nir_deref_var_clone(texture, instrs[i]);
2154          instrs[i]->sampler = NULL;
2155
2156          memcpy(instrs[i]->src, srcs, instr->num_srcs * sizeof(*instr->src));
2157
2158          nir_ssa_dest_init(&instrs[i]->instr, &instrs[i]->dest,
2159                            nir_tex_instr_dest_size(instr), 32, NULL);
2160       }
2161
2162       /* Fill in the last argument with the offset from the passed in offsets
2163        * and insert the instruction into the stream.
2164        */
2165       for (uint32_t i = 0; i < 4; i++) {
2166          nir_tex_src src;
2167          src.src = nir_src_for_ssa(gather_offsets->elems[i]->def);
2168          src.src_type = nir_tex_src_offset;
2169          instrs[i]->src[instrs[i]->num_srcs - 1] = src;
2170          nir_builder_instr_insert(&b->nb, &instrs[i]->instr);
2171       }
2172
2173       /* Combine the results of the 4 instructions by taking their .w
2174        * components
2175        */
2176       nir_alu_instr *vec4 = nir_alu_instr_create(b->shader, nir_op_vec4);
2177       nir_ssa_dest_init(&vec4->instr, &vec4->dest.dest, 4, 32, NULL);
2178       vec4->dest.write_mask = 0xf;
2179       for (uint32_t i = 0; i < 4; i++) {
2180          vec4->src[i].src = nir_src_for_ssa(&instrs[i]->dest.ssa);
2181          vec4->src[i].swizzle[0] = 3;
2182       }
2183       def = &vec4->dest.dest.ssa;
2184       instruction = &vec4->instr;
2185    } else {
2186       def = &instr->dest.ssa;
2187       instruction = &instr->instr;
2188    }
2189
2190    val->ssa = vtn_create_ssa_value(b, ret_type->type);
2191    val->ssa->def = def;
2192
2193    nir_builder_instr_insert(&b->nb, instruction);
2194 }
2195
2196 static void
2197 fill_common_atomic_sources(struct vtn_builder *b, SpvOp opcode,
2198                            const uint32_t *w, nir_src *src)
2199 {
2200    switch (opcode) {
2201    case SpvOpAtomicIIncrement:
2202       src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, 1));
2203       break;
2204
2205    case SpvOpAtomicIDecrement:
2206       src[0] = nir_src_for_ssa(nir_imm_int(&b->nb, -1));
2207       break;
2208
2209    case SpvOpAtomicISub:
2210       src[0] =
2211          nir_src_for_ssa(nir_ineg(&b->nb, vtn_ssa_value(b, w[6])->def));
2212       break;
2213
2214    case SpvOpAtomicCompareExchange:
2215       src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[8])->def);
2216       src[1] = nir_src_for_ssa(vtn_ssa_value(b, w[7])->def);
2217       break;
2218
2219    case SpvOpAtomicExchange:
2220    case SpvOpAtomicIAdd:
2221    case SpvOpAtomicSMin:
2222    case SpvOpAtomicUMin:
2223    case SpvOpAtomicSMax:
2224    case SpvOpAtomicUMax:
2225    case SpvOpAtomicAnd:
2226    case SpvOpAtomicOr:
2227    case SpvOpAtomicXor:
2228       src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[6])->def);
2229       break;
2230
2231    default:
2232       vtn_fail("Invalid SPIR-V atomic");
2233    }
2234 }
2235
2236 static nir_ssa_def *
2237 get_image_coord(struct vtn_builder *b, uint32_t value)
2238 {
2239    struct vtn_ssa_value *coord = vtn_ssa_value(b, value);
2240
2241    /* The image_load_store intrinsics assume a 4-dim coordinate */
2242    unsigned dim = glsl_get_vector_elements(coord->type);
2243    unsigned swizzle[4];
2244    for (unsigned i = 0; i < 4; i++)
2245       swizzle[i] = MIN2(i, dim - 1);
2246
2247    return nir_swizzle(&b->nb, coord->def, swizzle, 4, false);
2248 }
2249
2250 static void
2251 vtn_handle_image(struct vtn_builder *b, SpvOp opcode,
2252                  const uint32_t *w, unsigned count)
2253 {
2254    /* Just get this one out of the way */
2255    if (opcode == SpvOpImageTexelPointer) {
2256       struct vtn_value *val =
2257          vtn_push_value(b, w[2], vtn_value_type_image_pointer);
2258       val->image = ralloc(b, struct vtn_image_pointer);
2259
2260       val->image->image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2261       val->image->coord = get_image_coord(b, w[4]);
2262       val->image->sample = vtn_ssa_value(b, w[5])->def;
2263       return;
2264    }
2265
2266    struct vtn_image_pointer image;
2267
2268    switch (opcode) {
2269    case SpvOpAtomicExchange:
2270    case SpvOpAtomicCompareExchange:
2271    case SpvOpAtomicCompareExchangeWeak:
2272    case SpvOpAtomicIIncrement:
2273    case SpvOpAtomicIDecrement:
2274    case SpvOpAtomicIAdd:
2275    case SpvOpAtomicISub:
2276    case SpvOpAtomicLoad:
2277    case SpvOpAtomicSMin:
2278    case SpvOpAtomicUMin:
2279    case SpvOpAtomicSMax:
2280    case SpvOpAtomicUMax:
2281    case SpvOpAtomicAnd:
2282    case SpvOpAtomicOr:
2283    case SpvOpAtomicXor:
2284       image = *vtn_value(b, w[3], vtn_value_type_image_pointer)->image;
2285       break;
2286
2287    case SpvOpAtomicStore:
2288       image = *vtn_value(b, w[1], vtn_value_type_image_pointer)->image;
2289       break;
2290
2291    case SpvOpImageQuerySize:
2292       image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2293       image.coord = NULL;
2294       image.sample = NULL;
2295       break;
2296
2297    case SpvOpImageRead:
2298       image.image = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2299       image.coord = get_image_coord(b, w[4]);
2300
2301       if (count > 5 && (w[5] & SpvImageOperandsSampleMask)) {
2302          vtn_assert(w[5] == SpvImageOperandsSampleMask);
2303          image.sample = vtn_ssa_value(b, w[6])->def;
2304       } else {
2305          image.sample = nir_ssa_undef(&b->nb, 1, 32);
2306       }
2307       break;
2308
2309    case SpvOpImageWrite:
2310       image.image = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2311       image.coord = get_image_coord(b, w[2]);
2312
2313       /* texel = w[3] */
2314
2315       if (count > 4 && (w[4] & SpvImageOperandsSampleMask)) {
2316          vtn_assert(w[4] == SpvImageOperandsSampleMask);
2317          image.sample = vtn_ssa_value(b, w[5])->def;
2318       } else {
2319          image.sample = nir_ssa_undef(&b->nb, 1, 32);
2320       }
2321       break;
2322
2323    default:
2324       vtn_fail("Invalid image opcode");
2325    }
2326
2327    nir_intrinsic_op op;
2328    switch (opcode) {
2329 #define OP(S, N) case SpvOp##S: op = nir_intrinsic_image_##N; break;
2330    OP(ImageQuerySize,         size)
2331    OP(ImageRead,              load)
2332    OP(ImageWrite,             store)
2333    OP(AtomicLoad,             load)
2334    OP(AtomicStore,            store)
2335    OP(AtomicExchange,         atomic_exchange)
2336    OP(AtomicCompareExchange,  atomic_comp_swap)
2337    OP(AtomicIIncrement,       atomic_add)
2338    OP(AtomicIDecrement,       atomic_add)
2339    OP(AtomicIAdd,             atomic_add)
2340    OP(AtomicISub,             atomic_add)
2341    OP(AtomicSMin,             atomic_min)
2342    OP(AtomicUMin,             atomic_min)
2343    OP(AtomicSMax,             atomic_max)
2344    OP(AtomicUMax,             atomic_max)
2345    OP(AtomicAnd,              atomic_and)
2346    OP(AtomicOr,               atomic_or)
2347    OP(AtomicXor,              atomic_xor)
2348 #undef OP
2349    default:
2350       vtn_fail("Invalid image opcode");
2351    }
2352
2353    nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2354
2355    nir_deref_var *image_deref = vtn_pointer_to_deref(b, image.image);
2356    intrin->variables[0] = nir_deref_var_clone(image_deref, intrin);
2357
2358    /* ImageQuerySize doesn't take any extra parameters */
2359    if (opcode != SpvOpImageQuerySize) {
2360       /* The image coordinate is always 4 components but we may not have that
2361        * many.  Swizzle to compensate.
2362        */
2363       unsigned swiz[4];
2364       for (unsigned i = 0; i < 4; i++)
2365          swiz[i] = i < image.coord->num_components ? i : 0;
2366       intrin->src[0] = nir_src_for_ssa(nir_swizzle(&b->nb, image.coord,
2367                                                    swiz, 4, false));
2368       intrin->src[1] = nir_src_for_ssa(image.sample);
2369    }
2370
2371    switch (opcode) {
2372    case SpvOpAtomicLoad:
2373    case SpvOpImageQuerySize:
2374    case SpvOpImageRead:
2375       break;
2376    case SpvOpAtomicStore:
2377       intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2378       break;
2379    case SpvOpImageWrite:
2380       intrin->src[2] = nir_src_for_ssa(vtn_ssa_value(b, w[3])->def);
2381       break;
2382
2383    case SpvOpAtomicCompareExchange:
2384    case SpvOpAtomicIIncrement:
2385    case SpvOpAtomicIDecrement:
2386    case SpvOpAtomicExchange:
2387    case SpvOpAtomicIAdd:
2388    case SpvOpAtomicISub:
2389    case SpvOpAtomicSMin:
2390    case SpvOpAtomicUMin:
2391    case SpvOpAtomicSMax:
2392    case SpvOpAtomicUMax:
2393    case SpvOpAtomicAnd:
2394    case SpvOpAtomicOr:
2395    case SpvOpAtomicXor:
2396       fill_common_atomic_sources(b, opcode, w, &intrin->src[2]);
2397       break;
2398
2399    default:
2400       vtn_fail("Invalid image opcode");
2401    }
2402
2403    if (opcode != SpvOpImageWrite) {
2404       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2405       struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2406
2407       unsigned dest_components =
2408          nir_intrinsic_infos[intrin->intrinsic].dest_components;
2409       if (intrin->intrinsic == nir_intrinsic_image_size) {
2410          dest_components = intrin->num_components =
2411             glsl_get_vector_elements(type->type);
2412       }
2413
2414       nir_ssa_dest_init(&intrin->instr, &intrin->dest,
2415                         dest_components, 32, NULL);
2416
2417       nir_builder_instr_insert(&b->nb, &intrin->instr);
2418
2419       val->ssa = vtn_create_ssa_value(b, type->type);
2420       val->ssa->def = &intrin->dest.ssa;
2421    } else {
2422       nir_builder_instr_insert(&b->nb, &intrin->instr);
2423    }
2424 }
2425
2426 static nir_intrinsic_op
2427 get_ssbo_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2428 {
2429    switch (opcode) {
2430    case SpvOpAtomicLoad:      return nir_intrinsic_load_ssbo;
2431    case SpvOpAtomicStore:     return nir_intrinsic_store_ssbo;
2432 #define OP(S, N) case SpvOp##S: return nir_intrinsic_ssbo_##N;
2433    OP(AtomicExchange,         atomic_exchange)
2434    OP(AtomicCompareExchange,  atomic_comp_swap)
2435    OP(AtomicIIncrement,       atomic_add)
2436    OP(AtomicIDecrement,       atomic_add)
2437    OP(AtomicIAdd,             atomic_add)
2438    OP(AtomicISub,             atomic_add)
2439    OP(AtomicSMin,             atomic_imin)
2440    OP(AtomicUMin,             atomic_umin)
2441    OP(AtomicSMax,             atomic_imax)
2442    OP(AtomicUMax,             atomic_umax)
2443    OP(AtomicAnd,              atomic_and)
2444    OP(AtomicOr,               atomic_or)
2445    OP(AtomicXor,              atomic_xor)
2446 #undef OP
2447    default:
2448       vtn_fail("Invalid SSBO atomic");
2449    }
2450 }
2451
2452 static nir_intrinsic_op
2453 get_shared_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2454 {
2455    switch (opcode) {
2456    case SpvOpAtomicLoad:      return nir_intrinsic_load_shared;
2457    case SpvOpAtomicStore:     return nir_intrinsic_store_shared;
2458 #define OP(S, N) case SpvOp##S: return nir_intrinsic_shared_##N;
2459    OP(AtomicExchange,         atomic_exchange)
2460    OP(AtomicCompareExchange,  atomic_comp_swap)
2461    OP(AtomicIIncrement,       atomic_add)
2462    OP(AtomicIDecrement,       atomic_add)
2463    OP(AtomicIAdd,             atomic_add)
2464    OP(AtomicISub,             atomic_add)
2465    OP(AtomicSMin,             atomic_imin)
2466    OP(AtomicUMin,             atomic_umin)
2467    OP(AtomicSMax,             atomic_imax)
2468    OP(AtomicUMax,             atomic_umax)
2469    OP(AtomicAnd,              atomic_and)
2470    OP(AtomicOr,               atomic_or)
2471    OP(AtomicXor,              atomic_xor)
2472 #undef OP
2473    default:
2474       vtn_fail("Invalid shared atomic");
2475    }
2476 }
2477
2478 static nir_intrinsic_op
2479 get_var_nir_atomic_op(struct vtn_builder *b, SpvOp opcode)
2480 {
2481    switch (opcode) {
2482    case SpvOpAtomicLoad:      return nir_intrinsic_load_var;
2483    case SpvOpAtomicStore:     return nir_intrinsic_store_var;
2484 #define OP(S, N) case SpvOp##S: return nir_intrinsic_var_##N;
2485    OP(AtomicExchange,         atomic_exchange)
2486    OP(AtomicCompareExchange,  atomic_comp_swap)
2487    OP(AtomicIIncrement,       atomic_add)
2488    OP(AtomicIDecrement,       atomic_add)
2489    OP(AtomicIAdd,             atomic_add)
2490    OP(AtomicISub,             atomic_add)
2491    OP(AtomicSMin,             atomic_imin)
2492    OP(AtomicUMin,             atomic_umin)
2493    OP(AtomicSMax,             atomic_imax)
2494    OP(AtomicUMax,             atomic_umax)
2495    OP(AtomicAnd,              atomic_and)
2496    OP(AtomicOr,               atomic_or)
2497    OP(AtomicXor,              atomic_xor)
2498 #undef OP
2499    default:
2500       vtn_fail("Invalid shared atomic");
2501    }
2502 }
2503
2504 static void
2505 vtn_handle_ssbo_or_shared_atomic(struct vtn_builder *b, SpvOp opcode,
2506                                  const uint32_t *w, unsigned count)
2507 {
2508    struct vtn_pointer *ptr;
2509    nir_intrinsic_instr *atomic;
2510
2511    switch (opcode) {
2512    case SpvOpAtomicLoad:
2513    case SpvOpAtomicExchange:
2514    case SpvOpAtomicCompareExchange:
2515    case SpvOpAtomicCompareExchangeWeak:
2516    case SpvOpAtomicIIncrement:
2517    case SpvOpAtomicIDecrement:
2518    case SpvOpAtomicIAdd:
2519    case SpvOpAtomicISub:
2520    case SpvOpAtomicSMin:
2521    case SpvOpAtomicUMin:
2522    case SpvOpAtomicSMax:
2523    case SpvOpAtomicUMax:
2524    case SpvOpAtomicAnd:
2525    case SpvOpAtomicOr:
2526    case SpvOpAtomicXor:
2527       ptr = vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
2528       break;
2529
2530    case SpvOpAtomicStore:
2531       ptr = vtn_value(b, w[1], vtn_value_type_pointer)->pointer;
2532       break;
2533
2534    default:
2535       vtn_fail("Invalid SPIR-V atomic");
2536    }
2537
2538    /*
2539    SpvScope scope = w[4];
2540    SpvMemorySemanticsMask semantics = w[5];
2541    */
2542
2543    if (ptr->mode == vtn_variable_mode_workgroup &&
2544        !b->options->lower_workgroup_access_to_offsets) {
2545       nir_deref_var *deref = vtn_pointer_to_deref(b, ptr);
2546       const struct glsl_type *deref_type = nir_deref_tail(&deref->deref)->type;
2547       nir_intrinsic_op op = get_var_nir_atomic_op(b, opcode);
2548       atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2549       atomic->variables[0] = nir_deref_var_clone(deref, atomic);
2550
2551       switch (opcode) {
2552       case SpvOpAtomicLoad:
2553          atomic->num_components = glsl_get_vector_elements(deref_type);
2554          break;
2555
2556       case SpvOpAtomicStore:
2557          atomic->num_components = glsl_get_vector_elements(deref_type);
2558          nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2559          atomic->src[0] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2560          break;
2561
2562       case SpvOpAtomicExchange:
2563       case SpvOpAtomicCompareExchange:
2564       case SpvOpAtomicCompareExchangeWeak:
2565       case SpvOpAtomicIIncrement:
2566       case SpvOpAtomicIDecrement:
2567       case SpvOpAtomicIAdd:
2568       case SpvOpAtomicISub:
2569       case SpvOpAtomicSMin:
2570       case SpvOpAtomicUMin:
2571       case SpvOpAtomicSMax:
2572       case SpvOpAtomicUMax:
2573       case SpvOpAtomicAnd:
2574       case SpvOpAtomicOr:
2575       case SpvOpAtomicXor:
2576          fill_common_atomic_sources(b, opcode, w, &atomic->src[0]);
2577          break;
2578
2579       default:
2580          vtn_fail("Invalid SPIR-V atomic");
2581
2582       }
2583    } else {
2584       nir_ssa_def *offset, *index;
2585       offset = vtn_pointer_to_offset(b, ptr, &index, NULL);
2586
2587       nir_intrinsic_op op;
2588       if (ptr->mode == vtn_variable_mode_ssbo) {
2589          op = get_ssbo_nir_atomic_op(b, opcode);
2590       } else {
2591          vtn_assert(ptr->mode == vtn_variable_mode_workgroup &&
2592                     b->options->lower_workgroup_access_to_offsets);
2593          op = get_shared_nir_atomic_op(b, opcode);
2594       }
2595
2596       atomic = nir_intrinsic_instr_create(b->nb.shader, op);
2597
2598       int src = 0;
2599       switch (opcode) {
2600       case SpvOpAtomicLoad:
2601          atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2602          if (ptr->mode == vtn_variable_mode_ssbo)
2603             atomic->src[src++] = nir_src_for_ssa(index);
2604          atomic->src[src++] = nir_src_for_ssa(offset);
2605          break;
2606
2607       case SpvOpAtomicStore:
2608          atomic->num_components = glsl_get_vector_elements(ptr->type->type);
2609          nir_intrinsic_set_write_mask(atomic, (1 << atomic->num_components) - 1);
2610          atomic->src[src++] = nir_src_for_ssa(vtn_ssa_value(b, w[4])->def);
2611          if (ptr->mode == vtn_variable_mode_ssbo)
2612             atomic->src[src++] = nir_src_for_ssa(index);
2613          atomic->src[src++] = nir_src_for_ssa(offset);
2614          break;
2615
2616       case SpvOpAtomicExchange:
2617       case SpvOpAtomicCompareExchange:
2618       case SpvOpAtomicCompareExchangeWeak:
2619       case SpvOpAtomicIIncrement:
2620       case SpvOpAtomicIDecrement:
2621       case SpvOpAtomicIAdd:
2622       case SpvOpAtomicISub:
2623       case SpvOpAtomicSMin:
2624       case SpvOpAtomicUMin:
2625       case SpvOpAtomicSMax:
2626       case SpvOpAtomicUMax:
2627       case SpvOpAtomicAnd:
2628       case SpvOpAtomicOr:
2629       case SpvOpAtomicXor:
2630          if (ptr->mode == vtn_variable_mode_ssbo)
2631             atomic->src[src++] = nir_src_for_ssa(index);
2632          atomic->src[src++] = nir_src_for_ssa(offset);
2633          fill_common_atomic_sources(b, opcode, w, &atomic->src[src]);
2634          break;
2635
2636       default:
2637          vtn_fail("Invalid SPIR-V atomic");
2638       }
2639    }
2640
2641    if (opcode != SpvOpAtomicStore) {
2642       struct vtn_type *type = vtn_value(b, w[1], vtn_value_type_type)->type;
2643
2644       nir_ssa_dest_init(&atomic->instr, &atomic->dest,
2645                         glsl_get_vector_elements(type->type),
2646                         glsl_get_bit_size(type->type), NULL);
2647
2648       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2649       val->ssa = rzalloc(b, struct vtn_ssa_value);
2650       val->ssa->def = &atomic->dest.ssa;
2651       val->ssa->type = type->type;
2652    }
2653
2654    nir_builder_instr_insert(&b->nb, &atomic->instr);
2655 }
2656
2657 static nir_alu_instr *
2658 create_vec(struct vtn_builder *b, unsigned num_components, unsigned bit_size)
2659 {
2660    nir_op op;
2661    switch (num_components) {
2662    case 1: op = nir_op_fmov; break;
2663    case 2: op = nir_op_vec2; break;
2664    case 3: op = nir_op_vec3; break;
2665    case 4: op = nir_op_vec4; break;
2666    default: vtn_fail("bad vector size");
2667    }
2668
2669    nir_alu_instr *vec = nir_alu_instr_create(b->shader, op);
2670    nir_ssa_dest_init(&vec->instr, &vec->dest.dest, num_components,
2671                      bit_size, NULL);
2672    vec->dest.write_mask = (1 << num_components) - 1;
2673
2674    return vec;
2675 }
2676
2677 struct vtn_ssa_value *
2678 vtn_ssa_transpose(struct vtn_builder *b, struct vtn_ssa_value *src)
2679 {
2680    if (src->transposed)
2681       return src->transposed;
2682
2683    struct vtn_ssa_value *dest =
2684       vtn_create_ssa_value(b, glsl_transposed_type(src->type));
2685
2686    for (unsigned i = 0; i < glsl_get_matrix_columns(dest->type); i++) {
2687       nir_alu_instr *vec = create_vec(b, glsl_get_matrix_columns(src->type),
2688                                          glsl_get_bit_size(src->type));
2689       if (glsl_type_is_vector_or_scalar(src->type)) {
2690           vec->src[0].src = nir_src_for_ssa(src->def);
2691           vec->src[0].swizzle[0] = i;
2692       } else {
2693          for (unsigned j = 0; j < glsl_get_matrix_columns(src->type); j++) {
2694             vec->src[j].src = nir_src_for_ssa(src->elems[j]->def);
2695             vec->src[j].swizzle[0] = i;
2696          }
2697       }
2698       nir_builder_instr_insert(&b->nb, &vec->instr);
2699       dest->elems[i]->def = &vec->dest.dest.ssa;
2700    }
2701
2702    dest->transposed = src;
2703
2704    return dest;
2705 }
2706
2707 nir_ssa_def *
2708 vtn_vector_extract(struct vtn_builder *b, nir_ssa_def *src, unsigned index)
2709 {
2710    unsigned swiz[4] = { index };
2711    return nir_swizzle(&b->nb, src, swiz, 1, true);
2712 }
2713
2714 nir_ssa_def *
2715 vtn_vector_insert(struct vtn_builder *b, nir_ssa_def *src, nir_ssa_def *insert,
2716                   unsigned index)
2717 {
2718    nir_alu_instr *vec = create_vec(b, src->num_components,
2719                                    src->bit_size);
2720
2721    for (unsigned i = 0; i < src->num_components; i++) {
2722       if (i == index) {
2723          vec->src[i].src = nir_src_for_ssa(insert);
2724       } else {
2725          vec->src[i].src = nir_src_for_ssa(src);
2726          vec->src[i].swizzle[0] = i;
2727       }
2728    }
2729
2730    nir_builder_instr_insert(&b->nb, &vec->instr);
2731
2732    return &vec->dest.dest.ssa;
2733 }
2734
2735 nir_ssa_def *
2736 vtn_vector_extract_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2737                            nir_ssa_def *index)
2738 {
2739    nir_ssa_def *dest = vtn_vector_extract(b, src, 0);
2740    for (unsigned i = 1; i < src->num_components; i++)
2741       dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2742                        vtn_vector_extract(b, src, i), dest);
2743
2744    return dest;
2745 }
2746
2747 nir_ssa_def *
2748 vtn_vector_insert_dynamic(struct vtn_builder *b, nir_ssa_def *src,
2749                           nir_ssa_def *insert, nir_ssa_def *index)
2750 {
2751    nir_ssa_def *dest = vtn_vector_insert(b, src, insert, 0);
2752    for (unsigned i = 1; i < src->num_components; i++)
2753       dest = nir_bcsel(&b->nb, nir_ieq(&b->nb, index, nir_imm_int(&b->nb, i)),
2754                        vtn_vector_insert(b, src, insert, i), dest);
2755
2756    return dest;
2757 }
2758
2759 static nir_ssa_def *
2760 vtn_vector_shuffle(struct vtn_builder *b, unsigned num_components,
2761                    nir_ssa_def *src0, nir_ssa_def *src1,
2762                    const uint32_t *indices)
2763 {
2764    nir_alu_instr *vec = create_vec(b, num_components, src0->bit_size);
2765
2766    for (unsigned i = 0; i < num_components; i++) {
2767       uint32_t index = indices[i];
2768       if (index == 0xffffffff) {
2769          vec->src[i].src =
2770             nir_src_for_ssa(nir_ssa_undef(&b->nb, 1, src0->bit_size));
2771       } else if (index < src0->num_components) {
2772          vec->src[i].src = nir_src_for_ssa(src0);
2773          vec->src[i].swizzle[0] = index;
2774       } else {
2775          vec->src[i].src = nir_src_for_ssa(src1);
2776          vec->src[i].swizzle[0] = index - src0->num_components;
2777       }
2778    }
2779
2780    nir_builder_instr_insert(&b->nb, &vec->instr);
2781
2782    return &vec->dest.dest.ssa;
2783 }
2784
2785 /*
2786  * Concatentates a number of vectors/scalars together to produce a vector
2787  */
2788 static nir_ssa_def *
2789 vtn_vector_construct(struct vtn_builder *b, unsigned num_components,
2790                      unsigned num_srcs, nir_ssa_def **srcs)
2791 {
2792    nir_alu_instr *vec = create_vec(b, num_components, srcs[0]->bit_size);
2793
2794    /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2795     *
2796     *    "When constructing a vector, there must be at least two Constituent
2797     *    operands."
2798     */
2799    vtn_assert(num_srcs >= 2);
2800
2801    unsigned dest_idx = 0;
2802    for (unsigned i = 0; i < num_srcs; i++) {
2803       nir_ssa_def *src = srcs[i];
2804       vtn_assert(dest_idx + src->num_components <= num_components);
2805       for (unsigned j = 0; j < src->num_components; j++) {
2806          vec->src[dest_idx].src = nir_src_for_ssa(src);
2807          vec->src[dest_idx].swizzle[0] = j;
2808          dest_idx++;
2809       }
2810    }
2811
2812    /* From the SPIR-V 1.1 spec for OpCompositeConstruct:
2813     *
2814     *    "When constructing a vector, the total number of components in all
2815     *    the operands must equal the number of components in Result Type."
2816     */
2817    vtn_assert(dest_idx == num_components);
2818
2819    nir_builder_instr_insert(&b->nb, &vec->instr);
2820
2821    return &vec->dest.dest.ssa;
2822 }
2823
2824 static struct vtn_ssa_value *
2825 vtn_composite_copy(void *mem_ctx, struct vtn_ssa_value *src)
2826 {
2827    struct vtn_ssa_value *dest = rzalloc(mem_ctx, struct vtn_ssa_value);
2828    dest->type = src->type;
2829
2830    if (glsl_type_is_vector_or_scalar(src->type)) {
2831       dest->def = src->def;
2832    } else {
2833       unsigned elems = glsl_get_length(src->type);
2834
2835       dest->elems = ralloc_array(mem_ctx, struct vtn_ssa_value *, elems);
2836       for (unsigned i = 0; i < elems; i++)
2837          dest->elems[i] = vtn_composite_copy(mem_ctx, src->elems[i]);
2838    }
2839
2840    return dest;
2841 }
2842
2843 static struct vtn_ssa_value *
2844 vtn_composite_insert(struct vtn_builder *b, struct vtn_ssa_value *src,
2845                      struct vtn_ssa_value *insert, const uint32_t *indices,
2846                      unsigned num_indices)
2847 {
2848    struct vtn_ssa_value *dest = vtn_composite_copy(b, src);
2849
2850    struct vtn_ssa_value *cur = dest;
2851    unsigned i;
2852    for (i = 0; i < num_indices - 1; i++) {
2853       cur = cur->elems[indices[i]];
2854    }
2855
2856    if (glsl_type_is_vector_or_scalar(cur->type)) {
2857       /* According to the SPIR-V spec, OpCompositeInsert may work down to
2858        * the component granularity. In that case, the last index will be
2859        * the index to insert the scalar into the vector.
2860        */
2861
2862       cur->def = vtn_vector_insert(b, cur->def, insert->def, indices[i]);
2863    } else {
2864       cur->elems[indices[i]] = insert;
2865    }
2866
2867    return dest;
2868 }
2869
2870 static struct vtn_ssa_value *
2871 vtn_composite_extract(struct vtn_builder *b, struct vtn_ssa_value *src,
2872                       const uint32_t *indices, unsigned num_indices)
2873 {
2874    struct vtn_ssa_value *cur = src;
2875    for (unsigned i = 0; i < num_indices; i++) {
2876       if (glsl_type_is_vector_or_scalar(cur->type)) {
2877          vtn_assert(i == num_indices - 1);
2878          /* According to the SPIR-V spec, OpCompositeExtract may work down to
2879           * the component granularity. The last index will be the index of the
2880           * vector to extract.
2881           */
2882
2883          struct vtn_ssa_value *ret = rzalloc(b, struct vtn_ssa_value);
2884          ret->type = glsl_scalar_type(glsl_get_base_type(cur->type));
2885          ret->def = vtn_vector_extract(b, cur->def, indices[i]);
2886          return ret;
2887       } else {
2888          cur = cur->elems[indices[i]];
2889       }
2890    }
2891
2892    return cur;
2893 }
2894
2895 static void
2896 vtn_handle_composite(struct vtn_builder *b, SpvOp opcode,
2897                      const uint32_t *w, unsigned count)
2898 {
2899    struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_ssa);
2900    const struct glsl_type *type =
2901       vtn_value(b, w[1], vtn_value_type_type)->type->type;
2902    val->ssa = vtn_create_ssa_value(b, type);
2903
2904    switch (opcode) {
2905    case SpvOpVectorExtractDynamic:
2906       val->ssa->def = vtn_vector_extract_dynamic(b, vtn_ssa_value(b, w[3])->def,
2907                                                  vtn_ssa_value(b, w[4])->def);
2908       break;
2909
2910    case SpvOpVectorInsertDynamic:
2911       val->ssa->def = vtn_vector_insert_dynamic(b, vtn_ssa_value(b, w[3])->def,
2912                                                 vtn_ssa_value(b, w[4])->def,
2913                                                 vtn_ssa_value(b, w[5])->def);
2914       break;
2915
2916    case SpvOpVectorShuffle:
2917       val->ssa->def = vtn_vector_shuffle(b, glsl_get_vector_elements(type),
2918                                          vtn_ssa_value(b, w[3])->def,
2919                                          vtn_ssa_value(b, w[4])->def,
2920                                          w + 5);
2921       break;
2922
2923    case SpvOpCompositeConstruct: {
2924       unsigned elems = count - 3;
2925       if (glsl_type_is_vector_or_scalar(type)) {
2926          nir_ssa_def *srcs[4];
2927          for (unsigned i = 0; i < elems; i++)
2928             srcs[i] = vtn_ssa_value(b, w[3 + i])->def;
2929          val->ssa->def =
2930             vtn_vector_construct(b, glsl_get_vector_elements(type),
2931                                  elems, srcs);
2932       } else {
2933          val->ssa->elems = ralloc_array(b, struct vtn_ssa_value *, elems);
2934          for (unsigned i = 0; i < elems; i++)
2935             val->ssa->elems[i] = vtn_ssa_value(b, w[3 + i]);
2936       }
2937       break;
2938    }
2939    case SpvOpCompositeExtract:
2940       val->ssa = vtn_composite_extract(b, vtn_ssa_value(b, w[3]),
2941                                        w + 4, count - 4);
2942       break;
2943
2944    case SpvOpCompositeInsert:
2945       val->ssa = vtn_composite_insert(b, vtn_ssa_value(b, w[4]),
2946                                       vtn_ssa_value(b, w[3]),
2947                                       w + 5, count - 5);
2948       break;
2949
2950    case SpvOpCopyObject:
2951       val->ssa = vtn_composite_copy(b, vtn_ssa_value(b, w[3]));
2952       break;
2953
2954    default:
2955       vtn_fail("unknown composite operation");
2956    }
2957 }
2958
2959 static void
2960 vtn_emit_barrier(struct vtn_builder *b, nir_intrinsic_op op)
2961 {
2962    nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->shader, op);
2963    nir_builder_instr_insert(&b->nb, &intrin->instr);
2964 }
2965
2966 static void
2967 vtn_emit_memory_barrier(struct vtn_builder *b, SpvScope scope,
2968                         SpvMemorySemanticsMask semantics)
2969 {
2970    static const SpvMemorySemanticsMask all_memory_semantics =
2971       SpvMemorySemanticsUniformMemoryMask |
2972       SpvMemorySemanticsWorkgroupMemoryMask |
2973       SpvMemorySemanticsAtomicCounterMemoryMask |
2974       SpvMemorySemanticsImageMemoryMask;
2975
2976    /* If we're not actually doing a memory barrier, bail */
2977    if (!(semantics & all_memory_semantics))
2978       return;
2979
2980    /* GL and Vulkan don't have these */
2981    vtn_assert(scope != SpvScopeCrossDevice);
2982
2983    if (scope == SpvScopeSubgroup)
2984       return; /* Nothing to do here */
2985
2986    if (scope == SpvScopeWorkgroup) {
2987       vtn_emit_barrier(b, nir_intrinsic_group_memory_barrier);
2988       return;
2989    }
2990
2991    /* There's only two scopes thing left */
2992    vtn_assert(scope == SpvScopeInvocation || scope == SpvScopeDevice);
2993
2994    if ((semantics & all_memory_semantics) == all_memory_semantics) {
2995       vtn_emit_barrier(b, nir_intrinsic_memory_barrier);
2996       return;
2997    }
2998
2999    /* Issue a bunch of more specific barriers */
3000    uint32_t bits = semantics;
3001    while (bits) {
3002       SpvMemorySemanticsMask semantic = 1 << u_bit_scan(&bits);
3003       switch (semantic) {
3004       case SpvMemorySemanticsUniformMemoryMask:
3005          vtn_emit_barrier(b, nir_intrinsic_memory_barrier_buffer);
3006          break;
3007       case SpvMemorySemanticsWorkgroupMemoryMask:
3008          vtn_emit_barrier(b, nir_intrinsic_memory_barrier_shared);
3009          break;
3010       case SpvMemorySemanticsAtomicCounterMemoryMask:
3011          vtn_emit_barrier(b, nir_intrinsic_memory_barrier_atomic_counter);
3012          break;
3013       case SpvMemorySemanticsImageMemoryMask:
3014          vtn_emit_barrier(b, nir_intrinsic_memory_barrier_image);
3015          break;
3016       default:
3017          break;;
3018       }
3019    }
3020 }
3021
3022 static void
3023 vtn_handle_barrier(struct vtn_builder *b, SpvOp opcode,
3024                    const uint32_t *w, unsigned count)
3025 {
3026    switch (opcode) {
3027    case SpvOpEmitVertex:
3028    case SpvOpEmitStreamVertex:
3029    case SpvOpEndPrimitive:
3030    case SpvOpEndStreamPrimitive: {
3031       nir_intrinsic_op intrinsic_op;
3032       switch (opcode) {
3033       case SpvOpEmitVertex:
3034       case SpvOpEmitStreamVertex:
3035          intrinsic_op = nir_intrinsic_emit_vertex;
3036          break;
3037       case SpvOpEndPrimitive:
3038       case SpvOpEndStreamPrimitive:
3039          intrinsic_op = nir_intrinsic_end_primitive;
3040          break;
3041       default:
3042          unreachable("Invalid opcode");
3043       }
3044
3045       nir_intrinsic_instr *intrin =
3046          nir_intrinsic_instr_create(b->shader, intrinsic_op);
3047
3048       switch (opcode) {
3049       case SpvOpEmitStreamVertex:
3050       case SpvOpEndStreamPrimitive:
3051          nir_intrinsic_set_stream_id(intrin, w[1]);
3052          break;
3053       default:
3054          break;
3055       }
3056
3057       nir_builder_instr_insert(&b->nb, &intrin->instr);
3058       break;
3059    }
3060
3061    case SpvOpMemoryBarrier: {
3062       SpvScope scope = vtn_constant_value(b, w[1])->values[0].u32[0];
3063       SpvMemorySemanticsMask semantics =
3064          vtn_constant_value(b, w[2])->values[0].u32[0];
3065       vtn_emit_memory_barrier(b, scope, semantics);
3066       return;
3067    }
3068
3069    case SpvOpControlBarrier: {
3070       SpvScope execution_scope =
3071          vtn_constant_value(b, w[1])->values[0].u32[0];
3072       if (execution_scope == SpvScopeWorkgroup)
3073          vtn_emit_barrier(b, nir_intrinsic_barrier);
3074
3075       SpvScope memory_scope =
3076          vtn_constant_value(b, w[2])->values[0].u32[0];
3077       SpvMemorySemanticsMask memory_semantics =
3078          vtn_constant_value(b, w[3])->values[0].u32[0];
3079       vtn_emit_memory_barrier(b, memory_scope, memory_semantics);
3080       break;
3081    }
3082
3083    default:
3084       unreachable("unknown barrier instruction");
3085    }
3086 }
3087
3088 static unsigned
3089 gl_primitive_from_spv_execution_mode(struct vtn_builder *b,
3090                                      SpvExecutionMode mode)
3091 {
3092    switch (mode) {
3093    case SpvExecutionModeInputPoints:
3094    case SpvExecutionModeOutputPoints:
3095       return 0; /* GL_POINTS */
3096    case SpvExecutionModeInputLines:
3097       return 1; /* GL_LINES */
3098    case SpvExecutionModeInputLinesAdjacency:
3099       return 0x000A; /* GL_LINE_STRIP_ADJACENCY_ARB */
3100    case SpvExecutionModeTriangles:
3101       return 4; /* GL_TRIANGLES */
3102    case SpvExecutionModeInputTrianglesAdjacency:
3103       return 0x000C; /* GL_TRIANGLES_ADJACENCY_ARB */
3104    case SpvExecutionModeQuads:
3105       return 7; /* GL_QUADS */
3106    case SpvExecutionModeIsolines:
3107       return 0x8E7A; /* GL_ISOLINES */
3108    case SpvExecutionModeOutputLineStrip:
3109       return 3; /* GL_LINE_STRIP */
3110    case SpvExecutionModeOutputTriangleStrip:
3111       return 5; /* GL_TRIANGLE_STRIP */
3112    default:
3113       vtn_fail("Invalid primitive type");
3114    }
3115 }
3116
3117 static unsigned
3118 vertices_in_from_spv_execution_mode(struct vtn_builder *b,
3119                                     SpvExecutionMode mode)
3120 {
3121    switch (mode) {
3122    case SpvExecutionModeInputPoints:
3123       return 1;
3124    case SpvExecutionModeInputLines:
3125       return 2;
3126    case SpvExecutionModeInputLinesAdjacency:
3127       return 4;
3128    case SpvExecutionModeTriangles:
3129       return 3;
3130    case SpvExecutionModeInputTrianglesAdjacency:
3131       return 6;
3132    default:
3133       vtn_fail("Invalid GS input mode");
3134    }
3135 }
3136
3137 static gl_shader_stage
3138 stage_for_execution_model(struct vtn_builder *b, SpvExecutionModel model)
3139 {
3140    switch (model) {
3141    case SpvExecutionModelVertex:
3142       return MESA_SHADER_VERTEX;
3143    case SpvExecutionModelTessellationControl:
3144       return MESA_SHADER_TESS_CTRL;
3145    case SpvExecutionModelTessellationEvaluation:
3146       return MESA_SHADER_TESS_EVAL;
3147    case SpvExecutionModelGeometry:
3148       return MESA_SHADER_GEOMETRY;
3149    case SpvExecutionModelFragment:
3150       return MESA_SHADER_FRAGMENT;
3151    case SpvExecutionModelGLCompute:
3152       return MESA_SHADER_COMPUTE;
3153    default:
3154       vtn_fail("Unsupported execution model");
3155    }
3156 }
3157
3158 #define spv_check_supported(name, cap) do {             \
3159       if (!(b->options && b->options->caps.name))       \
3160          vtn_warn("Unsupported SPIR-V capability: %s",  \
3161                   spirv_capability_to_string(cap));     \
3162    } while(0)
3163
3164 static bool
3165 vtn_handle_preamble_instruction(struct vtn_builder *b, SpvOp opcode,
3166                                 const uint32_t *w, unsigned count)
3167 {
3168    switch (opcode) {
3169    case SpvOpSource: {
3170       const char *lang;
3171       switch (w[1]) {
3172       default:
3173       case SpvSourceLanguageUnknown:      lang = "unknown";    break;
3174       case SpvSourceLanguageESSL:         lang = "ESSL";       break;
3175       case SpvSourceLanguageGLSL:         lang = "GLSL";       break;
3176       case SpvSourceLanguageOpenCL_C:     lang = "OpenCL C";   break;
3177       case SpvSourceLanguageOpenCL_CPP:   lang = "OpenCL C++"; break;
3178       case SpvSourceLanguageHLSL:         lang = "HLSL";       break;
3179       }
3180
3181       uint32_t version = w[2];
3182
3183       const char *file =
3184          (count > 3) ? vtn_value(b, w[3], vtn_value_type_string)->str : "";
3185
3186       vtn_info("Parsing SPIR-V from %s %u source file %s", lang, version, file);
3187       break;
3188    }
3189
3190    case SpvOpSourceExtension:
3191    case SpvOpSourceContinued:
3192    case SpvOpExtension:
3193       /* Unhandled, but these are for debug so that's ok. */
3194       break;
3195
3196    case SpvOpCapability: {
3197       SpvCapability cap = w[1];
3198       switch (cap) {
3199       case SpvCapabilityMatrix:
3200       case SpvCapabilityShader:
3201       case SpvCapabilityGeometry:
3202       case SpvCapabilityGeometryPointSize:
3203       case SpvCapabilityUniformBufferArrayDynamicIndexing:
3204       case SpvCapabilitySampledImageArrayDynamicIndexing:
3205       case SpvCapabilityStorageBufferArrayDynamicIndexing:
3206       case SpvCapabilityStorageImageArrayDynamicIndexing:
3207       case SpvCapabilityImageRect:
3208       case SpvCapabilitySampledRect:
3209       case SpvCapabilitySampled1D:
3210       case SpvCapabilityImage1D:
3211       case SpvCapabilitySampledCubeArray:
3212       case SpvCapabilityImageCubeArray:
3213       case SpvCapabilitySampledBuffer:
3214       case SpvCapabilityImageBuffer:
3215       case SpvCapabilityImageQuery:
3216       case SpvCapabilityDerivativeControl:
3217       case SpvCapabilityInterpolationFunction:
3218       case SpvCapabilityMultiViewport:
3219       case SpvCapabilitySampleRateShading:
3220       case SpvCapabilityClipDistance:
3221       case SpvCapabilityCullDistance:
3222       case SpvCapabilityInputAttachment:
3223       case SpvCapabilityImageGatherExtended:
3224       case SpvCapabilityStorageImageExtendedFormats:
3225          break;
3226
3227       case SpvCapabilityGeometryStreams:
3228       case SpvCapabilityLinkage:
3229       case SpvCapabilityVector16:
3230       case SpvCapabilityFloat16Buffer:
3231       case SpvCapabilityFloat16:
3232       case SpvCapabilityInt64Atomics:
3233       case SpvCapabilityAtomicStorage:
3234       case SpvCapabilityInt16:
3235       case SpvCapabilityStorageImageMultisample:
3236       case SpvCapabilityInt8:
3237       case SpvCapabilitySparseResidency:
3238       case SpvCapabilityMinLod:
3239       case SpvCapabilityTransformFeedback:
3240          vtn_warn("Unsupported SPIR-V capability: %s",
3241                   spirv_capability_to_string(cap));
3242          break;
3243
3244       case SpvCapabilityFloat64:
3245          spv_check_supported(float64, cap);
3246          break;
3247       case SpvCapabilityInt64:
3248          spv_check_supported(int64, cap);
3249          break;
3250
3251       case SpvCapabilityAddresses:
3252       case SpvCapabilityKernel:
3253       case SpvCapabilityImageBasic:
3254       case SpvCapabilityImageReadWrite:
3255       case SpvCapabilityImageMipmap:
3256       case SpvCapabilityPipes:
3257       case SpvCapabilityGroups:
3258       case SpvCapabilityDeviceEnqueue:
3259       case SpvCapabilityLiteralSampler:
3260       case SpvCapabilityGenericPointer:
3261          vtn_warn("Unsupported OpenCL-style SPIR-V capability: %s",
3262                   spirv_capability_to_string(cap));
3263          break;
3264
3265       case SpvCapabilityImageMSArray:
3266          spv_check_supported(image_ms_array, cap);
3267          break;
3268
3269       case SpvCapabilityTessellation:
3270       case SpvCapabilityTessellationPointSize:
3271          spv_check_supported(tessellation, cap);
3272          break;
3273
3274       case SpvCapabilityDrawParameters:
3275          spv_check_supported(draw_parameters, cap);
3276          break;
3277
3278       case SpvCapabilityStorageImageReadWithoutFormat:
3279          spv_check_supported(image_read_without_format, cap);
3280          break;
3281
3282       case SpvCapabilityStorageImageWriteWithoutFormat:
3283          spv_check_supported(image_write_without_format, cap);
3284          break;
3285
3286       case SpvCapabilityDeviceGroup:
3287          spv_check_supported(device_group, cap);
3288          break;
3289
3290       case SpvCapabilityMultiView:
3291          spv_check_supported(multiview, cap);
3292          break;
3293
3294       case SpvCapabilityVariablePointersStorageBuffer:
3295       case SpvCapabilityVariablePointers:
3296          spv_check_supported(variable_pointers, cap);
3297          break;
3298
3299       case SpvCapabilityStorageUniformBufferBlock16:
3300       case SpvCapabilityStorageUniform16:
3301       case SpvCapabilityStoragePushConstant16:
3302       case SpvCapabilityStorageInputOutput16:
3303          spv_check_supported(storage_16bit, cap);
3304          break;
3305
3306       case SpvCapabilityShaderViewportIndexLayerEXT:
3307          spv_check_supported(shader_viewport_index_layer, cap);
3308          break;
3309
3310       default:
3311          vtn_fail("Unhandled capability");
3312       }
3313       break;
3314    }
3315
3316    case SpvOpExtInstImport:
3317       vtn_handle_extension(b, opcode, w, count);
3318       break;
3319
3320    case SpvOpMemoryModel:
3321       vtn_assert(w[1] == SpvAddressingModelLogical);
3322       vtn_assert(w[2] == SpvMemoryModelSimple ||
3323                  w[2] == SpvMemoryModelGLSL450);
3324       break;
3325
3326    case SpvOpEntryPoint: {
3327       struct vtn_value *entry_point = &b->values[w[2]];
3328       /* Let this be a name label regardless */
3329       unsigned name_words;
3330       entry_point->name = vtn_string_literal(b, &w[3], count - 3, &name_words);
3331
3332       if (strcmp(entry_point->name, b->entry_point_name) != 0 ||
3333           stage_for_execution_model(b, w[1]) != b->entry_point_stage)
3334          break;
3335
3336       vtn_assert(b->entry_point == NULL);
3337       b->entry_point = entry_point;
3338       break;
3339    }
3340
3341    case SpvOpString:
3342       vtn_push_value(b, w[1], vtn_value_type_string)->str =
3343          vtn_string_literal(b, &w[2], count - 2, NULL);
3344       break;
3345
3346    case SpvOpName:
3347       b->values[w[1]].name = vtn_string_literal(b, &w[2], count - 2, NULL);
3348       break;
3349
3350    case SpvOpMemberName:
3351       /* TODO */
3352       break;
3353
3354    case SpvOpExecutionMode:
3355    case SpvOpDecorationGroup:
3356    case SpvOpDecorate:
3357    case SpvOpMemberDecorate:
3358    case SpvOpGroupDecorate:
3359    case SpvOpGroupMemberDecorate:
3360       vtn_handle_decoration(b, opcode, w, count);
3361       break;
3362
3363    default:
3364       return false; /* End of preamble */
3365    }
3366
3367    return true;
3368 }
3369
3370 static void
3371 vtn_handle_execution_mode(struct vtn_builder *b, struct vtn_value *entry_point,
3372                           const struct vtn_decoration *mode, void *data)
3373 {
3374    vtn_assert(b->entry_point == entry_point);
3375
3376    switch(mode->exec_mode) {
3377    case SpvExecutionModeOriginUpperLeft:
3378    case SpvExecutionModeOriginLowerLeft:
3379       b->origin_upper_left =
3380          (mode->exec_mode == SpvExecutionModeOriginUpperLeft);
3381       break;
3382
3383    case SpvExecutionModeEarlyFragmentTests:
3384       vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3385       b->shader->info.fs.early_fragment_tests = true;
3386       break;
3387
3388    case SpvExecutionModeInvocations:
3389       vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3390       b->shader->info.gs.invocations = MAX2(1, mode->literals[0]);
3391       break;
3392
3393    case SpvExecutionModeDepthReplacing:
3394       vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3395       b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_ANY;
3396       break;
3397    case SpvExecutionModeDepthGreater:
3398       vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3399       b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_GREATER;
3400       break;
3401    case SpvExecutionModeDepthLess:
3402       vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3403       b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_LESS;
3404       break;
3405    case SpvExecutionModeDepthUnchanged:
3406       vtn_assert(b->shader->info.stage == MESA_SHADER_FRAGMENT);
3407       b->shader->info.fs.depth_layout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3408       break;
3409
3410    case SpvExecutionModeLocalSize:
3411       vtn_assert(b->shader->info.stage == MESA_SHADER_COMPUTE);
3412       b->shader->info.cs.local_size[0] = mode->literals[0];
3413       b->shader->info.cs.local_size[1] = mode->literals[1];
3414       b->shader->info.cs.local_size[2] = mode->literals[2];
3415       break;
3416    case SpvExecutionModeLocalSizeHint:
3417       break; /* Nothing to do with this */
3418
3419    case SpvExecutionModeOutputVertices:
3420       if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3421           b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3422          b->shader->info.tess.tcs_vertices_out = mode->literals[0];
3423       } else {
3424          vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3425          b->shader->info.gs.vertices_out = mode->literals[0];
3426       }
3427       break;
3428
3429    case SpvExecutionModeInputPoints:
3430    case SpvExecutionModeInputLines:
3431    case SpvExecutionModeInputLinesAdjacency:
3432    case SpvExecutionModeTriangles:
3433    case SpvExecutionModeInputTrianglesAdjacency:
3434    case SpvExecutionModeQuads:
3435    case SpvExecutionModeIsolines:
3436       if (b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3437           b->shader->info.stage == MESA_SHADER_TESS_EVAL) {
3438          b->shader->info.tess.primitive_mode =
3439             gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3440       } else {
3441          vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3442          b->shader->info.gs.vertices_in =
3443             vertices_in_from_spv_execution_mode(b, mode->exec_mode);
3444       }
3445       break;
3446
3447    case SpvExecutionModeOutputPoints:
3448    case SpvExecutionModeOutputLineStrip:
3449    case SpvExecutionModeOutputTriangleStrip:
3450       vtn_assert(b->shader->info.stage == MESA_SHADER_GEOMETRY);
3451       b->shader->info.gs.output_primitive =
3452          gl_primitive_from_spv_execution_mode(b, mode->exec_mode);
3453       break;
3454
3455    case SpvExecutionModeSpacingEqual:
3456       vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3457                  b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3458       b->shader->info.tess.spacing = TESS_SPACING_EQUAL;
3459       break;
3460    case SpvExecutionModeSpacingFractionalEven:
3461       vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3462                  b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3463       b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_EVEN;
3464       break;
3465    case SpvExecutionModeSpacingFractionalOdd:
3466       vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3467                  b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3468       b->shader->info.tess.spacing = TESS_SPACING_FRACTIONAL_ODD;
3469       break;
3470    case SpvExecutionModeVertexOrderCw:
3471       vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3472                  b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3473       b->shader->info.tess.ccw = false;
3474       break;
3475    case SpvExecutionModeVertexOrderCcw:
3476       vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3477                  b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3478       b->shader->info.tess.ccw = true;
3479       break;
3480    case SpvExecutionModePointMode:
3481       vtn_assert(b->shader->info.stage == MESA_SHADER_TESS_CTRL ||
3482                  b->shader->info.stage == MESA_SHADER_TESS_EVAL);
3483       b->shader->info.tess.point_mode = true;
3484       break;
3485
3486    case SpvExecutionModePixelCenterInteger:
3487       b->pixel_center_integer = true;
3488       break;
3489
3490    case SpvExecutionModeXfb:
3491       vtn_fail("Unhandled execution mode");
3492       break;
3493
3494    case SpvExecutionModeVecTypeHint:
3495    case SpvExecutionModeContractionOff:
3496       break; /* OpenCL */
3497
3498    default:
3499       vtn_fail("Unhandled execution mode");
3500    }
3501 }
3502
3503 static bool
3504 vtn_handle_variable_or_type_instruction(struct vtn_builder *b, SpvOp opcode,
3505                                         const uint32_t *w, unsigned count)
3506 {
3507    vtn_set_instruction_result_type(b, opcode, w, count);
3508
3509    switch (opcode) {
3510    case SpvOpSource:
3511    case SpvOpSourceContinued:
3512    case SpvOpSourceExtension:
3513    case SpvOpExtension:
3514    case SpvOpCapability:
3515    case SpvOpExtInstImport:
3516    case SpvOpMemoryModel:
3517    case SpvOpEntryPoint:
3518    case SpvOpExecutionMode:
3519    case SpvOpString:
3520    case SpvOpName:
3521    case SpvOpMemberName:
3522    case SpvOpDecorationGroup:
3523    case SpvOpDecorate:
3524    case SpvOpMemberDecorate:
3525    case SpvOpGroupDecorate:
3526    case SpvOpGroupMemberDecorate:
3527       vtn_fail("Invalid opcode types and variables section");
3528       break;
3529
3530    case SpvOpTypeVoid:
3531    case SpvOpTypeBool:
3532    case SpvOpTypeInt:
3533    case SpvOpTypeFloat:
3534    case SpvOpTypeVector:
3535    case SpvOpTypeMatrix:
3536    case SpvOpTypeImage:
3537    case SpvOpTypeSampler:
3538    case SpvOpTypeSampledImage:
3539    case SpvOpTypeArray:
3540    case SpvOpTypeRuntimeArray:
3541    case SpvOpTypeStruct:
3542    case SpvOpTypeOpaque:
3543    case SpvOpTypePointer:
3544    case SpvOpTypeFunction:
3545    case SpvOpTypeEvent:
3546    case SpvOpTypeDeviceEvent:
3547    case SpvOpTypeReserveId:
3548    case SpvOpTypeQueue:
3549    case SpvOpTypePipe:
3550       vtn_handle_type(b, opcode, w, count);
3551       break;
3552
3553    case SpvOpConstantTrue:
3554    case SpvOpConstantFalse:
3555    case SpvOpConstant:
3556    case SpvOpConstantComposite:
3557    case SpvOpConstantSampler:
3558    case SpvOpConstantNull:
3559    case SpvOpSpecConstantTrue:
3560    case SpvOpSpecConstantFalse:
3561    case SpvOpSpecConstant:
3562    case SpvOpSpecConstantComposite:
3563    case SpvOpSpecConstantOp:
3564       vtn_handle_constant(b, opcode, w, count);
3565       break;
3566
3567    case SpvOpUndef:
3568    case SpvOpVariable:
3569       vtn_handle_variables(b, opcode, w, count);
3570       break;
3571
3572    default:
3573       return false; /* End of preamble */
3574    }
3575
3576    return true;
3577 }
3578
3579 static bool
3580 vtn_handle_body_instruction(struct vtn_builder *b, SpvOp opcode,
3581                             const uint32_t *w, unsigned count)
3582 {
3583    switch (opcode) {
3584    case SpvOpLabel:
3585       break;
3586
3587    case SpvOpLoopMerge:
3588    case SpvOpSelectionMerge:
3589       /* This is handled by cfg pre-pass and walk_blocks */
3590       break;
3591
3592    case SpvOpUndef: {
3593       struct vtn_value *val = vtn_push_value(b, w[2], vtn_value_type_undef);
3594       val->type = vtn_value(b, w[1], vtn_value_type_type)->type;
3595       break;
3596    }
3597
3598    case SpvOpExtInst:
3599       vtn_handle_extension(b, opcode, w, count);
3600       break;
3601
3602    case SpvOpVariable:
3603    case SpvOpLoad:
3604    case SpvOpStore:
3605    case SpvOpCopyMemory:
3606    case SpvOpCopyMemorySized:
3607    case SpvOpAccessChain:
3608    case SpvOpPtrAccessChain:
3609    case SpvOpInBoundsAccessChain:
3610    case SpvOpArrayLength:
3611       vtn_handle_variables(b, opcode, w, count);
3612       break;
3613
3614    case SpvOpFunctionCall:
3615       vtn_handle_function_call(b, opcode, w, count);
3616       break;
3617
3618    case SpvOpSampledImage:
3619    case SpvOpImage:
3620    case SpvOpImageSampleImplicitLod:
3621    case SpvOpImageSampleExplicitLod:
3622    case SpvOpImageSampleDrefImplicitLod:
3623    case SpvOpImageSampleDrefExplicitLod:
3624    case SpvOpImageSampleProjImplicitLod:
3625    case SpvOpImageSampleProjExplicitLod:
3626    case SpvOpImageSampleProjDrefImplicitLod:
3627    case SpvOpImageSampleProjDrefExplicitLod:
3628    case SpvOpImageFetch:
3629    case SpvOpImageGather:
3630    case SpvOpImageDrefGather:
3631    case SpvOpImageQuerySizeLod:
3632    case SpvOpImageQueryLod:
3633    case SpvOpImageQueryLevels:
3634    case SpvOpImageQuerySamples:
3635       vtn_handle_texture(b, opcode, w, count);
3636       break;
3637
3638    case SpvOpImageRead:
3639    case SpvOpImageWrite:
3640    case SpvOpImageTexelPointer:
3641       vtn_handle_image(b, opcode, w, count);
3642       break;
3643
3644    case SpvOpImageQuerySize: {
3645       struct vtn_pointer *image =
3646          vtn_value(b, w[3], vtn_value_type_pointer)->pointer;
3647       if (image->mode == vtn_variable_mode_image) {
3648          vtn_handle_image(b, opcode, w, count);
3649       } else {
3650          vtn_assert(image->mode == vtn_variable_mode_sampler);
3651          vtn_handle_texture(b, opcode, w, count);
3652       }
3653       break;
3654    }
3655
3656    case SpvOpAtomicLoad:
3657    case SpvOpAtomicExchange:
3658    case SpvOpAtomicCompareExchange:
3659    case SpvOpAtomicCompareExchangeWeak:
3660    case SpvOpAtomicIIncrement:
3661    case SpvOpAtomicIDecrement:
3662    case SpvOpAtomicIAdd:
3663    case SpvOpAtomicISub:
3664    case SpvOpAtomicSMin:
3665    case SpvOpAtomicUMin:
3666    case SpvOpAtomicSMax:
3667    case SpvOpAtomicUMax:
3668    case SpvOpAtomicAnd:
3669    case SpvOpAtomicOr:
3670    case SpvOpAtomicXor: {
3671       struct vtn_value *pointer = vtn_untyped_value(b, w[3]);
3672       if (pointer->value_type == vtn_value_type_image_pointer) {
3673          vtn_handle_image(b, opcode, w, count);
3674       } else {
3675          vtn_assert(pointer->value_type == vtn_value_type_pointer);
3676          vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
3677       }
3678       break;
3679    }
3680
3681    case SpvOpAtomicStore: {
3682       struct vtn_value *pointer = vtn_untyped_value(b, w[1]);
3683       if (pointer->value_type == vtn_value_type_image_pointer) {
3684          vtn_handle_image(b, opcode, w, count);
3685       } else {
3686          vtn_assert(pointer->value_type == vtn_value_type_pointer);
3687          vtn_handle_ssbo_or_shared_atomic(b, opcode, w, count);
3688       }
3689       break;
3690    }
3691
3692    case SpvOpSelect: {
3693       /* Handle OpSelect up-front here because it needs to be able to handle
3694        * pointers and not just regular vectors and scalars.
3695        */
3696       struct vtn_value *res_val = vtn_untyped_value(b, w[2]);
3697       struct vtn_value *sel_val = vtn_untyped_value(b, w[3]);
3698       struct vtn_value *obj1_val = vtn_untyped_value(b, w[4]);
3699       struct vtn_value *obj2_val = vtn_untyped_value(b, w[5]);
3700
3701       const struct glsl_type *sel_type;
3702       switch (res_val->type->base_type) {
3703       case vtn_base_type_scalar:
3704          sel_type = glsl_bool_type();
3705          break;
3706       case vtn_base_type_vector:
3707          sel_type = glsl_vector_type(GLSL_TYPE_BOOL, res_val->type->length);
3708          break;
3709       case vtn_base_type_pointer:
3710          /* We need to have actual storage for pointer types */
3711          vtn_fail_if(res_val->type->type == NULL,
3712                      "Invalid pointer result type for OpSelect");
3713          sel_type = glsl_bool_type();
3714          break;
3715       default:
3716          vtn_fail("Result type of OpSelect must be a scalar, vector, or pointer");
3717       }
3718
3719       if (unlikely(sel_val->type->type != sel_type)) {
3720          if (sel_val->type->type == glsl_bool_type()) {
3721             /* This case is illegal but some older versions of GLSLang produce
3722              * it.  The GLSLang issue was fixed on March 30, 2017:
3723              *
3724              * https://github.com/KhronosGroup/glslang/issues/809
3725              *
3726              * Unfortunately, there are applications in the wild which are
3727              * shipping with this bug so it isn't nice to fail on them so we
3728              * throw a warning instead.  It's not actually a problem for us as
3729              * nir_builder will just splat the condition out which is most
3730              * likely what the client wanted anyway.
3731              */
3732             vtn_warn("Condition type of OpSelect must have the same number "
3733                      "of components as Result Type");
3734          } else {
3735             vtn_fail("Condition type of OpSelect must be a scalar or vector "
3736                      "of Boolean type. It must have the same number of "
3737                      "components as Result Type");
3738          }
3739       }
3740
3741       vtn_fail_if(obj1_val->type != res_val->type ||
3742                   obj2_val->type != res_val->type,
3743                   "Object types must match the result type in OpSelect");
3744
3745       struct vtn_type *res_type = vtn_value(b, w[1], vtn_value_type_type)->type;
3746       struct vtn_ssa_value *ssa = vtn_create_ssa_value(b, res_type->type);
3747       ssa->def = nir_bcsel(&b->nb, vtn_ssa_value(b, w[3])->def,
3748                                    vtn_ssa_value(b, w[4])->def,
3749                                    vtn_ssa_value(b, w[5])->def);
3750       vtn_push_ssa(b, w[2], res_type, ssa);
3751       break;
3752    }
3753
3754    case SpvOpSNegate:
3755    case SpvOpFNegate:
3756    case SpvOpNot:
3757    case SpvOpAny:
3758    case SpvOpAll:
3759    case SpvOpConvertFToU:
3760    case SpvOpConvertFToS:
3761    case SpvOpConvertSToF:
3762    case SpvOpConvertUToF:
3763    case SpvOpUConvert:
3764    case SpvOpSConvert:
3765    case SpvOpFConvert:
3766    case SpvOpQuantizeToF16:
3767    case SpvOpConvertPtrToU:
3768    case SpvOpConvertUToPtr:
3769    case SpvOpPtrCastToGeneric:
3770    case SpvOpGenericCastToPtr:
3771    case SpvOpBitcast:
3772    case SpvOpIsNan:
3773    case SpvOpIsInf:
3774    case SpvOpIsFinite:
3775    case SpvOpIsNormal:
3776    case SpvOpSignBitSet:
3777    case SpvOpLessOrGreater:
3778    case SpvOpOrdered:
3779    case SpvOpUnordered:
3780    case SpvOpIAdd:
3781    case SpvOpFAdd:
3782    case SpvOpISub:
3783    case SpvOpFSub:
3784    case SpvOpIMul:
3785    case SpvOpFMul:
3786    case SpvOpUDiv:
3787    case SpvOpSDiv:
3788    case SpvOpFDiv:
3789    case SpvOpUMod:
3790    case SpvOpSRem:
3791    case SpvOpSMod:
3792    case SpvOpFRem:
3793    case SpvOpFMod:
3794    case SpvOpVectorTimesScalar:
3795    case SpvOpDot:
3796    case SpvOpIAddCarry:
3797    case SpvOpISubBorrow:
3798    case SpvOpUMulExtended:
3799    case SpvOpSMulExtended:
3800    case SpvOpShiftRightLogical:
3801    case SpvOpShiftRightArithmetic:
3802    case SpvOpShiftLeftLogical:
3803    case SpvOpLogicalEqual:
3804    case SpvOpLogicalNotEqual:
3805    case SpvOpLogicalOr:
3806    case SpvOpLogicalAnd:
3807    case SpvOpLogicalNot:
3808    case SpvOpBitwiseOr:
3809    case SpvOpBitwiseXor:
3810    case SpvOpBitwiseAnd:
3811    case SpvOpIEqual:
3812    case SpvOpFOrdEqual:
3813    case SpvOpFUnordEqual:
3814    case SpvOpINotEqual:
3815    case SpvOpFOrdNotEqual:
3816    case SpvOpFUnordNotEqual:
3817    case SpvOpULessThan:
3818    case SpvOpSLessThan:
3819    case SpvOpFOrdLessThan:
3820    case SpvOpFUnordLessThan:
3821    case SpvOpUGreaterThan:
3822    case SpvOpSGreaterThan:
3823    case SpvOpFOrdGreaterThan:
3824    case SpvOpFUnordGreaterThan:
3825    case SpvOpULessThanEqual:
3826    case SpvOpSLessThanEqual:
3827    case SpvOpFOrdLessThanEqual:
3828    case SpvOpFUnordLessThanEqual:
3829    case SpvOpUGreaterThanEqual:
3830    case SpvOpSGreaterThanEqual:
3831    case SpvOpFOrdGreaterThanEqual:
3832    case SpvOpFUnordGreaterThanEqual:
3833    case SpvOpDPdx:
3834    case SpvOpDPdy:
3835    case SpvOpFwidth:
3836    case SpvOpDPdxFine:
3837    case SpvOpDPdyFine:
3838    case SpvOpFwidthFine:
3839    case SpvOpDPdxCoarse:
3840    case SpvOpDPdyCoarse:
3841    case SpvOpFwidthCoarse:
3842    case SpvOpBitFieldInsert:
3843    case SpvOpBitFieldSExtract:
3844    case SpvOpBitFieldUExtract:
3845    case SpvOpBitReverse:
3846    case SpvOpBitCount:
3847    case SpvOpTranspose:
3848    case SpvOpOuterProduct:
3849    case SpvOpMatrixTimesScalar:
3850    case SpvOpVectorTimesMatrix:
3851    case SpvOpMatrixTimesVector:
3852    case SpvOpMatrixTimesMatrix:
3853       vtn_handle_alu(b, opcode, w, count);
3854       break;
3855
3856    case SpvOpVectorExtractDynamic:
3857    case SpvOpVectorInsertDynamic:
3858    case SpvOpVectorShuffle:
3859    case SpvOpCompositeConstruct:
3860    case SpvOpCompositeExtract:
3861    case SpvOpCompositeInsert:
3862    case SpvOpCopyObject:
3863       vtn_handle_composite(b, opcode, w, count);
3864       break;
3865
3866    case SpvOpEmitVertex:
3867    case SpvOpEndPrimitive:
3868    case SpvOpEmitStreamVertex:
3869    case SpvOpEndStreamPrimitive:
3870    case SpvOpControlBarrier:
3871    case SpvOpMemoryBarrier:
3872       vtn_handle_barrier(b, opcode, w, count);
3873       break;
3874
3875    default:
3876       vtn_fail("Unhandled opcode");
3877    }
3878
3879    return true;
3880 }
3881
3882 nir_function *
3883 spirv_to_nir(const uint32_t *words, size_t word_count,
3884              struct nir_spirv_specialization *spec, unsigned num_spec,
3885              gl_shader_stage stage, const char *entry_point_name,
3886              const struct spirv_to_nir_options *options,
3887              const nir_shader_compiler_options *nir_options)
3888 {
3889    /* Initialize the stn_builder object */
3890    struct vtn_builder *b = rzalloc(NULL, struct vtn_builder);
3891    b->spirv = words;
3892    b->spirv_word_count = word_count;
3893    b->file = NULL;
3894    b->line = -1;
3895    b->col = -1;
3896    exec_list_make_empty(&b->functions);
3897    b->entry_point_stage = stage;
3898    b->entry_point_name = entry_point_name;
3899    b->options = options;
3900
3901    /* See also _vtn_fail() */
3902    if (setjmp(b->fail_jump)) {
3903       ralloc_free(b);
3904       return NULL;
3905    }
3906
3907    const uint32_t *word_end = words + word_count;
3908
3909    /* Handle the SPIR-V header (first 4 dwords)  */
3910    vtn_assert(word_count > 5);
3911
3912    vtn_assert(words[0] == SpvMagicNumber);
3913    vtn_assert(words[1] >= 0x10000);
3914    /* words[2] == generator magic */
3915    unsigned value_id_bound = words[3];
3916    vtn_assert(words[4] == 0);
3917
3918    words+= 5;
3919
3920    b->value_id_bound = value_id_bound;
3921    b->values = rzalloc_array(b, struct vtn_value, value_id_bound);
3922
3923    /* Handle all the preamble instructions */
3924    words = vtn_foreach_instruction(b, words, word_end,
3925                                    vtn_handle_preamble_instruction);
3926
3927    if (b->entry_point == NULL) {
3928       vtn_fail("Entry point not found");
3929       ralloc_free(b);
3930       return NULL;
3931    }
3932
3933    b->shader = nir_shader_create(b, stage, nir_options, NULL);
3934
3935    /* Set shader info defaults */
3936    b->shader->info.gs.invocations = 1;
3937
3938    /* Parse execution modes */
3939    vtn_foreach_execution_mode(b, b->entry_point,
3940                               vtn_handle_execution_mode, NULL);
3941
3942    b->specializations = spec;
3943    b->num_specializations = num_spec;
3944
3945    /* Handle all variable, type, and constant instructions */
3946    words = vtn_foreach_instruction(b, words, word_end,
3947                                    vtn_handle_variable_or_type_instruction);
3948
3949    /* Set types on all vtn_values */
3950    vtn_foreach_instruction(b, words, word_end, vtn_set_instruction_result_type);
3951
3952    vtn_build_cfg(b, words, word_end);
3953
3954    assert(b->entry_point->value_type == vtn_value_type_function);
3955    b->entry_point->func->referenced = true;
3956
3957    bool progress;
3958    do {
3959       progress = false;
3960       foreach_list_typed(struct vtn_function, func, node, &b->functions) {
3961          if (func->referenced && !func->emitted) {
3962             b->const_table = _mesa_hash_table_create(b, _mesa_hash_pointer,
3963                                                      _mesa_key_pointer_equal);
3964
3965             vtn_function_emit(b, func, vtn_handle_body_instruction);
3966             progress = true;
3967          }
3968       }
3969    } while (progress);
3970
3971    vtn_assert(b->entry_point->value_type == vtn_value_type_function);
3972    nir_function *entry_point = b->entry_point->func->impl->function;
3973    vtn_assert(entry_point);
3974
3975    /* Unparent the shader from the vtn_builder before we delete the builder */
3976    ralloc_steal(NULL, b->shader);
3977
3978    ralloc_free(b);
3979
3980    return entry_point;
3981 }