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