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