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