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