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