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