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