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