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