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