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