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