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