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