e331bcdabc31d0f002525aa4929fa809b727b402
[mesa.git] / src / glsl / nir / nir_lower_vars_to_ssa.c
1 /*
2 * Copyright © 2014 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 "nir.h"
29
30 struct deref_node {
31 struct deref_node *parent;
32 const struct glsl_type *type;
33
34 bool lower_to_ssa;
35
36 struct set *loads;
37 struct set *stores;
38 struct set *copies;
39
40 nir_ssa_def **def_stack;
41 nir_ssa_def **def_stack_tail;
42
43 struct deref_node *wildcard;
44 struct deref_node *indirect;
45 struct deref_node *children[0];
46 };
47
48 struct lower_variables_state {
49 void *mem_ctx;
50 void *dead_ctx;
51 nir_function_impl *impl;
52
53 /* A hash table mapping variables to deref_node data */
54 struct hash_table *deref_var_nodes;
55
56 /* A hash table mapping fully-qualified direct dereferences, i.e.
57 * dereferences with no indirect or wildcard array dereferences, to
58 * deref_node data.
59 *
60 * At the moment, we only lower loads, stores, and copies that can be
61 * trivially lowered to loads and stores, i.e. copies with no indirects
62 * and no wildcards. If a part of a variable that is being loaded from
63 * and/or stored into is also involved in a copy operation with
64 * wildcards, then we lower that copy operation to loads and stores, but
65 * otherwise we leave copies with wildcards alone. Since the only derefs
66 * used in these loads, stores, and trivial copies are ones with no
67 * wildcards and no indirects, these are precisely the derefs that we
68 * can actually consider lowering.
69 */
70 struct hash_table *direct_deref_nodes;
71
72 /* Controls whether get_deref_node will add variables to the
73 * direct_deref_nodes table. This is turned on when we are initially
74 * scanning for load/store instructions. It is then turned off so we
75 * don't accidentally change the direct_deref_nodes table while we're
76 * iterating throug it.
77 */
78 bool add_to_direct_deref_nodes;
79
80 /* A hash table mapping phi nodes to deref_state data */
81 struct hash_table *phi_table;
82 };
83
84 /* The following two functions implement a hash and equality check for
85 * variable dreferences. When the hash or equality function encounters an
86 * array, all indirects are treated as equal and are never equal to a
87 * direct dereference or a wildcard.
88 */
89 static uint32_t
90 hash_deref(const void *void_deref)
91 {
92 uint32_t hash = _mesa_fnv32_1a_offset_bias;
93
94 const nir_deref_var *deref_var = void_deref;
95 hash = _mesa_fnv32_1a_accumulate(hash, deref_var->var);
96
97 for (const nir_deref *deref = deref_var->deref.child;
98 deref; deref = deref->child) {
99 switch (deref->deref_type) {
100 case nir_deref_type_array: {
101 nir_deref_array *deref_array = nir_deref_as_array(deref);
102
103 hash = _mesa_fnv32_1a_accumulate(hash, deref_array->deref_array_type);
104
105 if (deref_array->deref_array_type == nir_deref_array_type_direct)
106 hash = _mesa_fnv32_1a_accumulate(hash, deref_array->base_offset);
107 break;
108 }
109 case nir_deref_type_struct: {
110 nir_deref_struct *deref_struct = nir_deref_as_struct(deref);
111 hash = _mesa_fnv32_1a_accumulate(hash, deref_struct->index);
112 break;
113 }
114 default:
115 assert("Invalid deref chain");
116 }
117 }
118
119 return hash;
120 }
121
122 static bool
123 derefs_equal(const void *void_a, const void *void_b)
124 {
125 const nir_deref_var *a_var = void_a;
126 const nir_deref_var *b_var = void_b;
127
128 if (a_var->var != b_var->var)
129 return false;
130
131 for (const nir_deref *a = a_var->deref.child, *b = b_var->deref.child;
132 a != NULL; a = a->child, b = b->child) {
133 if (a->deref_type != b->deref_type)
134 return false;
135
136 switch (a->deref_type) {
137 case nir_deref_type_array: {
138 nir_deref_array *a_arr = nir_deref_as_array(a);
139 nir_deref_array *b_arr = nir_deref_as_array(b);
140
141 if (a_arr->deref_array_type != b_arr->deref_array_type)
142 return false;
143
144 if (a_arr->deref_array_type == nir_deref_array_type_direct &&
145 a_arr->base_offset != b_arr->base_offset)
146 return false;
147 break;
148 }
149 case nir_deref_type_struct:
150 if (nir_deref_as_struct(a)->index != nir_deref_as_struct(b)->index)
151 return false;
152 break;
153 default:
154 assert("Invalid deref chain");
155 return false;
156 }
157
158 assert((a->child == NULL) == (b->child == NULL));
159 if((a->child == NULL) != (b->child == NULL))
160 return false;
161 }
162
163 return true;
164 }
165
166 static int
167 type_get_length(const struct glsl_type *type)
168 {
169 switch (glsl_get_base_type(type)) {
170 case GLSL_TYPE_STRUCT:
171 case GLSL_TYPE_ARRAY:
172 return glsl_get_length(type);
173 case GLSL_TYPE_FLOAT:
174 case GLSL_TYPE_INT:
175 case GLSL_TYPE_UINT:
176 case GLSL_TYPE_BOOL:
177 if (glsl_type_is_matrix(type))
178 return glsl_get_matrix_columns(type);
179 else
180 return glsl_get_vector_elements(type);
181 default:
182 unreachable("Invalid deref base type");
183 }
184 }
185
186 static struct deref_node *
187 deref_node_create(struct deref_node *parent,
188 const struct glsl_type *type, void *mem_ctx)
189 {
190 size_t size = sizeof(struct deref_node) +
191 type_get_length(type) * sizeof(struct deref_node *);
192
193 struct deref_node *node = rzalloc_size(mem_ctx, size);
194 node->type = type;
195 node->parent = parent;
196
197 return node;
198 }
199
200 /* Returns the deref node associated with the given variable. This will be
201 * the root of the tree representing all of the derefs of the given variable.
202 */
203 static struct deref_node *
204 get_deref_node_for_var(nir_variable *var, struct lower_variables_state *state)
205 {
206 struct deref_node *node;
207
208 struct hash_entry *var_entry =
209 _mesa_hash_table_search(state->deref_var_nodes, var);
210
211 if (var_entry) {
212 return var_entry->data;
213 } else {
214 node = deref_node_create(NULL, var->type, state->dead_ctx);
215 _mesa_hash_table_insert(state->deref_var_nodes, var, node);
216 return node;
217 }
218 }
219
220 /* Gets the deref_node for the given deref chain and creates it if it
221 * doesn't yet exist. If the deref is fully-qualified and direct and
222 * state->add_to_direct_deref_nodes is true, it will be added to the hash
223 * table of of fully-qualified direct derefs.
224 */
225 static struct deref_node *
226 get_deref_node(nir_deref_var *deref, struct lower_variables_state *state)
227 {
228 bool is_direct = true;
229
230 /* Start at the base of the chain. */
231 struct deref_node *node = get_deref_node_for_var(deref->var, state);
232 assert(deref->deref.type == node->type);
233
234 for (nir_deref *tail = deref->deref.child; tail; tail = tail->child) {
235 switch (tail->deref_type) {
236 case nir_deref_type_struct: {
237 nir_deref_struct *deref_struct = nir_deref_as_struct(tail);
238
239 assert(deref_struct->index < type_get_length(node->type));
240
241 if (node->children[deref_struct->index] == NULL)
242 node->children[deref_struct->index] =
243 deref_node_create(node, tail->type, state->dead_ctx);
244
245 node = node->children[deref_struct->index];
246 break;
247 }
248
249 case nir_deref_type_array: {
250 nir_deref_array *arr = nir_deref_as_array(tail);
251
252 switch (arr->deref_array_type) {
253 case nir_deref_array_type_direct:
254 /* This is possible if a loop unrolls and generates an
255 * out-of-bounds offset. We need to handle this at least
256 * somewhat gracefully.
257 */
258 if (arr->base_offset >= type_get_length(node->type))
259 return NULL;
260
261 if (node->children[arr->base_offset] == NULL)
262 node->children[arr->base_offset] =
263 deref_node_create(node, tail->type, state->dead_ctx);
264
265 node = node->children[arr->base_offset];
266 break;
267
268 case nir_deref_array_type_indirect:
269 if (node->indirect == NULL)
270 node->indirect = deref_node_create(node, tail->type,
271 state->dead_ctx);
272
273 node = node->indirect;
274 is_direct = false;
275 break;
276
277 case nir_deref_array_type_wildcard:
278 if (node->wildcard == NULL)
279 node->wildcard = deref_node_create(node, tail->type,
280 state->dead_ctx);
281
282 node = node->wildcard;
283 is_direct = false;
284 break;
285
286 default:
287 unreachable("Invalid array deref type");
288 }
289 break;
290 }
291 default:
292 unreachable("Invalid deref type");
293 }
294 }
295
296 assert(node);
297
298 if (is_direct && state->add_to_direct_deref_nodes)
299 _mesa_hash_table_insert(state->direct_deref_nodes, deref, node);
300
301 return node;
302 }
303
304 /* \sa foreach_deref_node_match */
305 static bool
306 foreach_deref_node_worker(struct deref_node *node, nir_deref *deref,
307 bool (* cb)(struct deref_node *node,
308 struct lower_variables_state *state),
309 struct lower_variables_state *state)
310 {
311 if (deref->child == NULL) {
312 return cb(node, state);
313 } else {
314 switch (deref->child->deref_type) {
315 case nir_deref_type_array: {
316 nir_deref_array *arr = nir_deref_as_array(deref->child);
317 assert(arr->deref_array_type == nir_deref_array_type_direct);
318 if (node->children[arr->base_offset] &&
319 !foreach_deref_node_worker(node->children[arr->base_offset],
320 deref->child, cb, state))
321 return false;
322
323 if (node->wildcard &&
324 !foreach_deref_node_worker(node->wildcard,
325 deref->child, cb, state))
326 return false;
327
328 return true;
329 }
330
331 case nir_deref_type_struct: {
332 nir_deref_struct *str = nir_deref_as_struct(deref->child);
333 return foreach_deref_node_worker(node->children[str->index],
334 deref->child, cb, state);
335 }
336
337 default:
338 unreachable("Invalid deref child type");
339 }
340 }
341 }
342
343 /* Walks over every "matching" deref_node and calls the callback. A node
344 * is considered to "match" if either refers to that deref or matches up t
345 * a wildcard. In other words, the following would match a[6].foo[3].bar:
346 *
347 * a[6].foo[3].bar
348 * a[*].foo[3].bar
349 * a[6].foo[*].bar
350 * a[*].foo[*].bar
351 *
352 * The given deref must be a full-length and fully qualified (no wildcards
353 * or indirects) deref chain.
354 */
355 static bool
356 foreach_deref_node_match(nir_deref_var *deref,
357 bool (* cb)(struct deref_node *node,
358 struct lower_variables_state *state),
359 struct lower_variables_state *state)
360 {
361 nir_deref_var var_deref = *deref;
362 var_deref.deref.child = NULL;
363 struct deref_node *node = get_deref_node(&var_deref, state);
364
365 if (node == NULL)
366 return false;
367
368 return foreach_deref_node_worker(node, &deref->deref, cb, state);
369 }
370
371 /* \sa deref_may_be_aliased */
372 static bool
373 deref_may_be_aliased_node(struct deref_node *node, nir_deref *deref,
374 struct lower_variables_state *state)
375 {
376 if (deref->child == NULL) {
377 return false;
378 } else {
379 switch (deref->child->deref_type) {
380 case nir_deref_type_array: {
381 nir_deref_array *arr = nir_deref_as_array(deref->child);
382 if (arr->deref_array_type == nir_deref_array_type_indirect)
383 return true;
384
385 assert(arr->deref_array_type == nir_deref_array_type_direct);
386
387 if (node->children[arr->base_offset] &&
388 deref_may_be_aliased_node(node->children[arr->base_offset],
389 deref->child, state))
390 return true;
391
392 if (node->wildcard &&
393 deref_may_be_aliased_node(node->wildcard, deref->child, state))
394 return true;
395
396 return false;
397 }
398
399 case nir_deref_type_struct: {
400 nir_deref_struct *str = nir_deref_as_struct(deref->child);
401 if (node->children[str->index]) {
402 return deref_may_be_aliased_node(node->children[str->index],
403 deref->child, state);
404 } else {
405 return false;
406 }
407 }
408
409 default:
410 unreachable("Invalid nir_deref child type");
411 }
412 }
413 }
414
415 /* Returns true if there are no indirects that can ever touch this deref.
416 *
417 * For example, if the given deref is a[6].foo, then any uses of a[i].foo
418 * would cause this to return false, but a[i].bar would not affect it
419 * because it's a different structure member. A var_copy involving of
420 * a[*].bar also doesn't affect it because that can be lowered to entirely
421 * direct load/stores.
422 *
423 * We only support asking this question about fully-qualified derefs.
424 * Obviously, it's pointless to ask this about indirects, but we also
425 * rule-out wildcards. Handling Wildcard dereferences would involve
426 * checking each array index to make sure that there aren't any indirect
427 * references.
428 */
429 static bool
430 deref_may_be_aliased(nir_deref_var *deref,
431 struct lower_variables_state *state)
432 {
433 return deref_may_be_aliased_node(get_deref_node_for_var(deref->var, state),
434 &deref->deref, state);
435 }
436
437 static void
438 register_load_instr(nir_intrinsic_instr *load_instr,
439 struct lower_variables_state *state)
440 {
441 struct deref_node *node = get_deref_node(load_instr->variables[0], state);
442 if (node == NULL)
443 return;
444
445 if (node->loads == NULL)
446 node->loads = _mesa_set_create(state->dead_ctx,
447 _mesa_key_pointer_equal);
448
449 _mesa_set_add(node->loads, _mesa_hash_pointer(load_instr), load_instr);
450 }
451
452 static void
453 register_store_instr(nir_intrinsic_instr *store_instr,
454 struct lower_variables_state *state)
455 {
456 struct deref_node *node = get_deref_node(store_instr->variables[0], state);
457 if (node == NULL)
458 return;
459
460 if (node->stores == NULL)
461 node->stores = _mesa_set_create(state->dead_ctx,
462 _mesa_key_pointer_equal);
463
464 _mesa_set_add(node->stores, _mesa_hash_pointer(store_instr), store_instr);
465 }
466
467 static void
468 register_copy_instr(nir_intrinsic_instr *copy_instr,
469 struct lower_variables_state *state)
470 {
471 for (unsigned idx = 0; idx < 2; idx++) {
472 struct deref_node *node =
473 get_deref_node(copy_instr->variables[idx], state);
474
475 if (node == NULL)
476 continue;
477
478 if (node->copies == NULL)
479 node->copies = _mesa_set_create(state->dead_ctx,
480 _mesa_key_pointer_equal);
481
482 _mesa_set_add(node->copies, _mesa_hash_pointer(copy_instr), copy_instr);
483 }
484 }
485
486 /* Registers all variable uses in the given block. */
487 static bool
488 register_variable_uses_block(nir_block *block, void *void_state)
489 {
490 struct lower_variables_state *state = void_state;
491
492 nir_foreach_instr_safe(block, instr) {
493 if (instr->type != nir_instr_type_intrinsic)
494 continue;
495
496 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
497
498 switch (intrin->intrinsic) {
499 case nir_intrinsic_load_var:
500 register_load_instr(intrin, state);
501 break;
502
503 case nir_intrinsic_store_var:
504 register_store_instr(intrin, state);
505 break;
506
507 case nir_intrinsic_copy_var:
508 register_copy_instr(intrin, state);
509 break;
510
511 default:
512 continue;
513 }
514 }
515
516 return true;
517 }
518
519 /* Walks over all of the copy instructions to or from the given deref_node
520 * and lowers them to load/store intrinsics.
521 */
522 static bool
523 lower_copies_to_load_store(struct deref_node *node,
524 struct lower_variables_state *state)
525 {
526 if (!node->copies)
527 return true;
528
529 struct set_entry *copy_entry;
530 set_foreach(node->copies, copy_entry) {
531 nir_intrinsic_instr *copy = (void *)copy_entry->key;
532
533 nir_lower_var_copy_instr(copy, state->mem_ctx);
534
535 for (unsigned i = 0; i < 2; ++i) {
536 struct deref_node *arg_node =
537 get_deref_node(copy->variables[i], state);
538
539 if (arg_node == NULL)
540 continue;
541
542 struct set_entry *arg_entry = _mesa_set_search(arg_node->copies,
543 copy_entry->hash,
544 copy);
545 assert(arg_entry);
546 _mesa_set_remove(node->copies, arg_entry);
547 }
548
549 nir_instr_remove(&copy->instr);
550 }
551
552 return true;
553 }
554
555 /* Returns a load_const instruction that represents the constant
556 * initializer for the given deref chain. The caller is responsible for
557 * ensuring that there actually is a constant initializer.
558 */
559 static nir_load_const_instr *
560 get_const_initializer_load(const nir_deref_var *deref,
561 struct lower_variables_state *state)
562 {
563 nir_constant *constant = deref->var->constant_initializer;
564 const nir_deref *tail = &deref->deref;
565 unsigned matrix_offset = 0;
566 while (tail->child) {
567 switch (tail->child->deref_type) {
568 case nir_deref_type_array: {
569 nir_deref_array *arr = nir_deref_as_array(tail->child);
570 assert(arr->deref_array_type == nir_deref_array_type_direct);
571 if (glsl_type_is_matrix(tail->type)) {
572 assert(arr->deref.child == NULL);
573 matrix_offset = arr->base_offset;
574 } else {
575 constant = constant->elements[arr->base_offset];
576 }
577 break;
578 }
579
580 case nir_deref_type_struct: {
581 constant = constant->elements[nir_deref_as_struct(tail->child)->index];
582 break;
583 }
584
585 default:
586 unreachable("Invalid deref child type");
587 }
588
589 tail = tail->child;
590 }
591
592 nir_load_const_instr *load =
593 nir_load_const_instr_create(state->mem_ctx,
594 glsl_get_vector_elements(tail->type));
595
596 matrix_offset *= load->def.num_components;
597 for (unsigned i = 0; i < load->def.num_components; i++) {
598 switch (glsl_get_base_type(tail->type)) {
599 case GLSL_TYPE_FLOAT:
600 case GLSL_TYPE_INT:
601 case GLSL_TYPE_UINT:
602 load->value.u[i] = constant->value.u[matrix_offset + i];
603 break;
604 case GLSL_TYPE_BOOL:
605 load->value.u[i] = constant->value.u[matrix_offset + i] ?
606 NIR_TRUE : NIR_FALSE;
607 break;
608 default:
609 unreachable("Invalid immediate type");
610 }
611 }
612
613 return load;
614 }
615
616 /** Pushes an SSA def onto the def stack for the given node
617 *
618 * Each node is potentially associated with a stack of SSA definitions.
619 * This stack is used for determining what SSA definition reaches a given
620 * point in the program for variable renaming. The stack is always kept in
621 * dominance-order with at most one SSA def per block. If the SSA
622 * definition on the top of the stack is in the same block as the one being
623 * pushed, the top element is replaced.
624 */
625 static void
626 def_stack_push(struct deref_node *node, nir_ssa_def *def,
627 struct lower_variables_state *state)
628 {
629 if (node->def_stack == NULL) {
630 node->def_stack = ralloc_array(state->dead_ctx, nir_ssa_def *,
631 state->impl->num_blocks);
632 node->def_stack_tail = node->def_stack - 1;
633 }
634
635 if (node->def_stack_tail >= node->def_stack) {
636 nir_ssa_def *top_def = *node->def_stack_tail;
637
638 if (def->parent_instr->block == top_def->parent_instr->block) {
639 /* They're in the same block, just replace the top */
640 *node->def_stack_tail = def;
641 return;
642 }
643 }
644
645 *(++node->def_stack_tail) = def;
646 }
647
648 /* Pop the top of the def stack if it's in the given block */
649 static void
650 def_stack_pop_if_in_block(struct deref_node *node, nir_block *block)
651 {
652 /* If we're popping, then we have presumably pushed at some time in the
653 * past so this should exist.
654 */
655 assert(node->def_stack != NULL);
656
657 /* The stack is already empty. Do nothing. */
658 if (node->def_stack_tail < node->def_stack)
659 return;
660
661 nir_ssa_def *def = *node->def_stack_tail;
662 if (def->parent_instr->block == block)
663 node->def_stack_tail--;
664 }
665
666 /** Retrieves the SSA definition on the top of the stack for the given
667 * node, if one exists. If the stack is empty, then we return the constant
668 * initializer (if it exists) or an SSA undef.
669 */
670 static nir_ssa_def *
671 get_ssa_def_for_block(struct deref_node *node, nir_block *block,
672 struct lower_variables_state *state)
673 {
674 /* If we have something on the stack, go ahead and return it. We're
675 * assuming that the top of the stack dominates the given block.
676 */
677 if (node->def_stack && node->def_stack_tail >= node->def_stack)
678 return *node->def_stack_tail;
679
680 /* If we got here then we don't have a definition that dominates the
681 * given block. This means that we need to add an undef and use that.
682 */
683 nir_ssa_undef_instr *undef =
684 nir_ssa_undef_instr_create(state->mem_ctx,
685 glsl_get_vector_elements(node->type));
686 nir_instr_insert_before_cf_list(&state->impl->body, &undef->instr);
687 def_stack_push(node, &undef->def, state);
688 return &undef->def;
689 }
690
691 /* Given a block and one of its predecessors, this function fills in the
692 * souces of the phi nodes to take SSA defs from the given predecessor.
693 * This function must be called exactly once per block/predecessor pair.
694 */
695 static void
696 add_phi_sources(nir_block *block, nir_block *pred,
697 struct lower_variables_state *state)
698 {
699 nir_foreach_instr(block, instr) {
700 if (instr->type != nir_instr_type_phi)
701 break;
702
703 nir_phi_instr *phi = nir_instr_as_phi(instr);
704
705 struct hash_entry *entry =
706 _mesa_hash_table_search(state->phi_table, phi);
707 if (!entry)
708 continue;
709
710 struct deref_node *node = entry->data;
711
712 nir_phi_src *src = ralloc(state->mem_ctx, nir_phi_src);
713 src->pred = pred;
714 src->src.is_ssa = true;
715 src->src.ssa = get_ssa_def_for_block(node, pred, state);
716
717 _mesa_set_add(src->src.ssa->uses, _mesa_hash_pointer(instr), instr);
718
719 exec_list_push_tail(&phi->srcs, &src->node);
720 }
721 }
722
723 /* Performs variable renaming by doing a DFS of the dominance tree
724 *
725 * This algorithm is very similar to the one outlined in "Efficiently
726 * Computing Static Single Assignment Form and the Control Dependence
727 * Graph" by Cytron et. al. The primary difference is that we only put one
728 * SSA def on the stack per block.
729 */
730 static bool
731 rename_variables_block(nir_block *block, struct lower_variables_state *state)
732 {
733 nir_foreach_instr_safe(block, instr) {
734 if (instr->type == nir_instr_type_phi) {
735 nir_phi_instr *phi = nir_instr_as_phi(instr);
736
737 struct hash_entry *entry =
738 _mesa_hash_table_search(state->phi_table, phi);
739
740 /* This can happen if we already have phi nodes in the program
741 * that were not created in this pass.
742 */
743 if (!entry)
744 continue;
745
746 struct deref_node *node = entry->data;
747
748 def_stack_push(node, &phi->dest.ssa, state);
749 } else if (instr->type == nir_instr_type_intrinsic) {
750 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
751
752 switch (intrin->intrinsic) {
753 case nir_intrinsic_load_var: {
754 struct deref_node *node =
755 get_deref_node(intrin->variables[0], state);
756
757 if (node == NULL) {
758 /* If we hit this path then we are referencing an invalid
759 * value. Most likely, we unrolled something and are
760 * reading past the end of some array. In any case, this
761 * should result in an undefined value.
762 */
763 nir_ssa_undef_instr *undef =
764 nir_ssa_undef_instr_create(state->mem_ctx,
765 intrin->num_components);
766
767 nir_instr_insert_before(&intrin->instr, &undef->instr);
768 nir_instr_remove(&intrin->instr);
769
770 nir_src new_src = {
771 .is_ssa = true,
772 .ssa = &undef->def,
773 };
774
775 nir_ssa_def_rewrite_uses(&intrin->dest.ssa, new_src,
776 state->mem_ctx);
777 continue;
778 }
779
780 if (!node->lower_to_ssa)
781 continue;
782
783 nir_alu_instr *mov = nir_alu_instr_create(state->mem_ctx,
784 nir_op_imov);
785 mov->src[0].src.is_ssa = true;
786 mov->src[0].src.ssa = get_ssa_def_for_block(node, block, state);
787 for (unsigned i = intrin->num_components; i < 4; i++)
788 mov->src[0].swizzle[i] = 0;
789
790 assert(intrin->dest.is_ssa);
791
792 mov->dest.write_mask = (1 << intrin->num_components) - 1;
793 mov->dest.dest.is_ssa = true;
794 nir_ssa_def_init(&mov->instr, &mov->dest.dest.ssa,
795 intrin->num_components, NULL);
796
797 nir_instr_insert_before(&intrin->instr, &mov->instr);
798 nir_instr_remove(&intrin->instr);
799
800 nir_src new_src = {
801 .is_ssa = true,
802 .ssa = &mov->dest.dest.ssa,
803 };
804
805 nir_ssa_def_rewrite_uses(&intrin->dest.ssa, new_src,
806 state->mem_ctx);
807 break;
808 }
809
810 case nir_intrinsic_store_var: {
811 struct deref_node *node =
812 get_deref_node(intrin->variables[0], state);
813
814 if (node == NULL) {
815 /* Probably an out-of-bounds array store. That should be a
816 * no-op. */
817 nir_instr_remove(&intrin->instr);
818 continue;
819 }
820
821 if (!node->lower_to_ssa)
822 continue;
823
824 assert(intrin->num_components ==
825 glsl_get_vector_elements(node->type));
826
827 assert(intrin->src[0].is_ssa);
828
829 nir_alu_instr *mov = nir_alu_instr_create(state->mem_ctx,
830 nir_op_imov);
831 mov->src[0].src.is_ssa = true;
832 mov->src[0].src.ssa = intrin->src[0].ssa;
833 for (unsigned i = intrin->num_components; i < 4; i++)
834 mov->src[0].swizzle[i] = 0;
835
836 mov->dest.write_mask = (1 << intrin->num_components) - 1;
837 mov->dest.dest.is_ssa = true;
838 nir_ssa_def_init(&mov->instr, &mov->dest.dest.ssa,
839 intrin->num_components, NULL);
840
841 nir_instr_insert_before(&intrin->instr, &mov->instr);
842
843 def_stack_push(node, &mov->dest.dest.ssa, state);
844
845 /* We'll wait to remove the instruction until the next pass
846 * where we pop the node we just pushed back off the stack.
847 */
848 break;
849 }
850
851 default:
852 break;
853 }
854 }
855 }
856
857 if (block->successors[0])
858 add_phi_sources(block->successors[0], block, state);
859 if (block->successors[1])
860 add_phi_sources(block->successors[1], block, state);
861
862 for (unsigned i = 0; i < block->num_dom_children; ++i)
863 rename_variables_block(block->dom_children[i], state);
864
865 /* Now we iterate over the instructions and pop off any SSA defs that we
866 * pushed in the first loop.
867 */
868 nir_foreach_instr_safe(block, instr) {
869 if (instr->type == nir_instr_type_phi) {
870 nir_phi_instr *phi = nir_instr_as_phi(instr);
871
872 struct hash_entry *entry =
873 _mesa_hash_table_search(state->phi_table, phi);
874
875 /* This can happen if we already have phi nodes in the program
876 * that were not created in this pass.
877 */
878 if (!entry)
879 continue;
880
881 struct deref_node *node = entry->data;
882
883 def_stack_pop_if_in_block(node, block);
884 } else if (instr->type == nir_instr_type_intrinsic) {
885 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
886
887 if (intrin->intrinsic != nir_intrinsic_store_var)
888 continue;
889
890 struct deref_node *node = get_deref_node(intrin->variables[0], state);
891 if (!node)
892 continue;
893
894 if (!node->lower_to_ssa)
895 continue;
896
897 def_stack_pop_if_in_block(node, block);
898 nir_instr_remove(&intrin->instr);
899 }
900 }
901
902 return true;
903 }
904
905 /* Inserts phi nodes for all variables marked lower_to_ssa
906 *
907 * This is the same algorithm as presented in "Efficiently Computing Static
908 * Single Assignment Form and the Control Dependence Graph" by Cytron et.
909 * al.
910 */
911 static void
912 insert_phi_nodes(struct lower_variables_state *state)
913 {
914 unsigned work[state->impl->num_blocks];
915 unsigned has_already[state->impl->num_blocks];
916
917 /*
918 * Since the work flags already prevent us from inserting a node that has
919 * ever been inserted into W, we don't need to use a set to represent W.
920 * Also, since no block can ever be inserted into W more than once, we know
921 * that the maximum size of W is the number of basic blocks in the
922 * function. So all we need to handle W is an array and a pointer to the
923 * next element to be inserted and the next element to be removed.
924 */
925 nir_block *W[state->impl->num_blocks];
926
927 memset(work, 0, sizeof work);
928 memset(has_already, 0, sizeof has_already);
929
930 unsigned w_start, w_end;
931 unsigned iter_count = 0;
932
933 struct hash_entry *deref_entry;
934 hash_table_foreach(state->direct_deref_nodes, deref_entry) {
935 struct deref_node *node = deref_entry->data;
936
937 if (node->stores == NULL)
938 continue;
939
940 if (!node->lower_to_ssa)
941 continue;
942
943 w_start = w_end = 0;
944 iter_count++;
945
946 struct set_entry *store_entry;
947 set_foreach(node->stores, store_entry) {
948 nir_intrinsic_instr *store = (nir_intrinsic_instr *)store_entry->key;
949 if (work[store->instr.block->index] < iter_count)
950 W[w_end++] = store->instr.block;
951 work[store->instr.block->index] = iter_count;
952 }
953
954 while (w_start != w_end) {
955 nir_block *cur = W[w_start++];
956 struct set_entry *dom_entry;
957 set_foreach(cur->dom_frontier, dom_entry) {
958 nir_block *next = (nir_block *) dom_entry->key;
959
960 /*
961 * If there's more than one return statement, then the end block
962 * can be a join point for some definitions. However, there are
963 * no instructions in the end block, so nothing would use those
964 * phi nodes. Of course, we couldn't place those phi nodes
965 * anyways due to the restriction of having no instructions in the
966 * end block...
967 */
968 if (next == state->impl->end_block)
969 continue;
970
971 if (has_already[next->index] < iter_count) {
972 nir_phi_instr *phi = nir_phi_instr_create(state->mem_ctx);
973 phi->dest.is_ssa = true;
974 nir_ssa_def_init(&phi->instr, &phi->dest.ssa,
975 glsl_get_vector_elements(node->type), NULL);
976 nir_instr_insert_before_block(next, &phi->instr);
977
978 _mesa_hash_table_insert(state->phi_table, phi, node);
979
980 has_already[next->index] = iter_count;
981 if (work[next->index] < iter_count) {
982 work[next->index] = iter_count;
983 W[w_end++] = next;
984 }
985 }
986 }
987 }
988 }
989 }
990
991
992 /** Implements a pass to lower variable uses to SSA values
993 *
994 * This path walks the list of instructions and tries to lower as many
995 * local variable load/store operations to SSA defs and uses as it can.
996 * The process involves four passes:
997 *
998 * 1) Iterate over all of the instructions and mark where each local
999 * variable deref is used in a load, store, or copy. While we're at
1000 * it, we keep track of all of the fully-qualified (no wildcards) and
1001 * fully-direct references we see and store them in the
1002 * direct_deref_nodes hash table.
1003 *
1004 * 2) Walk over the the list of fully-qualified direct derefs generated in
1005 * the previous pass. For each deref, we determine if it can ever be
1006 * aliased, i.e. if there is an indirect reference anywhere that may
1007 * refer to it. If it cannot be aliased, we mark it for lowering to an
1008 * SSA value. At this point, we lower any var_copy instructions that
1009 * use the given deref to load/store operations and, if the deref has a
1010 * constant initializer, we go ahead and add a load_const value at the
1011 * beginning of the function with the initialized value.
1012 *
1013 * 3) Walk over the list of derefs we plan to lower to SSA values and
1014 * insert phi nodes as needed.
1015 *
1016 * 4) Perform "variable renaming" by replacing the load/store instructions
1017 * with SSA definitions and SSA uses.
1018 */
1019 static bool
1020 nir_lower_vars_to_ssa_impl(nir_function_impl *impl)
1021 {
1022 struct lower_variables_state state;
1023
1024 state.mem_ctx = ralloc_parent(impl);
1025 state.dead_ctx = ralloc_context(state.mem_ctx);
1026 state.impl = impl;
1027
1028 state.deref_var_nodes = _mesa_hash_table_create(state.dead_ctx,
1029 _mesa_hash_pointer,
1030 _mesa_key_pointer_equal);
1031 state.direct_deref_nodes = _mesa_hash_table_create(state.dead_ctx,
1032 hash_deref, derefs_equal);
1033 state.phi_table = _mesa_hash_table_create(state.dead_ctx,
1034 _mesa_hash_pointer,
1035 _mesa_key_pointer_equal);
1036
1037 /* Build the initial deref structures and direct_deref_nodes table */
1038 state.add_to_direct_deref_nodes = true;
1039 nir_foreach_block(impl, register_variable_uses_block, &state);
1040
1041 struct set *outputs = _mesa_set_create(state.dead_ctx,
1042 _mesa_key_pointer_equal);
1043
1044 bool progress = false;
1045
1046 nir_metadata_require(impl, nir_metadata_block_index);
1047
1048 /* We're about to iterate through direct_deref_nodes. Don't modify it. */
1049 state.add_to_direct_deref_nodes = false;
1050
1051 struct hash_entry *entry;
1052 hash_table_foreach(state.direct_deref_nodes, entry) {
1053 nir_deref_var *deref = (void *)entry->key;
1054 struct deref_node *node = entry->data;
1055
1056 if (deref->var->data.mode != nir_var_local) {
1057 _mesa_hash_table_remove(state.direct_deref_nodes, entry);
1058 continue;
1059 }
1060
1061 if (deref_may_be_aliased(deref, &state)) {
1062 _mesa_hash_table_remove(state.direct_deref_nodes, entry);
1063 continue;
1064 }
1065
1066 node->lower_to_ssa = true;
1067 progress = true;
1068
1069 if (deref->var->constant_initializer) {
1070 nir_load_const_instr *load = get_const_initializer_load(deref, &state);
1071 nir_ssa_def_init(&load->instr, &load->def,
1072 glsl_get_vector_elements(node->type), NULL);
1073 nir_instr_insert_before_cf_list(&impl->body, &load->instr);
1074 def_stack_push(node, &load->def, &state);
1075 }
1076
1077 if (deref->var->data.mode == nir_var_shader_out)
1078 _mesa_set_add(outputs, _mesa_hash_pointer(node), node);
1079
1080 foreach_deref_node_match(deref, lower_copies_to_load_store, &state);
1081 }
1082
1083 if (!progress)
1084 return false;
1085
1086 nir_metadata_require(impl, nir_metadata_dominance);
1087
1088 /* We may have lowered some copy instructions to load/store
1089 * instructions. The uses from the copy instructions hav already been
1090 * removed but we need to rescan to ensure that the uses from the newly
1091 * added load/store instructions are registered. We need this
1092 * information for phi node insertion below.
1093 */
1094 nir_foreach_block(impl, register_variable_uses_block, &state);
1095
1096 insert_phi_nodes(&state);
1097 rename_variables_block(impl->start_block, &state);
1098
1099 nir_metadata_preserve(impl, nir_metadata_block_index |
1100 nir_metadata_dominance);
1101
1102 ralloc_free(state.dead_ctx);
1103
1104 return progress;
1105 }
1106
1107 void
1108 nir_lower_vars_to_ssa(nir_shader *shader)
1109 {
1110 nir_foreach_overload(shader, overload) {
1111 if (overload->impl)
1112 nir_lower_vars_to_ssa_impl(overload->impl);
1113 }
1114 }