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