• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
24 #include "nir.h"
25 #include "nir_builder.h"
26 #include "nir_builder_opcodes.h"
27 #include "nir_vla.h"
28 
29 /*
30  * This file implements an out-of-SSA pass as described in "Revisiting
31  * Out-of-SSA Translation for Correctness, Code Quality, and Efficiency" by
32  * Boissinot et al.
33  */
34 
35 struct from_ssa_state {
36    nir_builder builder;
37    void *dead_ctx;
38    struct exec_list dead_instrs;
39    bool phi_webs_only;
40    struct hash_table *merge_node_table;
41    nir_instr *instr;
42    bool consider_divergence;
43    bool progress;
44 };
45 
46 /* Returns if def @a comes after def @b.
47  *
48  * The core observation that makes the Boissinot algorithm efficient
49  * is that, given two properly sorted sets, we can check for
50  * interference in these sets via a linear walk. This is accomplished
51  * by doing single combined walk over union of the two sets in DFS
52  * order. It doesn't matter what DFS we do so long as we're
53  * consistent. Fortunately, the dominance algorithm we ran prior to
54  * this pass did such a walk and recorded the pre- and post-indices in
55  * the blocks.
56  *
57  * We treat SSA undefs as always coming before other instruction types.
58  */
59 static bool
def_after(nir_def * a,nir_def * b)60 def_after(nir_def *a, nir_def *b)
61 {
62    if (a->parent_instr->type == nir_instr_type_undef)
63       return false;
64 
65    if (b->parent_instr->type == nir_instr_type_undef)
66       return true;
67 
68    /* If they're in the same block, we can rely on whichever instruction
69     * comes first in the block.
70     */
71    if (a->parent_instr->block == b->parent_instr->block)
72       return a->parent_instr->index > b->parent_instr->index;
73 
74    /* Otherwise, if blocks are distinct, we sort them in DFS pre-order */
75    return a->parent_instr->block->dom_pre_index >
76           b->parent_instr->block->dom_pre_index;
77 }
78 
79 /* Returns true if a dominates b */
80 static bool
ssa_def_dominates(nir_def * a,nir_def * b)81 ssa_def_dominates(nir_def *a, nir_def *b)
82 {
83    if (a->parent_instr->type == nir_instr_type_undef) {
84       /* SSA undefs always dominate */
85       return true;
86    }
87    if (def_after(a, b)) {
88       return false;
89    } else if (a->parent_instr->block == b->parent_instr->block) {
90       return def_after(b, a);
91    } else {
92       return nir_block_dominates(a->parent_instr->block,
93                                  b->parent_instr->block);
94    }
95 }
96 
97 /* The following data structure, which I have named merge_set is a way of
98  * representing a set registers of non-interfering registers.  This is
99  * based on the concept of a "dominance forest" presented in "Fast Copy
100  * Coalescing and Live-Range Identification" by Budimlic et al. but the
101  * implementation concept is taken from  "Revisiting Out-of-SSA Translation
102  * for Correctness, Code Quality, and Efficiency" by Boissinot et al.
103  *
104  * Each SSA definition is associated with a merge_node and the association
105  * is represented by a combination of a hash table and the "def" parameter
106  * in the merge_node structure.  The merge_set stores a linked list of
107  * merge_nodes, ordered by a pre-order DFS walk of the dominance tree.  (Since
108  * the liveness analysis pass indexes the SSA values in dominance order for
109  * us, this is an easy thing to keep up.)  It is assumed that no pair of the
110  * nodes in a given set interfere.  Merging two sets or checking for
111  * interference can be done in a single linear-time merge-sort walk of the
112  * two lists of nodes.
113  */
114 struct merge_set;
115 
116 typedef struct {
117    struct exec_node node;
118    struct merge_set *set;
119    nir_def *def;
120 } merge_node;
121 
122 typedef struct merge_set {
123    struct exec_list nodes;
124    unsigned size;
125    bool divergent;
126    nir_def *reg_decl;
127 } merge_set;
128 
129 #if 0
130 static void
131 merge_set_dump(merge_set *set, FILE *fp)
132 {
133    NIR_VLA(nir_def *, dom, set->size);
134    int dom_idx = -1;
135 
136    foreach_list_typed(merge_node, node, node, &set->nodes) {
137       while (dom_idx >= 0 && !ssa_def_dominates(dom[dom_idx], node->def))
138          dom_idx--;
139 
140       for (int i = 0; i <= dom_idx; i++)
141          fprintf(fp, "  ");
142 
143       fprintf(fp, "ssa_%d\n", node->def->index);
144 
145       dom[++dom_idx] = node->def;
146    }
147 }
148 #endif
149 
150 static merge_node *
get_merge_node(nir_def * def,struct from_ssa_state * state)151 get_merge_node(nir_def *def, struct from_ssa_state *state)
152 {
153    struct hash_entry *entry =
154       _mesa_hash_table_search(state->merge_node_table, def);
155    if (entry)
156       return entry->data;
157 
158    merge_set *set = rzalloc(state->dead_ctx, merge_set);
159    exec_list_make_empty(&set->nodes);
160    set->size = 1;
161    set->divergent = state->consider_divergence && def->divergent;
162 
163    merge_node *node = ralloc(state->dead_ctx, merge_node);
164    node->set = set;
165    node->def = def;
166    exec_list_push_head(&set->nodes, &node->node);
167 
168    _mesa_hash_table_insert(state->merge_node_table, def, node);
169 
170    return node;
171 }
172 
173 static bool
merge_nodes_interfere(merge_node * a,merge_node * b)174 merge_nodes_interfere(merge_node *a, merge_node *b)
175 {
176    /* There's no need to check for interference within the same set,
177     * because we assume, that sets themselves are already
178     * interference-free.
179     */
180    if (a->set == b->set)
181       return false;
182 
183    return nir_defs_interfere(a->def, b->def);
184 }
185 
186 /* Merges b into a
187  *
188  * This algorithm uses def_after to ensure that the sets always stay in the
189  * same order as the pre-order DFS done by the liveness algorithm.
190  */
191 static merge_set *
merge_merge_sets(merge_set * a,merge_set * b)192 merge_merge_sets(merge_set *a, merge_set *b)
193 {
194    struct exec_node *an = exec_list_get_head(&a->nodes);
195    struct exec_node *bn = exec_list_get_head(&b->nodes);
196    while (!exec_node_is_tail_sentinel(bn)) {
197       merge_node *a_node = exec_node_data(merge_node, an, node);
198       merge_node *b_node = exec_node_data(merge_node, bn, node);
199 
200       if (exec_node_is_tail_sentinel(an) ||
201           def_after(a_node->def, b_node->def)) {
202          struct exec_node *next = bn->next;
203          exec_node_remove(bn);
204          exec_node_insert_node_before(an, bn);
205          exec_node_data(merge_node, bn, node)->set = a;
206          bn = next;
207       } else {
208          an = an->next;
209       }
210    }
211 
212    a->size += b->size;
213    b->size = 0;
214    a->divergent |= b->divergent;
215 
216    return a;
217 }
218 
219 /* Checks for any interference between two merge sets
220  *
221  * This is an implementation of Algorithm 2 in "Revisiting Out-of-SSA
222  * Translation for Correctness, Code Quality, and Efficiency" by
223  * Boissinot et al.
224  */
225 static bool
merge_sets_interfere(merge_set * a,merge_set * b)226 merge_sets_interfere(merge_set *a, merge_set *b)
227 {
228    /* List of all the nodes which dominate the current node, in dominance
229     * order.
230     */
231    NIR_VLA(merge_node *, dom, a->size + b->size);
232    int dom_idx = -1;
233 
234    struct exec_node *an = exec_list_get_head(&a->nodes);
235    struct exec_node *bn = exec_list_get_head(&b->nodes);
236    while (!exec_node_is_tail_sentinel(an) ||
237           !exec_node_is_tail_sentinel(bn)) {
238 
239       /* We walk the union of the two sets in the same order as the pre-order
240        * DFS done by liveness analysis.
241        */
242       merge_node *current;
243       if (exec_node_is_tail_sentinel(an)) {
244          current = exec_node_data(merge_node, bn, node);
245          bn = bn->next;
246       } else if (exec_node_is_tail_sentinel(bn)) {
247          current = exec_node_data(merge_node, an, node);
248          an = an->next;
249       } else {
250          merge_node *a_node = exec_node_data(merge_node, an, node);
251          merge_node *b_node = exec_node_data(merge_node, bn, node);
252 
253          if (def_after(b_node->def, a_node->def)) {
254             current = a_node;
255             an = an->next;
256          } else {
257             current = b_node;
258             bn = bn->next;
259          }
260       }
261 
262       /* Because our walk is a pre-order DFS, we can maintain the list of
263        * dominating nodes as a simple stack, pushing every node onto the list
264        * after we visit it and popping any non-dominating nodes off before we
265        * visit the current node.
266        */
267       while (dom_idx >= 0 &&
268              !ssa_def_dominates(dom[dom_idx]->def, current->def))
269          dom_idx--;
270 
271       /* There are three invariants of this algorithm that are important here:
272        *
273        *  1. There is no interference within either set a or set b.
274        *  2. None of the nodes processed up until this point interfere.
275        *  3. All the dominators of `current` have been processed
276        *
277        * Because of these invariants, we only need to check the current node
278        * against its minimal dominator.  If any other node N in the union
279        * interferes with current, then N must dominate current because we are
280        * in SSA form.  If N dominates current then it must also dominate our
281        * minimal dominator dom[dom_idx].  Since N is live at current it must
282        * also be live at the minimal dominator which means N interferes with
283        * the minimal dominator dom[dom_idx] and, by invariants 2 and 3 above,
284        * the algorithm would have already terminated.  Therefore, if we got
285        * here, the only node that can possibly interfere with current is the
286        * minimal dominator dom[dom_idx].
287        *
288        * This is what allows us to do a interference check of the union of the
289        * two sets with a single linear-time walk.
290        */
291       if (dom_idx >= 0 && merge_nodes_interfere(current, dom[dom_idx]))
292          return true;
293 
294       dom[++dom_idx] = current;
295    }
296 
297    return false;
298 }
299 
300 static bool
add_parallel_copy_to_end_of_block(nir_shader * shader,nir_block * block,void * dead_ctx)301 add_parallel_copy_to_end_of_block(nir_shader *shader, nir_block *block, void *dead_ctx)
302 {
303    bool need_end_copy = false;
304    if (block->successors[0]) {
305       nir_instr *instr = nir_block_first_instr(block->successors[0]);
306       if (instr && instr->type == nir_instr_type_phi)
307          need_end_copy = true;
308    }
309 
310    if (block->successors[1]) {
311       nir_instr *instr = nir_block_first_instr(block->successors[1]);
312       if (instr && instr->type == nir_instr_type_phi)
313          need_end_copy = true;
314    }
315 
316    if (need_end_copy) {
317       /* If one of our successors has at least one phi node, we need to
318        * create a parallel copy at the end of the block but before the jump
319        * (if there is one).
320        */
321       nir_parallel_copy_instr *pcopy =
322          nir_parallel_copy_instr_create(shader);
323 
324       nir_instr_insert(nir_after_block_before_jump(block), &pcopy->instr);
325    }
326 
327    return true;
328 }
329 
330 static nir_parallel_copy_instr *
get_parallel_copy_at_end_of_block(nir_block * block)331 get_parallel_copy_at_end_of_block(nir_block *block)
332 {
333    nir_instr *last_instr = nir_block_last_instr(block);
334    if (last_instr == NULL)
335       return NULL;
336 
337    /* The last instruction may be a jump in which case the parallel copy is
338     * right before it.
339     */
340    if (last_instr->type == nir_instr_type_jump)
341       last_instr = nir_instr_prev(last_instr);
342 
343    if (last_instr && last_instr->type == nir_instr_type_parallel_copy)
344       return nir_instr_as_parallel_copy(last_instr);
345    else
346       return NULL;
347 }
348 
349 /** Isolate phi nodes with parallel copies
350  *
351  * In order to solve the dependency problems with the sources and
352  * destinations of phi nodes, we first isolate them by adding parallel
353  * copies to the beginnings and ends of basic blocks.  For every block with
354  * phi nodes, we add a parallel copy immediately following the last phi
355  * node that copies the destinations of all of the phi nodes to new SSA
356  * values.  We also add a parallel copy to the end of every block that has
357  * a successor with phi nodes that, for each phi node in each successor,
358  * copies the corresponding sorce of the phi node and adjust the phi to
359  * used the destination of the parallel copy.
360  *
361  * In SSA form, each value has exactly one definition.  What this does is
362  * ensure that each value used in a phi also has exactly one use.  The
363  * destinations of phis are only used by the parallel copy immediately
364  * following the phi nodes and.  Thanks to the parallel copy at the end of
365  * the predecessor block, the sources of phi nodes are are the only use of
366  * that value.  This allows us to immediately assign all the sources and
367  * destinations of any given phi node to the same register without worrying
368  * about interference at all.  We do coalescing to get rid of the parallel
369  * copies where possible.
370  *
371  * Before this pass can be run, we have to iterate over the blocks with
372  * add_parallel_copy_to_end_of_block to ensure that the parallel copies at
373  * the ends of blocks exist.  We can create the ones at the beginnings as
374  * we go, but the ones at the ends of blocks need to be created ahead of
375  * time because of potential back-edges in the CFG.
376  */
377 static bool
isolate_phi_nodes_block(nir_shader * shader,nir_block * block,struct from_ssa_state * state)378 isolate_phi_nodes_block(nir_shader *shader, nir_block *block, struct from_ssa_state *state)
379 {
380    /* If we don't have any phis, then there's nothing for us to do. */
381    nir_phi_instr *last_phi = nir_block_last_phi_instr(block);
382    if (last_phi == NULL)
383       return true;
384 
385    /* If we have phi nodes, we need to create a parallel copy at the
386     * start of this block but after the phi nodes.
387     */
388    nir_parallel_copy_instr *block_pcopy =
389       nir_parallel_copy_instr_create(shader);
390    nir_instr_insert_after(&last_phi->instr, &block_pcopy->instr);
391 
392    nir_foreach_phi(phi, block) {
393       nir_foreach_phi_src(src, phi) {
394          if (nir_src_is_undef(src->src))
395             continue;
396 
397          nir_parallel_copy_instr *pcopy =
398             get_parallel_copy_at_end_of_block(src->pred);
399          assert(pcopy);
400 
401          nir_parallel_copy_entry *entry = rzalloc(state->dead_ctx,
402                                                   nir_parallel_copy_entry);
403 
404          entry->dest_is_reg = false;
405          nir_def_init(&pcopy->instr, &entry->dest.def,
406                       phi->def.num_components, phi->def.bit_size);
407          entry->dest.def.divergent = state->consider_divergence && nir_src_is_divergent(&src->src);
408 
409          /* We're adding a source to a live instruction so we need to use
410           * nir_instr_init_src()
411           */
412          entry->src_is_reg = false;
413          nir_instr_init_src(&pcopy->instr, &entry->src, src->src.ssa);
414 
415          exec_list_push_tail(&pcopy->entries, &entry->node);
416 
417          nir_src_rewrite(&src->src, &entry->dest.def);
418       }
419 
420       nir_parallel_copy_entry *entry = rzalloc(state->dead_ctx,
421                                                nir_parallel_copy_entry);
422 
423       entry->dest_is_reg = false;
424       nir_def_init(&block_pcopy->instr, &entry->dest.def,
425                    phi->def.num_components, phi->def.bit_size);
426       entry->dest.def.divergent = state->consider_divergence && phi->def.divergent;
427 
428       nir_def_rewrite_uses(&phi->def, &entry->dest.def);
429 
430       /* We're adding a source to a live instruction so we need to use
431        * nir_instr_init_src().
432        *
433        * Note that we do this after we've rewritten all uses of the phi to
434        * entry->def, ensuring that entry->src will be the only remaining use
435        * of the phi.
436        */
437       entry->src_is_reg = false;
438       nir_instr_init_src(&block_pcopy->instr, &entry->src, &phi->def);
439 
440       exec_list_push_tail(&block_pcopy->entries, &entry->node);
441    }
442 
443    return true;
444 }
445 
446 static bool
coalesce_phi_nodes_block(nir_block * block,struct from_ssa_state * state)447 coalesce_phi_nodes_block(nir_block *block, struct from_ssa_state *state)
448 {
449    nir_foreach_phi(phi, block) {
450       merge_node *dest_node = get_merge_node(&phi->def, state);
451 
452       nir_foreach_phi_src(src, phi) {
453          if (nir_src_is_undef(src->src))
454             continue;
455 
456          merge_node *src_node = get_merge_node(src->src.ssa, state);
457          if (src_node->set != dest_node->set)
458             merge_merge_sets(dest_node->set, src_node->set);
459       }
460    }
461 
462    return true;
463 }
464 
465 static void
aggressive_coalesce_parallel_copy(nir_parallel_copy_instr * pcopy,struct from_ssa_state * state)466 aggressive_coalesce_parallel_copy(nir_parallel_copy_instr *pcopy,
467                                   struct from_ssa_state *state)
468 {
469    nir_foreach_parallel_copy_entry(entry, pcopy) {
470       assert(!entry->src_is_reg);
471       assert(!entry->dest_is_reg);
472       assert(entry->dest.def.num_components ==
473              entry->src.ssa->num_components);
474 
475       /* Since load_const instructions are SSA only, we can't replace their
476        * destinations with registers and, therefore, can't coalesce them.
477        */
478       if (entry->src.ssa->parent_instr->type == nir_instr_type_load_const)
479          continue;
480 
481       merge_node *src_node = get_merge_node(entry->src.ssa, state);
482       merge_node *dest_node = get_merge_node(&entry->dest.def, state);
483 
484       if (src_node->set == dest_node->set)
485          continue;
486 
487       /* TODO: We can probably do better here but for now we should be safe if
488        * we just don't coalesce things with different divergence.
489        */
490       if (dest_node->set->divergent != src_node->set->divergent)
491          continue;
492 
493       if (!merge_sets_interfere(src_node->set, dest_node->set))
494          merge_merge_sets(src_node->set, dest_node->set);
495    }
496 }
497 
498 static bool
aggressive_coalesce_block(nir_block * block,struct from_ssa_state * state)499 aggressive_coalesce_block(nir_block *block, struct from_ssa_state *state)
500 {
501    nir_parallel_copy_instr *start_pcopy = NULL;
502    nir_foreach_instr(instr, block) {
503       /* Phi nodes only ever come at the start of a block */
504       if (instr->type != nir_instr_type_phi) {
505          if (instr->type != nir_instr_type_parallel_copy)
506             break; /* The parallel copy must be right after the phis */
507 
508          start_pcopy = nir_instr_as_parallel_copy(instr);
509 
510          aggressive_coalesce_parallel_copy(start_pcopy, state);
511 
512          break;
513       }
514    }
515 
516    nir_parallel_copy_instr *end_pcopy =
517       get_parallel_copy_at_end_of_block(block);
518 
519    if (end_pcopy && end_pcopy != start_pcopy)
520       aggressive_coalesce_parallel_copy(end_pcopy, state);
521 
522    return true;
523 }
524 
525 static nir_def *
decl_reg_for_ssa_def(nir_builder * b,nir_def * def)526 decl_reg_for_ssa_def(nir_builder *b, nir_def *def)
527 {
528    return nir_decl_reg(b, def->num_components, def->bit_size, 0);
529 }
530 
531 static void
set_reg_divergent(nir_def * reg,bool divergent)532 set_reg_divergent(nir_def *reg, bool divergent)
533 {
534    nir_intrinsic_instr *decl = nir_reg_get_decl(reg);
535    nir_intrinsic_set_divergent(decl, divergent);
536 }
537 
538 void
nir_rewrite_uses_to_load_reg(nir_builder * b,nir_def * old,nir_def * reg)539 nir_rewrite_uses_to_load_reg(nir_builder *b, nir_def *old,
540                              nir_def *reg)
541 {
542    nir_foreach_use_including_if_safe(use, old) {
543       b->cursor = nir_before_src(use);
544 
545       /* If this is a parallel copy, it can just take the register directly */
546       if (!nir_src_is_if(use) &&
547           nir_src_parent_instr(use)->type == nir_instr_type_parallel_copy) {
548 
549          nir_parallel_copy_entry *copy_entry =
550             list_entry(use, nir_parallel_copy_entry, src);
551 
552          assert(!copy_entry->src_is_reg);
553          copy_entry->src_is_reg = true;
554          nir_src_rewrite(&copy_entry->src, reg);
555          continue;
556       }
557 
558       /* If the immediate preceding instruction is a load_reg from the same
559        * register, use it instead of creating a new load_reg. This helps when
560        * a register is referenced in multiple sources in the same instruction,
561        * which otherwise would turn into piles of unnecessary moves.
562        */
563       nir_def *load = NULL;
564       if (b->cursor.option == nir_cursor_before_instr) {
565          nir_instr *prev = nir_instr_prev(b->cursor.instr);
566 
567          if (prev != NULL && prev->type == nir_instr_type_intrinsic) {
568             nir_intrinsic_instr *intr = nir_instr_as_intrinsic(prev);
569             if (intr->intrinsic == nir_intrinsic_load_reg &&
570                 intr->src[0].ssa == reg &&
571                 nir_intrinsic_base(intr) == 0)
572                load = &intr->def;
573          }
574       }
575 
576       if (load == NULL)
577          load = nir_load_reg(b, reg);
578 
579       nir_src_rewrite(use, load);
580    }
581 }
582 
583 static bool
def_replace_with_reg(nir_def * def,nir_function_impl * impl)584 def_replace_with_reg(nir_def *def, nir_function_impl *impl)
585 {
586    /* These are handled elsewhere */
587    assert(def->parent_instr->type != nir_instr_type_undef &&
588           def->parent_instr->type != nir_instr_type_load_const);
589 
590    nir_builder b = nir_builder_create(impl);
591 
592    nir_def *reg = decl_reg_for_ssa_def(&b, def);
593    nir_rewrite_uses_to_load_reg(&b, def, reg);
594 
595    if (def->parent_instr->type == nir_instr_type_phi)
596       b.cursor = nir_before_block_after_phis(def->parent_instr->block);
597    else
598       b.cursor = nir_after_instr(def->parent_instr);
599 
600    nir_store_reg(&b, def, reg);
601    return true;
602 }
603 
604 static nir_def *
reg_for_ssa_def(nir_def * def,struct from_ssa_state * state)605 reg_for_ssa_def(nir_def *def, struct from_ssa_state *state)
606 {
607    struct hash_entry *entry =
608       _mesa_hash_table_search(state->merge_node_table, def);
609    if (entry) {
610       /* In this case, we're part of a phi web.  Use the web's register. */
611       merge_node *node = (merge_node *)entry->data;
612 
613       /* If it doesn't have a register yet, create one.  Note that all of
614        * the things in the merge set should be the same so it doesn't
615        * matter which node's definition we use.
616        */
617       if (node->set->reg_decl == NULL) {
618          node->set->reg_decl = decl_reg_for_ssa_def(&state->builder, def);
619          set_reg_divergent(node->set->reg_decl, node->set->divergent);
620       }
621 
622       return node->set->reg_decl;
623    } else {
624       assert(state->phi_webs_only);
625       return NULL;
626    }
627 }
628 
629 static void
remove_no_op_phi(nir_instr * instr,struct from_ssa_state * state)630 remove_no_op_phi(nir_instr *instr, struct from_ssa_state *state)
631 {
632 #ifndef NDEBUG
633    nir_phi_instr *phi = nir_instr_as_phi(instr);
634 
635    struct hash_entry *entry =
636       _mesa_hash_table_search(state->merge_node_table, &phi->def);
637    assert(entry != NULL);
638    merge_node *node = (merge_node *)entry->data;
639 
640    nir_foreach_phi_src(src, phi) {
641       if (nir_src_is_undef(src->src))
642          continue;
643 
644       entry = _mesa_hash_table_search(state->merge_node_table, src->src.ssa);
645       assert(entry != NULL);
646       merge_node *src_node = (merge_node *)entry->data;
647       assert(src_node->set == node->set);
648    }
649 #endif
650 
651    nir_instr_remove(instr);
652 }
653 
654 static bool
rewrite_ssa_def(nir_def * def,void * void_state)655 rewrite_ssa_def(nir_def *def, void *void_state)
656 {
657    struct from_ssa_state *state = void_state;
658 
659    nir_def *reg = reg_for_ssa_def(def, state);
660    if (reg == NULL)
661       return true;
662 
663    assert(nir_def_is_unused(def));
664 
665    /* At this point we know a priori that this SSA def is part of a
666     * nir_dest.  We can use exec_node_data to get the dest pointer.
667     */
668    assert(def->parent_instr->type != nir_instr_type_load_const);
669    nir_store_reg(&state->builder, def, reg);
670 
671    state->progress = true;
672    return true;
673 }
674 
675 static bool
rewrite_src(nir_src * src,void * void_state)676 rewrite_src(nir_src *src, void *void_state)
677 {
678    struct from_ssa_state *state = void_state;
679 
680    nir_def *reg = reg_for_ssa_def(src->ssa, state);
681    if (reg == NULL)
682       return true;
683 
684    nir_src_rewrite(src, nir_load_reg(&state->builder, reg));
685 
686    state->progress = true;
687    return true;
688 }
689 
690 /* Resolves ssa definitions to registers.  While we're at it, we also
691  * remove phi nodes.
692  */
693 static void
resolve_registers_impl(nir_function_impl * impl,struct from_ssa_state * state)694 resolve_registers_impl(nir_function_impl *impl, struct from_ssa_state *state)
695 {
696    nir_foreach_block_reverse(block, impl) {
697       /* Remove successor phis in case there's a back edge. */
698       for (unsigned i = 0; i < 2; i++) {
699          nir_block *succ = block->successors[i];
700          if (succ == NULL)
701             continue;
702 
703          nir_foreach_instr_safe(instr, succ) {
704             if (instr->type != nir_instr_type_phi)
705                break;
706 
707             remove_no_op_phi(instr, state);
708          }
709       }
710 
711       /* The following if is right after the block, handle its condition as the
712        * last source "in" the block.
713        */
714       nir_if *nif = nir_block_get_following_if(block);
715       if (nif) {
716          state->builder.cursor = nir_before_src(&nif->condition);
717          rewrite_src(&nif->condition, state);
718       }
719 
720       nir_foreach_instr_reverse_safe(instr, block) {
721          switch (instr->type) {
722          case nir_instr_type_phi:
723             remove_no_op_phi(instr, state);
724             break;
725 
726          case nir_instr_type_parallel_copy: {
727             nir_parallel_copy_instr *pcopy = nir_instr_as_parallel_copy(instr);
728 
729             nir_foreach_parallel_copy_entry(entry, pcopy) {
730                assert(!entry->dest_is_reg);
731 
732                /* Parallel copy destinations will always be registers */
733                nir_def *reg = reg_for_ssa_def(&entry->dest.def, state);
734                assert(reg != NULL);
735 
736                /* We're switching from the nir_def to the nir_src in the dest
737                 * union so we need to use nir_instr_init_src() here.
738                 */
739                assert(nir_def_is_unused(&entry->dest.def));
740                entry->dest_is_reg = true;
741                nir_instr_init_src(&pcopy->instr, &entry->dest.reg, reg);
742             }
743 
744             nir_foreach_parallel_copy_entry(entry, pcopy) {
745                assert(!entry->src_is_reg);
746                nir_def *reg = reg_for_ssa_def(entry->src.ssa, state);
747                if (reg == NULL)
748                   continue;
749 
750                entry->src_is_reg = true;
751                nir_src_rewrite(&entry->src, reg);
752             }
753             break;
754          }
755 
756          default:
757             state->builder.cursor = nir_after_instr(instr);
758             nir_foreach_def(instr, rewrite_ssa_def, state);
759             state->builder.cursor = nir_before_instr(instr);
760             nir_foreach_src(instr, rewrite_src, state);
761          }
762       }
763    }
764 }
765 
766 /* Resolves a single parallel copy operation into a sequence of movs
767  *
768  * This is based on Algorithm 1 from "Revisiting Out-of-SSA Translation for
769  * Correctness, Code Quality, and Efficiency" by Boissinot et al.
770  * However, I never got the algorithm to work as written, so this version
771  * is slightly modified.
772  *
773  * The algorithm works by playing this little shell game with the values.
774  * We start by recording where every source value is and which source value
775  * each destination value should receive.  We then grab any copy whose
776  * destination is "empty", i.e. not used as a source, and do the following:
777  *  - Find where its source value currently lives
778  *  - Emit the move instruction
779  *  - Set the location of the source value to the destination
780  *  - Mark the location containing the source value
781  *  - Mark the destination as no longer needing to be copied
782  *
783  * When we run out of "empty" destinations, we have a cycle and so we
784  * create a temporary register, copy to that register, and mark the value
785  * we copied as living in that temporary.  Now, the cycle is broken, so we
786  * can continue with the above steps.
787  */
788 struct copy_value {
789    bool is_reg;
790    nir_def *ssa;
791 };
792 
793 static bool
copy_values_equal(struct copy_value a,struct copy_value b)794 copy_values_equal(struct copy_value a, struct copy_value b)
795 {
796    return a.is_reg == b.is_reg && a.ssa == b.ssa;
797 }
798 
799 static bool
copy_value_is_divergent(struct copy_value v)800 copy_value_is_divergent(struct copy_value v)
801 {
802    if (!v.is_reg)
803       return v.ssa->divergent;
804 
805    nir_intrinsic_instr *decl = nir_reg_get_decl(v.ssa);
806    return nir_intrinsic_divergent(decl);
807 }
808 
809 static void
copy_values(struct from_ssa_state * state,struct copy_value dest,struct copy_value src)810 copy_values(struct from_ssa_state *state, struct copy_value dest, struct copy_value src)
811 {
812    nir_def *val = src.is_reg ? nir_load_reg(&state->builder, src.ssa) : src.ssa;
813 
814    assert(!state->consider_divergence || !copy_value_is_divergent(src) || copy_value_is_divergent(dest));
815 
816    assert(dest.is_reg);
817    nir_store_reg(&state->builder, val, dest.ssa);
818 }
819 
820 static void
resolve_parallel_copy(nir_parallel_copy_instr * pcopy,struct from_ssa_state * state)821 resolve_parallel_copy(nir_parallel_copy_instr *pcopy,
822                       struct from_ssa_state *state)
823 {
824    unsigned num_copies = 0;
825    nir_foreach_parallel_copy_entry(entry, pcopy) {
826       /* Sources may be SSA but destinations are always registers */
827       assert(entry->dest_is_reg);
828       if (entry->src_is_reg && entry->src.ssa == entry->dest.reg.ssa)
829          continue;
830 
831       num_copies++;
832    }
833 
834    if (num_copies == 0) {
835       /* Hooray, we don't need any copies! */
836       nir_instr_remove(&pcopy->instr);
837       exec_list_push_tail(&state->dead_instrs, &pcopy->instr.node);
838       return;
839    }
840 
841    /* The register/source corresponding to the given index */
842    NIR_VLA_ZERO(struct copy_value, values, num_copies * 2);
843 
844    /* The current location of a given piece of data.  We will use -1 for "null" */
845    NIR_VLA_FILL(int, loc, num_copies * 2, -1);
846 
847    /* The piece of data that the given piece of data is to be copied from.  We will use -1 for "null" */
848    NIR_VLA_FILL(int, pred, num_copies * 2, -1);
849 
850    /* The destinations we have yet to properly fill */
851    NIR_VLA(int, to_do, num_copies * 2);
852    int to_do_idx = -1;
853 
854    state->builder.cursor = nir_before_instr(&pcopy->instr);
855 
856    /* Now we set everything up:
857     *  - All values get assigned a temporary index
858     *  - Current locations are set from sources
859     *  - Predecessors are recorded from sources and destinations
860     */
861    int num_vals = 0;
862    nir_foreach_parallel_copy_entry(entry, pcopy) {
863       /* Sources may be SSA but destinations are always registers */
864       if (entry->src_is_reg && entry->src.ssa == entry->dest.reg.ssa)
865          continue;
866 
867       struct copy_value src_value = {
868          .is_reg = entry->src_is_reg,
869          .ssa = entry->src.ssa,
870       };
871 
872       int src_idx = -1;
873       for (int i = 0; i < num_vals; ++i) {
874          if (copy_values_equal(values[i], src_value))
875             src_idx = i;
876       }
877       if (src_idx < 0) {
878          src_idx = num_vals++;
879          values[src_idx] = src_value;
880       }
881 
882       assert(entry->dest_is_reg);
883       struct copy_value dest_value = {
884          .is_reg = true,
885          .ssa = entry->dest.reg.ssa,
886       };
887 
888       int dest_idx = -1;
889       for (int i = 0; i < num_vals; ++i) {
890          if (copy_values_equal(values[i], dest_value)) {
891             /* Each destination of a parallel copy instruction should be
892              * unique.  A destination may get used as a source, so we still
893              * have to walk the list.  However, the predecessor should not,
894              * at this point, be set yet, so we should have -1 here.
895              */
896             assert(pred[i] == -1);
897             dest_idx = i;
898          }
899       }
900       if (dest_idx < 0) {
901          dest_idx = num_vals++;
902          values[dest_idx] = dest_value;
903       }
904 
905       loc[src_idx] = src_idx;
906       pred[dest_idx] = src_idx;
907 
908       to_do[++to_do_idx] = dest_idx;
909    }
910 
911    /* Currently empty destinations we can go ahead and fill */
912    NIR_VLA(int, ready, num_copies * 2);
913    int ready_idx = -1;
914 
915    /* Mark the ones that are ready for copying.  We know an index is a
916     * destination if it has a predecessor and it's ready for copying if
917     * it's not marked as containing data.
918     */
919    for (int i = 0; i < num_vals; i++) {
920       if (pred[i] != -1 && loc[i] == -1)
921          ready[++ready_idx] = i;
922    }
923 
924    while (1) {
925       while (ready_idx >= 0) {
926          int b = ready[ready_idx--];
927          int a = pred[b];
928          copy_values(state, values[b], values[loc[a]]);
929 
930          /* b has been filled, mark it as not needing to be copied */
931          pred[b] = -1;
932 
933          /* The next bit only applies if the source and destination have the
934           * same divergence.  If they differ (it must be convergent ->
935           * divergent), then we can't guarantee we won't need the convergent
936           * version of it again.
937           */
938          if (!state->consider_divergence ||
939              copy_value_is_divergent(values[a]) == copy_value_is_divergent(values[b])) {
940             /* If a needs to be filled... */
941             if (pred[a] != -1) {
942                /* If any other copies want a they can find it at b */
943                loc[a] = b;
944 
945                /* It's ready for copying now */
946                ready[++ready_idx] = a;
947             }
948          }
949       }
950 
951       assert(ready_idx < 0);
952       if (to_do_idx < 0)
953          break;
954 
955       int b = to_do[to_do_idx--];
956       if (pred[b] == -1)
957          continue;
958 
959       /* If we got here, then we don't have any more trivial copies that we
960        * can do.  We have to break a cycle, so we create a new temporary
961        * register for that purpose.  Normally, if going out of SSA after
962        * register allocation, you would want to avoid creating temporary
963        * registers.  However, we are going out of SSA before register
964        * allocation, so we would rather not create extra register
965        * dependencies for the backend to deal with.  If it wants, the
966        * backend can coalesce the (possibly multiple) temporaries.
967        *
968        * We can also get here in the case where there is no cycle but our
969        * source value is convergent, is also used as a destination by another
970        * element of the parallel copy, and all the destinations of the
971        * parallel copy which copy from it are divergent. In this case, the
972        * above loop cannot detect that the value has moved due to all the
973        * divergent destinations and we'll end up emitting a copy to a
974        * temporary which never gets used. We can avoid this with additional
975        * tracking or we can just trust the back-end to dead-code the unused
976        * temporary (which is trivial).
977        */
978       assert(num_vals < num_copies * 2);
979       nir_def *reg;
980       if (values[b].is_reg) {
981          nir_intrinsic_instr *decl = nir_reg_get_decl(values[b].ssa);
982          uint8_t num_components = nir_intrinsic_num_components(decl);
983          uint8_t bit_size = nir_intrinsic_bit_size(decl);
984          reg = nir_decl_reg(&state->builder, num_components, bit_size, 0);
985       } else {
986          reg = decl_reg_for_ssa_def(&state->builder, values[b].ssa);
987       }
988       if (state->consider_divergence)
989          set_reg_divergent(reg, copy_value_is_divergent(values[b]));
990 
991       values[num_vals] = (struct copy_value){
992          .is_reg = true,
993          .ssa = reg,
994       };
995       copy_values(state, values[num_vals], values[b]);
996       loc[b] = num_vals;
997       ready[++ready_idx] = b;
998       num_vals++;
999    }
1000 
1001    nir_instr_remove(&pcopy->instr);
1002    exec_list_push_tail(&state->dead_instrs, &pcopy->instr.node);
1003 }
1004 
1005 /* Resolves the parallel copies in a block.  Each block can have at most
1006  * two:  One at the beginning, right after all the phi noces, and one at
1007  * the end (or right before the final jump if it exists).
1008  */
1009 static bool
resolve_parallel_copies_block(nir_block * block,struct from_ssa_state * state)1010 resolve_parallel_copies_block(nir_block *block, struct from_ssa_state *state)
1011 {
1012    /* At this point, we have removed all of the phi nodes.  If a parallel
1013     * copy existed right after the phi nodes in this block, it is now the
1014     * first instruction.
1015     */
1016    nir_instr *first_instr = nir_block_first_instr(block);
1017    if (first_instr == NULL)
1018       return true; /* Empty, nothing to do. */
1019 
1020    /* There can be load_reg in the way of the copies... don't be clever. */
1021    nir_foreach_instr_safe(instr, block) {
1022       if (instr->type == nir_instr_type_parallel_copy) {
1023          nir_parallel_copy_instr *pcopy = nir_instr_as_parallel_copy(instr);
1024 
1025          resolve_parallel_copy(pcopy, state);
1026       }
1027    }
1028 
1029    return true;
1030 }
1031 
1032 static bool
nir_convert_from_ssa_impl(nir_function_impl * impl,bool phi_webs_only,bool consider_divergence)1033 nir_convert_from_ssa_impl(nir_function_impl *impl,
1034                           bool phi_webs_only, bool consider_divergence)
1035 {
1036    nir_shader *shader = impl->function->shader;
1037 
1038    struct from_ssa_state state;
1039 
1040    state.builder = nir_builder_create(impl);
1041    state.dead_ctx = ralloc_context(NULL);
1042    state.phi_webs_only = phi_webs_only;
1043    state.merge_node_table = _mesa_pointer_hash_table_create(NULL);
1044    state.consider_divergence = consider_divergence;
1045    state.progress = false;
1046    exec_list_make_empty(&state.dead_instrs);
1047 
1048    nir_foreach_block(block, impl) {
1049       add_parallel_copy_to_end_of_block(shader, block, state.dead_ctx);
1050    }
1051 
1052    nir_foreach_block(block, impl) {
1053       isolate_phi_nodes_block(shader, block, &state);
1054    }
1055 
1056    /* Mark metadata as dirty before we ask for liveness analysis */
1057    nir_metadata_preserve(impl, nir_metadata_control_flow);
1058 
1059    nir_metadata_require(impl, nir_metadata_instr_index |
1060                                  nir_metadata_live_defs |
1061                                  nir_metadata_dominance);
1062 
1063    nir_foreach_block(block, impl) {
1064       coalesce_phi_nodes_block(block, &state);
1065    }
1066 
1067    nir_foreach_block(block, impl) {
1068       aggressive_coalesce_block(block, &state);
1069    }
1070 
1071    resolve_registers_impl(impl, &state);
1072 
1073    nir_foreach_block(block, impl) {
1074       resolve_parallel_copies_block(block, &state);
1075    }
1076 
1077    nir_metadata_preserve(impl, nir_metadata_control_flow);
1078 
1079    /* Clean up dead instructions and the hash tables */
1080    nir_instr_free_list(&state.dead_instrs);
1081    _mesa_hash_table_destroy(state.merge_node_table, NULL);
1082    ralloc_free(state.dead_ctx);
1083    return state.progress;
1084 }
1085 
1086 bool
nir_convert_from_ssa(nir_shader * shader,bool phi_webs_only,bool consider_divergence)1087 nir_convert_from_ssa(nir_shader *shader,
1088                      bool phi_webs_only, bool consider_divergence)
1089 {
1090    bool progress = false;
1091 
1092    nir_foreach_function_impl(impl, shader) {
1093       progress |= nir_convert_from_ssa_impl(impl, phi_webs_only, consider_divergence);
1094    }
1095 
1096    return progress;
1097 }
1098 
1099 static void
place_phi_read(nir_builder * b,nir_def * reg,nir_def * def,nir_block * block,struct set * visited_blocks)1100 place_phi_read(nir_builder *b, nir_def *reg,
1101                nir_def *def, nir_block *block, struct set *visited_blocks)
1102 {
1103    /* Search already visited blocks to avoid back edges in tree */
1104    if (_mesa_set_search(visited_blocks, block) == NULL) {
1105       /* Try to go up the single-successor tree */
1106       bool all_single_successors = true;
1107       set_foreach(block->predecessors, entry) {
1108          nir_block *pred = (nir_block *)entry->key;
1109          if (pred->successors[0] && pred->successors[1]) {
1110             all_single_successors = false;
1111             break;
1112          }
1113       }
1114 
1115       if (all_single_successors) {
1116          /* All predecessors of this block have exactly one successor and it
1117           * is this block so they must eventually lead here without
1118           * intersecting each other.  Place the reads in the predecessors
1119           * instead of this block.
1120           */
1121          _mesa_set_add(visited_blocks, block);
1122 
1123          set_foreach(block->predecessors, entry) {
1124             place_phi_read(b, reg, def, (nir_block *)entry->key, visited_blocks);
1125          }
1126          return;
1127       }
1128    }
1129 
1130    b->cursor = nir_after_block_before_jump(block);
1131    nir_store_reg(b, def, reg);
1132 }
1133 
1134 /** Lower all of the phi nodes in a block to movs to and from a register
1135  *
1136  * This provides a very quick-and-dirty out-of-SSA pass that you can run on a
1137  * single block to convert all of its phis to a register and some movs.
1138  * The code that is generated, while not optimal for actual codegen in a
1139  * back-end, is easy to generate, correct, and will turn into the same set of
1140  * phis after you call regs_to_ssa and do some copy propagation.  For each phi
1141  * node we do the following:
1142  *
1143  *  1. For each phi instruction in the block, create a new nir_register
1144  *
1145  *  2. Insert movs at the top of the destination block for each phi and
1146  *     rewrite all uses of the phi to use the mov.
1147  *
1148  *  3. For each phi source, insert movs in the predecessor block from the phi
1149  *     source to the register associated with the phi.
1150  *
1151  * Correctness is guaranteed by the fact that we create a new register for
1152  * each phi and emit movs on both sides of the control-flow edge.  Because all
1153  * the phis have SSA destinations (we assert this) and there is a separate
1154  * temporary for each phi, all movs inserted in any particular block have
1155  * unique destinations so the order of operations does not matter.
1156  *
1157  * The one intelligent thing this pass does is that it places the moves from
1158  * the phi sources as high up the predecessor tree as possible instead of in
1159  * the exact predecessor.  This means that, in particular, it will crawl into
1160  * the deepest nesting of any if-ladders.  In order to ensure that doing so is
1161  * safe, it stops as soon as one of the predecessors has multiple successors.
1162  */
1163 bool
nir_lower_phis_to_regs_block(nir_block * block)1164 nir_lower_phis_to_regs_block(nir_block *block)
1165 {
1166    nir_builder b = nir_builder_create(nir_cf_node_get_function(&block->cf_node));
1167    struct set *visited_blocks = _mesa_set_create(NULL, _mesa_hash_pointer,
1168                                                  _mesa_key_pointer_equal);
1169 
1170    bool progress = false;
1171    nir_foreach_phi_safe(phi, block) {
1172       nir_def *reg = decl_reg_for_ssa_def(&b, &phi->def);
1173       set_reg_divergent(reg, phi->def.divergent);
1174 
1175       b.cursor = nir_after_instr(&phi->instr);
1176       nir_def_rewrite_uses(&phi->def, nir_load_reg(&b, reg));
1177 
1178       nir_foreach_phi_src(src, phi) {
1179 
1180          _mesa_set_add(visited_blocks, src->src.ssa->parent_instr->block);
1181          place_phi_read(&b, reg, src->src.ssa, src->pred, visited_blocks);
1182          _mesa_set_clear(visited_blocks, NULL);
1183       }
1184 
1185       nir_instr_remove(&phi->instr);
1186 
1187       progress = true;
1188    }
1189 
1190    _mesa_set_destroy(visited_blocks, NULL);
1191 
1192    return progress;
1193 }
1194 
1195 struct ssa_def_to_reg_state {
1196    nir_function_impl *impl;
1197    bool progress;
1198 };
1199 
1200 static bool
def_replace_with_reg_state(nir_def * def,void * void_state)1201 def_replace_with_reg_state(nir_def *def, void *void_state)
1202 {
1203    struct ssa_def_to_reg_state *state = void_state;
1204    state->progress |= def_replace_with_reg(def, state->impl);
1205    return true;
1206 }
1207 
1208 static bool
ssa_def_is_local_to_block(nir_def * def,UNUSED void * state)1209 ssa_def_is_local_to_block(nir_def *def, UNUSED void *state)
1210 {
1211    nir_block *block = def->parent_instr->block;
1212    nir_foreach_use_including_if(use_src, def) {
1213       if (nir_src_is_if(use_src) ||
1214           nir_src_parent_instr(use_src)->block != block ||
1215           nir_src_parent_instr(use_src)->type == nir_instr_type_phi) {
1216          return false;
1217       }
1218    }
1219 
1220    return true;
1221 }
1222 
1223 static bool
instr_is_load_new_reg(nir_instr * instr,unsigned old_num_ssa)1224 instr_is_load_new_reg(nir_instr *instr, unsigned old_num_ssa)
1225 {
1226    if (instr->type != nir_instr_type_intrinsic)
1227       return false;
1228 
1229    nir_intrinsic_instr *load = nir_instr_as_intrinsic(instr);
1230    if (load->intrinsic != nir_intrinsic_load_reg)
1231       return false;
1232 
1233    nir_def *reg = load->src[0].ssa;
1234 
1235    return reg->index >= old_num_ssa;
1236 }
1237 
1238 /** Lower all of the SSA defs in a block to registers
1239  *
1240  * This performs the very simple operation of blindly replacing all of the SSA
1241  * defs in the given block with registers.  If not used carefully, this may
1242  * result in phi nodes with register sources which is technically invalid.
1243  * Fortunately, the register-based into-SSA pass handles them anyway.
1244  */
1245 bool
nir_lower_ssa_defs_to_regs_block(nir_block * block)1246 nir_lower_ssa_defs_to_regs_block(nir_block *block)
1247 {
1248    nir_function_impl *impl = nir_cf_node_get_function(&block->cf_node);
1249    nir_builder b = nir_builder_create(impl);
1250 
1251    struct ssa_def_to_reg_state state = {
1252       .impl = impl,
1253       .progress = false,
1254    };
1255 
1256    /* Save off the current number of SSA defs so we can detect which regs
1257     * we've added vs. regs that were already there.
1258     */
1259    const unsigned num_ssa = impl->ssa_alloc;
1260 
1261    nir_foreach_instr_safe(instr, block) {
1262       if (instr->type == nir_instr_type_undef) {
1263          /* Undefs are just a read of something never written. */
1264          nir_undef_instr *undef = nir_instr_as_undef(instr);
1265          nir_def *reg = decl_reg_for_ssa_def(&b, &undef->def);
1266          nir_rewrite_uses_to_load_reg(&b, &undef->def, reg);
1267       } else if (instr->type == nir_instr_type_load_const) {
1268          nir_load_const_instr *load = nir_instr_as_load_const(instr);
1269          nir_def *reg = decl_reg_for_ssa_def(&b, &load->def);
1270          nir_rewrite_uses_to_load_reg(&b, &load->def, reg);
1271 
1272          b.cursor = nir_after_instr(instr);
1273          nir_store_reg(&b, &load->def, reg);
1274       } else if (instr_is_load_new_reg(instr, num_ssa)) {
1275          /* Calls to nir_rewrite_uses_to_load_reg() may place new load_reg
1276           * intrinsics in this block with new SSA destinations.  To avoid
1277           * infinite recursion, we don't want to lower any newly placed
1278           * load_reg instructions to yet anoter load/store_reg.
1279           */
1280       } else if (nir_foreach_def(instr, ssa_def_is_local_to_block, NULL)) {
1281          /* If the SSA def produced by this instruction is only in the block
1282           * in which it is defined and is not used by ifs or phis, then we
1283           * don't have a reason to convert it to a register.
1284           */
1285       } else {
1286          nir_foreach_def(instr, def_replace_with_reg_state, &state);
1287       }
1288    }
1289 
1290    return state.progress;
1291 }
1292