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