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