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