util/hash_set: Rework the API to know about hashing
[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, _mesa_hash_pointer,
447 _mesa_key_pointer_equal);
448
449 _mesa_set_add(node->loads, 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, _mesa_hash_pointer,
462 _mesa_key_pointer_equal);
463
464 _mesa_set_add(node->stores, 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, _mesa_hash_pointer,
480 _mesa_key_pointer_equal);
481
482 _mesa_set_add(node->copies, 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, copy);
543 assert(arg_entry);
544 _mesa_set_remove(node->copies, arg_entry);
545 }
546
547 nir_instr_remove(&copy->instr);
548 }
549
550 return true;
551 }
552
553 /* Returns a load_const instruction that represents the constant
554 * initializer for the given deref chain. The caller is responsible for
555 * ensuring that there actually is a constant initializer.
556 */
557 static nir_load_const_instr *
558 get_const_initializer_load(const nir_deref_var *deref,
559 struct lower_variables_state *state)
560 {
561 nir_constant *constant = deref->var->constant_initializer;
562 const nir_deref *tail = &deref->deref;
563 unsigned matrix_offset = 0;
564 while (tail->child) {
565 switch (tail->child->deref_type) {
566 case nir_deref_type_array: {
567 nir_deref_array *arr = nir_deref_as_array(tail->child);
568 assert(arr->deref_array_type == nir_deref_array_type_direct);
569 if (glsl_type_is_matrix(tail->type)) {
570 assert(arr->deref.child == NULL);
571 matrix_offset = arr->base_offset;
572 } else {
573 constant = constant->elements[arr->base_offset];
574 }
575 break;
576 }
577
578 case nir_deref_type_struct: {
579 constant = constant->elements[nir_deref_as_struct(tail->child)->index];
580 break;
581 }
582
583 default:
584 unreachable("Invalid deref child type");
585 }
586
587 tail = tail->child;
588 }
589
590 nir_load_const_instr *load =
591 nir_load_const_instr_create(state->mem_ctx,
592 glsl_get_vector_elements(tail->type));
593
594 matrix_offset *= load->def.num_components;
595 for (unsigned i = 0; i < load->def.num_components; i++) {
596 switch (glsl_get_base_type(tail->type)) {
597 case GLSL_TYPE_FLOAT:
598 case GLSL_TYPE_INT:
599 case GLSL_TYPE_UINT:
600 load->value.u[i] = constant->value.u[matrix_offset + i];
601 break;
602 case GLSL_TYPE_BOOL:
603 load->value.u[i] = constant->value.u[matrix_offset + i] ?
604 NIR_TRUE : NIR_FALSE;
605 break;
606 default:
607 unreachable("Invalid immediate type");
608 }
609 }
610
611 return load;
612 }
613
614 /** Pushes an SSA def onto the def stack for the given node
615 *
616 * Each node is potentially associated with a stack of SSA definitions.
617 * This stack is used for determining what SSA definition reaches a given
618 * point in the program for variable renaming. The stack is always kept in
619 * dominance-order with at most one SSA def per block. If the SSA
620 * definition on the top of the stack is in the same block as the one being
621 * pushed, the top element is replaced.
622 */
623 static void
624 def_stack_push(struct deref_node *node, nir_ssa_def *def,
625 struct lower_variables_state *state)
626 {
627 if (node->def_stack == NULL) {
628 node->def_stack = ralloc_array(state->dead_ctx, nir_ssa_def *,
629 state->impl->num_blocks);
630 node->def_stack_tail = node->def_stack - 1;
631 }
632
633 if (node->def_stack_tail >= node->def_stack) {
634 nir_ssa_def *top_def = *node->def_stack_tail;
635
636 if (def->parent_instr->block == top_def->parent_instr->block) {
637 /* They're in the same block, just replace the top */
638 *node->def_stack_tail = def;
639 return;
640 }
641 }
642
643 *(++node->def_stack_tail) = def;
644 }
645
646 /* Pop the top of the def stack if it's in the given block */
647 static void
648 def_stack_pop_if_in_block(struct deref_node *node, nir_block *block)
649 {
650 /* If we're popping, then we have presumably pushed at some time in the
651 * past so this should exist.
652 */
653 assert(node->def_stack != NULL);
654
655 /* The stack is already empty. Do nothing. */
656 if (node->def_stack_tail < node->def_stack)
657 return;
658
659 nir_ssa_def *def = *node->def_stack_tail;
660 if (def->parent_instr->block == block)
661 node->def_stack_tail--;
662 }
663
664 /** Retrieves the SSA definition on the top of the stack for the given
665 * node, if one exists. If the stack is empty, then we return the constant
666 * initializer (if it exists) or an SSA undef.
667 */
668 static nir_ssa_def *
669 get_ssa_def_for_block(struct deref_node *node, nir_block *block,
670 struct lower_variables_state *state)
671 {
672 /* If we have something on the stack, go ahead and return it. We're
673 * assuming that the top of the stack dominates the given block.
674 */
675 if (node->def_stack && node->def_stack_tail >= node->def_stack)
676 return *node->def_stack_tail;
677
678 /* If we got here then we don't have a definition that dominates the
679 * given block. This means that we need to add an undef and use that.
680 */
681 nir_ssa_undef_instr *undef =
682 nir_ssa_undef_instr_create(state->mem_ctx,
683 glsl_get_vector_elements(node->type));
684 nir_instr_insert_before_cf_list(&state->impl->body, &undef->instr);
685 def_stack_push(node, &undef->def, state);
686 return &undef->def;
687 }
688
689 /* Given a block and one of its predecessors, this function fills in the
690 * souces of the phi nodes to take SSA defs from the given predecessor.
691 * This function must be called exactly once per block/predecessor pair.
692 */
693 static void
694 add_phi_sources(nir_block *block, nir_block *pred,
695 struct lower_variables_state *state)
696 {
697 nir_foreach_instr(block, instr) {
698 if (instr->type != nir_instr_type_phi)
699 break;
700
701 nir_phi_instr *phi = nir_instr_as_phi(instr);
702
703 struct hash_entry *entry =
704 _mesa_hash_table_search(state->phi_table, phi);
705 if (!entry)
706 continue;
707
708 struct deref_node *node = entry->data;
709
710 nir_phi_src *src = ralloc(state->mem_ctx, nir_phi_src);
711 src->pred = pred;
712 src->src.is_ssa = true;
713 src->src.ssa = get_ssa_def_for_block(node, pred, state);
714
715 _mesa_set_add(src->src.ssa->uses, instr);
716
717 exec_list_push_tail(&phi->srcs, &src->node);
718 }
719 }
720
721 /* Performs variable renaming by doing a DFS of the dominance tree
722 *
723 * This algorithm is very similar to the one outlined in "Efficiently
724 * Computing Static Single Assignment Form and the Control Dependence
725 * Graph" by Cytron et. al. The primary difference is that we only put one
726 * SSA def on the stack per block.
727 */
728 static bool
729 rename_variables_block(nir_block *block, struct lower_variables_state *state)
730 {
731 nir_foreach_instr_safe(block, instr) {
732 if (instr->type == nir_instr_type_phi) {
733 nir_phi_instr *phi = nir_instr_as_phi(instr);
734
735 struct hash_entry *entry =
736 _mesa_hash_table_search(state->phi_table, phi);
737
738 /* This can happen if we already have phi nodes in the program
739 * that were not created in this pass.
740 */
741 if (!entry)
742 continue;
743
744 struct deref_node *node = entry->data;
745
746 def_stack_push(node, &phi->dest.ssa, state);
747 } else if (instr->type == nir_instr_type_intrinsic) {
748 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
749
750 switch (intrin->intrinsic) {
751 case nir_intrinsic_load_var: {
752 struct deref_node *node =
753 get_deref_node(intrin->variables[0], state);
754
755 if (node == NULL) {
756 /* If we hit this path then we are referencing an invalid
757 * value. Most likely, we unrolled something and are
758 * reading past the end of some array. In any case, this
759 * should result in an undefined value.
760 */
761 nir_ssa_undef_instr *undef =
762 nir_ssa_undef_instr_create(state->mem_ctx,
763 intrin->num_components);
764
765 nir_instr_insert_before(&intrin->instr, &undef->instr);
766 nir_instr_remove(&intrin->instr);
767
768 nir_src new_src = {
769 .is_ssa = true,
770 .ssa = &undef->def,
771 };
772
773 nir_ssa_def_rewrite_uses(&intrin->dest.ssa, new_src,
774 state->mem_ctx);
775 continue;
776 }
777
778 if (!node->lower_to_ssa)
779 continue;
780
781 nir_alu_instr *mov = nir_alu_instr_create(state->mem_ctx,
782 nir_op_imov);
783 mov->src[0].src.is_ssa = true;
784 mov->src[0].src.ssa = get_ssa_def_for_block(node, block, state);
785 for (unsigned i = intrin->num_components; i < 4; i++)
786 mov->src[0].swizzle[i] = 0;
787
788 assert(intrin->dest.is_ssa);
789
790 mov->dest.write_mask = (1 << intrin->num_components) - 1;
791 mov->dest.dest.is_ssa = true;
792 nir_ssa_def_init(&mov->instr, &mov->dest.dest.ssa,
793 intrin->num_components, NULL);
794
795 nir_instr_insert_before(&intrin->instr, &mov->instr);
796 nir_instr_remove(&intrin->instr);
797
798 nir_src new_src = {
799 .is_ssa = true,
800 .ssa = &mov->dest.dest.ssa,
801 };
802
803 nir_ssa_def_rewrite_uses(&intrin->dest.ssa, new_src,
804 state->mem_ctx);
805 break;
806 }
807
808 case nir_intrinsic_store_var: {
809 struct deref_node *node =
810 get_deref_node(intrin->variables[0], state);
811
812 if (node == NULL) {
813 /* Probably an out-of-bounds array store. That should be a
814 * no-op. */
815 nir_instr_remove(&intrin->instr);
816 continue;
817 }
818
819 if (!node->lower_to_ssa)
820 continue;
821
822 assert(intrin->num_components ==
823 glsl_get_vector_elements(node->type));
824
825 assert(intrin->src[0].is_ssa);
826
827 nir_alu_instr *mov = nir_alu_instr_create(state->mem_ctx,
828 nir_op_imov);
829 mov->src[0].src.is_ssa = true;
830 mov->src[0].src.ssa = intrin->src[0].ssa;
831 for (unsigned i = intrin->num_components; i < 4; i++)
832 mov->src[0].swizzle[i] = 0;
833
834 mov->dest.write_mask = (1 << intrin->num_components) - 1;
835 mov->dest.dest.is_ssa = true;
836 nir_ssa_def_init(&mov->instr, &mov->dest.dest.ssa,
837 intrin->num_components, NULL);
838
839 nir_instr_insert_before(&intrin->instr, &mov->instr);
840
841 def_stack_push(node, &mov->dest.dest.ssa, state);
842
843 /* We'll wait to remove the instruction until the next pass
844 * where we pop the node we just pushed back off the stack.
845 */
846 break;
847 }
848
849 default:
850 break;
851 }
852 }
853 }
854
855 if (block->successors[0])
856 add_phi_sources(block->successors[0], block, state);
857 if (block->successors[1])
858 add_phi_sources(block->successors[1], block, state);
859
860 for (unsigned i = 0; i < block->num_dom_children; ++i)
861 rename_variables_block(block->dom_children[i], state);
862
863 /* Now we iterate over the instructions and pop off any SSA defs that we
864 * pushed in the first loop.
865 */
866 nir_foreach_instr_safe(block, instr) {
867 if (instr->type == nir_instr_type_phi) {
868 nir_phi_instr *phi = nir_instr_as_phi(instr);
869
870 struct hash_entry *entry =
871 _mesa_hash_table_search(state->phi_table, phi);
872
873 /* This can happen if we already have phi nodes in the program
874 * that were not created in this pass.
875 */
876 if (!entry)
877 continue;
878
879 struct deref_node *node = entry->data;
880
881 def_stack_pop_if_in_block(node, block);
882 } else if (instr->type == nir_instr_type_intrinsic) {
883 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
884
885 if (intrin->intrinsic != nir_intrinsic_store_var)
886 continue;
887
888 struct deref_node *node = get_deref_node(intrin->variables[0], state);
889 if (!node)
890 continue;
891
892 if (!node->lower_to_ssa)
893 continue;
894
895 def_stack_pop_if_in_block(node, block);
896 nir_instr_remove(&intrin->instr);
897 }
898 }
899
900 return true;
901 }
902
903 /* Inserts phi nodes for all variables marked lower_to_ssa
904 *
905 * This is the same algorithm as presented in "Efficiently Computing Static
906 * Single Assignment Form and the Control Dependence Graph" by Cytron et.
907 * al.
908 */
909 static void
910 insert_phi_nodes(struct lower_variables_state *state)
911 {
912 unsigned work[state->impl->num_blocks];
913 unsigned has_already[state->impl->num_blocks];
914
915 /*
916 * Since the work flags already prevent us from inserting a node that has
917 * ever been inserted into W, we don't need to use a set to represent W.
918 * Also, since no block can ever be inserted into W more than once, we know
919 * that the maximum size of W is the number of basic blocks in the
920 * function. So all we need to handle W is an array and a pointer to the
921 * next element to be inserted and the next element to be removed.
922 */
923 nir_block *W[state->impl->num_blocks];
924
925 memset(work, 0, sizeof work);
926 memset(has_already, 0, sizeof has_already);
927
928 unsigned w_start, w_end;
929 unsigned iter_count = 0;
930
931 struct hash_entry *deref_entry;
932 hash_table_foreach(state->direct_deref_nodes, deref_entry) {
933 struct deref_node *node = deref_entry->data;
934
935 if (node->stores == NULL)
936 continue;
937
938 if (!node->lower_to_ssa)
939 continue;
940
941 w_start = w_end = 0;
942 iter_count++;
943
944 struct set_entry *store_entry;
945 set_foreach(node->stores, store_entry) {
946 nir_intrinsic_instr *store = (nir_intrinsic_instr *)store_entry->key;
947 if (work[store->instr.block->index] < iter_count)
948 W[w_end++] = store->instr.block;
949 work[store->instr.block->index] = iter_count;
950 }
951
952 while (w_start != w_end) {
953 nir_block *cur = W[w_start++];
954 struct set_entry *dom_entry;
955 set_foreach(cur->dom_frontier, dom_entry) {
956 nir_block *next = (nir_block *) dom_entry->key;
957
958 /*
959 * If there's more than one return statement, then the end block
960 * can be a join point for some definitions. However, there are
961 * no instructions in the end block, so nothing would use those
962 * phi nodes. Of course, we couldn't place those phi nodes
963 * anyways due to the restriction of having no instructions in the
964 * end block...
965 */
966 if (next == state->impl->end_block)
967 continue;
968
969 if (has_already[next->index] < iter_count) {
970 nir_phi_instr *phi = nir_phi_instr_create(state->mem_ctx);
971 phi->dest.is_ssa = true;
972 nir_ssa_def_init(&phi->instr, &phi->dest.ssa,
973 glsl_get_vector_elements(node->type), NULL);
974 nir_instr_insert_before_block(next, &phi->instr);
975
976 _mesa_hash_table_insert(state->phi_table, phi, node);
977
978 has_already[next->index] = iter_count;
979 if (work[next->index] < iter_count) {
980 work[next->index] = iter_count;
981 W[w_end++] = next;
982 }
983 }
984 }
985 }
986 }
987 }
988
989
990 /** Implements a pass to lower variable uses to SSA values
991 *
992 * This path walks the list of instructions and tries to lower as many
993 * local variable load/store operations to SSA defs and uses as it can.
994 * The process involves four passes:
995 *
996 * 1) Iterate over all of the instructions and mark where each local
997 * variable deref is used in a load, store, or copy. While we're at
998 * it, we keep track of all of the fully-qualified (no wildcards) and
999 * fully-direct references we see and store them in the
1000 * direct_deref_nodes hash table.
1001 *
1002 * 2) Walk over the the list of fully-qualified direct derefs generated in
1003 * the previous pass. For each deref, we determine if it can ever be
1004 * aliased, i.e. if there is an indirect reference anywhere that may
1005 * refer to it. If it cannot be aliased, we mark it for lowering to an
1006 * SSA value. At this point, we lower any var_copy instructions that
1007 * use the given deref to load/store operations and, if the deref has a
1008 * constant initializer, we go ahead and add a load_const value at the
1009 * beginning of the function with the initialized value.
1010 *
1011 * 3) Walk over the list of derefs we plan to lower to SSA values and
1012 * insert phi nodes as needed.
1013 *
1014 * 4) Perform "variable renaming" by replacing the load/store instructions
1015 * with SSA definitions and SSA uses.
1016 */
1017 static bool
1018 nir_lower_vars_to_ssa_impl(nir_function_impl *impl)
1019 {
1020 struct lower_variables_state state;
1021
1022 state.mem_ctx = ralloc_parent(impl);
1023 state.dead_ctx = ralloc_context(state.mem_ctx);
1024 state.impl = impl;
1025
1026 state.deref_var_nodes = _mesa_hash_table_create(state.dead_ctx,
1027 _mesa_hash_pointer,
1028 _mesa_key_pointer_equal);
1029 state.direct_deref_nodes = _mesa_hash_table_create(state.dead_ctx,
1030 hash_deref, derefs_equal);
1031 state.phi_table = _mesa_hash_table_create(state.dead_ctx,
1032 _mesa_hash_pointer,
1033 _mesa_key_pointer_equal);
1034
1035 /* Build the initial deref structures and direct_deref_nodes table */
1036 state.add_to_direct_deref_nodes = true;
1037 nir_foreach_block(impl, register_variable_uses_block, &state);
1038
1039 struct set *outputs = _mesa_set_create(state.dead_ctx,
1040 _mesa_hash_pointer,
1041 _mesa_key_pointer_equal);
1042
1043 bool progress = false;
1044
1045 nir_metadata_require(impl, nir_metadata_block_index);
1046
1047 /* We're about to iterate through direct_deref_nodes. Don't modify it. */
1048 state.add_to_direct_deref_nodes = false;
1049
1050 struct hash_entry *entry;
1051 hash_table_foreach(state.direct_deref_nodes, entry) {
1052 nir_deref_var *deref = (void *)entry->key;
1053 struct deref_node *node = entry->data;
1054
1055 if (deref->var->data.mode != nir_var_local) {
1056 _mesa_hash_table_remove(state.direct_deref_nodes, entry);
1057 continue;
1058 }
1059
1060 if (deref_may_be_aliased(deref, &state)) {
1061 _mesa_hash_table_remove(state.direct_deref_nodes, entry);
1062 continue;
1063 }
1064
1065 node->lower_to_ssa = true;
1066 progress = true;
1067
1068 if (deref->var->constant_initializer) {
1069 nir_load_const_instr *load = get_const_initializer_load(deref, &state);
1070 nir_ssa_def_init(&load->instr, &load->def,
1071 glsl_get_vector_elements(node->type), NULL);
1072 nir_instr_insert_before_cf_list(&impl->body, &load->instr);
1073 def_stack_push(node, &load->def, &state);
1074 }
1075
1076 if (deref->var->data.mode == nir_var_shader_out)
1077 _mesa_set_add(outputs, node);
1078
1079 foreach_deref_node_match(deref, lower_copies_to_load_store, &state);
1080 }
1081
1082 if (!progress)
1083 return false;
1084
1085 nir_metadata_require(impl, nir_metadata_dominance);
1086
1087 /* We may have lowered some copy instructions to load/store
1088 * instructions. The uses from the copy instructions hav already been
1089 * removed but we need to rescan to ensure that the uses from the newly
1090 * added load/store instructions are registered. We need this
1091 * information for phi node insertion below.
1092 */
1093 nir_foreach_block(impl, register_variable_uses_block, &state);
1094
1095 insert_phi_nodes(&state);
1096 rename_variables_block(impl->start_block, &state);
1097
1098 nir_metadata_preserve(impl, nir_metadata_block_index |
1099 nir_metadata_dominance);
1100
1101 ralloc_free(state.dead_ctx);
1102
1103 return progress;
1104 }
1105
1106 void
1107 nir_lower_vars_to_ssa(nir_shader *shader)
1108 {
1109 nir_foreach_overload(shader, overload) {
1110 if (overload->impl)
1111 nir_lower_vars_to_ssa_impl(overload->impl);
1112 }
1113 }