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