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