nir: Rename parallel_copy_copy to parallel_copy_entry and add a foreach macro
[mesa.git] / src / glsl / nir / nir_from_ssa.c
1 /*
2 * Copyright © 2014 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Jason Ekstrand (jason@jlekstrand.net)
25 *
26 */
27
28 #include "nir.h"
29
30 /*
31 * This file implements an out-of-SSA pass as described in "Revisiting
32 * Out-of-SSA Translation for Correctness, Code Quality, and Efficiency" by
33 * Boissinot et. al.
34 */
35
36 struct from_ssa_state {
37 void *mem_ctx;
38 void *dead_ctx;
39 struct hash_table *ssa_table;
40 struct hash_table *merge_node_table;
41 nir_instr *instr;
42 nir_function_impl *impl;
43 };
44
45 /* Returns true if a dominates b */
46 static bool
47 ssa_def_dominates(nir_ssa_def *a, nir_ssa_def *b)
48 {
49 if (a->live_index == 0) {
50 /* SSA undefs always dominate */
51 return true;
52 } else if (b->live_index < a->live_index) {
53 return false;
54 } else if (a->parent_instr->block == b->parent_instr->block) {
55 return a->live_index <= b->live_index;
56 } else {
57 nir_block *block = b->parent_instr->block;
58 while (block->imm_dom != NULL) {
59 if (block->imm_dom == a->parent_instr->block)
60 return true;
61 block = block->imm_dom;
62 }
63 return false;
64 }
65 }
66
67
68 /* The following data structure, which I have named merge_set is a way of
69 * representing a set registers of non-interfering registers. This is
70 * based on the concept of a "dominence forest" presented in "Fast Copy
71 * Coalescing and Live-Range Identification" by Budimlic et. al. but the
72 * implementation concept is taken from "Revisiting Out-of-SSA Translation
73 * for Correctness, Code Quality, and Efficiency" by Boissinot et. al..
74 *
75 * Each SSA definition is associated with a merge_node and the association
76 * is represented by a combination of a hash table and the "def" parameter
77 * in the merge_node structure. The merge_set stores a linked list of
78 * merge_node's in dominence order of the ssa definitions. (Since the
79 * liveness analysis pass indexes the SSA values in dominence order for us,
80 * this is an easy thing to keep up.) It is assumed that no pair of the
81 * nodes in a given set interfere. Merging two sets or checking for
82 * interference can be done in a single linear-time merge-sort walk of the
83 * two lists of nodes.
84 */
85 struct merge_set;
86
87 typedef struct {
88 struct exec_node node;
89 struct merge_set *set;
90 nir_ssa_def *def;
91 } merge_node;
92
93 typedef struct merge_set {
94 struct exec_list nodes;
95 unsigned size;
96 nir_register *reg;
97 } merge_set;
98
99 #if 0
100 static void
101 merge_set_dump(merge_set *set, FILE *fp)
102 {
103 nir_ssa_def *dom[set->size];
104 int dom_idx = -1;
105
106 foreach_list_typed(merge_node, node, node, &set->nodes) {
107 while (dom_idx >= 0 && !ssa_def_dominates(dom[dom_idx], node->def))
108 dom_idx--;
109
110 for (int i = 0; i <= dom_idx; i++)
111 fprintf(fp, " ");
112
113 if (node->def->name)
114 fprintf(fp, "ssa_%d /* %s */\n", node->def->index, node->def->name);
115 else
116 fprintf(fp, "ssa_%d\n", node->def->index);
117
118 dom[++dom_idx] = node->def;
119 }
120 }
121 #endif
122
123 static merge_node *
124 get_merge_node(nir_ssa_def *def, struct from_ssa_state *state)
125 {
126 struct hash_entry *entry =
127 _mesa_hash_table_search(state->merge_node_table, def);
128 if (entry)
129 return entry->data;
130
131 merge_set *set = ralloc(state->dead_ctx, merge_set);
132 exec_list_make_empty(&set->nodes);
133 set->size = 1;
134 set->reg = NULL;
135
136 merge_node *node = ralloc(state->dead_ctx, merge_node);
137 node->set = set;
138 node->def = def;
139 exec_list_push_head(&set->nodes, &node->node);
140
141 _mesa_hash_table_insert(state->merge_node_table, def, node);
142
143 return node;
144 }
145
146 static bool
147 merge_nodes_interfere(merge_node *a, merge_node *b)
148 {
149 return nir_ssa_defs_interfere(a->def, b->def);
150 }
151
152 /* Merges b into a */
153 static merge_set *
154 merge_merge_sets(merge_set *a, merge_set *b)
155 {
156 struct exec_node *an = exec_list_get_head(&a->nodes);
157 struct exec_node *bn = exec_list_get_head(&b->nodes);
158 while (!exec_node_is_tail_sentinel(bn)) {
159 merge_node *a_node = exec_node_data(merge_node, an, node);
160 merge_node *b_node = exec_node_data(merge_node, bn, node);
161
162 if (exec_node_is_tail_sentinel(an) ||
163 a_node->def->live_index > b_node->def->live_index) {
164 struct exec_node *next = bn->next;
165 exec_node_remove(bn);
166 exec_node_insert_node_before(an, bn);
167 exec_node_data(merge_node, bn, node)->set = a;
168 bn = next;
169 } else {
170 an = an->next;
171 }
172 }
173
174 a->size += b->size;
175 b->size = 0;
176
177 return a;
178 }
179
180 /* Checks for any interference between two merge sets
181 *
182 * This is an implementation of Algorithm 2 in "Revisiting Out-of-SSA
183 * Translation for Correctness, Code Quality, and Efficiency" by
184 * Boissinot et. al.
185 */
186 static bool
187 merge_sets_interfere(merge_set *a, merge_set *b)
188 {
189 merge_node *dom[a->size + b->size];
190 int dom_idx = -1;
191
192 struct exec_node *an = exec_list_get_head(&a->nodes);
193 struct exec_node *bn = exec_list_get_head(&b->nodes);
194 while (!exec_node_is_tail_sentinel(an) ||
195 !exec_node_is_tail_sentinel(bn)) {
196
197 merge_node *current;
198 if (exec_node_is_tail_sentinel(an)) {
199 current = exec_node_data(merge_node, bn, node);
200 bn = bn->next;
201 } else if (exec_node_is_tail_sentinel(bn)) {
202 current = exec_node_data(merge_node, an, node);
203 an = an->next;
204 } else {
205 merge_node *a_node = exec_node_data(merge_node, an, node);
206 merge_node *b_node = exec_node_data(merge_node, bn, node);
207
208 if (a_node->def->live_index <= b_node->def->live_index) {
209 current = a_node;
210 an = an->next;
211 } else {
212 current = b_node;
213 bn = bn->next;
214 }
215 }
216
217 while (dom_idx >= 0 &&
218 !ssa_def_dominates(dom[dom_idx]->def, current->def))
219 dom_idx--;
220
221 if (dom_idx >= 0 && merge_nodes_interfere(current, dom[dom_idx]))
222 return true;
223
224 dom[++dom_idx] = current;
225 }
226
227 return false;
228 }
229
230 static bool
231 add_parallel_copy_to_end_of_block(nir_block *block, void *void_state)
232 {
233 struct from_ssa_state *state = void_state;
234
235 bool need_end_copy = false;
236 if (block->successors[0]) {
237 nir_instr *instr = nir_block_first_instr(block->successors[0]);
238 if (instr && instr->type == nir_instr_type_phi)
239 need_end_copy = true;
240 }
241
242 if (block->successors[1]) {
243 nir_instr *instr = nir_block_first_instr(block->successors[1]);
244 if (instr && instr->type == nir_instr_type_phi)
245 need_end_copy = true;
246 }
247
248 if (need_end_copy) {
249 /* If one of our successors has at least one phi node, we need to
250 * create a parallel copy at the end of the block but before the jump
251 * (if there is one).
252 */
253 nir_parallel_copy_instr *pcopy =
254 nir_parallel_copy_instr_create(state->dead_ctx);
255
256 nir_instr *last_instr = nir_block_last_instr(block);
257 if (last_instr && last_instr->type == nir_instr_type_jump) {
258 nir_instr_insert_before(last_instr, &pcopy->instr);
259 } else {
260 nir_instr_insert_after_block(block, &pcopy->instr);
261 }
262 }
263
264 return true;
265 }
266
267 static nir_parallel_copy_instr *
268 get_parallel_copy_at_end_of_block(nir_block *block)
269 {
270 nir_instr *last_instr = nir_block_last_instr(block);
271 if (last_instr == NULL)
272 return NULL;
273
274 /* The last instruction may be a jump in which case the parallel copy is
275 * right before it.
276 */
277 if (last_instr->type == nir_instr_type_jump)
278 last_instr = nir_instr_prev(last_instr);
279
280 if (last_instr->type == nir_instr_type_parallel_copy)
281 return nir_instr_as_parallel_copy(last_instr);
282 else
283 return NULL;
284 }
285
286 /** Isolate phi nodes with parallel copies
287 *
288 * In order to solve the dependency problems with the sources and
289 * destinations of phi nodes, we first isolate them by adding parallel
290 * copies to the beginnings and ends of basic blocks. For every block with
291 * phi nodes, we add a parallel copy immediately following the last phi
292 * node that copies the destinations of all of the phi nodes to new SSA
293 * values. We also add a parallel copy to the end of every block that has
294 * a successor with phi nodes that, for each phi node in each successor,
295 * copies the corresponding sorce of the phi node and adjust the phi to
296 * used the destination of the parallel copy.
297 *
298 * In SSA form, each value has exactly one definition. What this does is
299 * ensure that each value used in a phi also has exactly one use. The
300 * destinations of phis are only used by the parallel copy immediately
301 * following the phi nodes and. Thanks to the parallel copy at the end of
302 * the predecessor block, the sources of phi nodes are are the only use of
303 * that value. This allows us to immediately assign all the sources and
304 * destinations of any given phi node to the same register without worrying
305 * about interference at all. We do coalescing to get rid of the parallel
306 * copies where possible.
307 *
308 * Before this pass can be run, we have to iterate over the blocks with
309 * add_parallel_copy_to_end_of_block to ensure that the parallel copies at
310 * the ends of blocks exist. We can create the ones at the beginnings as
311 * we go, but the ones at the ends of blocks need to be created ahead of
312 * time because of potential back-edges in the CFG.
313 */
314 static bool
315 isolate_phi_nodes_block(nir_block *block, void *void_state)
316 {
317 struct from_ssa_state *state = void_state;
318
319 nir_instr *last_phi_instr = NULL;
320 nir_foreach_instr(block, instr) {
321 /* Phi nodes only ever come at the start of a block */
322 if (instr->type != nir_instr_type_phi)
323 break;
324
325 last_phi_instr = instr;
326 }
327
328 /* If we don't have any phi's, then there's nothing for us to do. */
329 if (last_phi_instr == NULL)
330 return true;
331
332 /* If we have phi nodes, we need to create a parallel copy at the
333 * start of this block but after the phi nodes.
334 */
335 nir_parallel_copy_instr *block_pcopy =
336 nir_parallel_copy_instr_create(state->dead_ctx);
337 nir_instr_insert_after(last_phi_instr, &block_pcopy->instr);
338
339 nir_foreach_instr(block, instr) {
340 /* Phi nodes only ever come at the start of a block */
341 if (instr->type != nir_instr_type_phi)
342 break;
343
344 nir_phi_instr *phi = nir_instr_as_phi(instr);
345 assert(phi->dest.is_ssa);
346 foreach_list_typed(nir_phi_src, src, node, &phi->srcs) {
347 nir_parallel_copy_instr *pcopy =
348 get_parallel_copy_at_end_of_block(src->pred);
349 assert(pcopy);
350
351 nir_parallel_copy_entry *entry = ralloc(state->dead_ctx,
352 nir_parallel_copy_entry);
353 exec_list_push_tail(&pcopy->entries, &entry->node);
354
355 entry->src = nir_src_copy(src->src, state->dead_ctx);
356 _mesa_set_add(src->src.ssa->uses,
357 _mesa_hash_pointer(&pcopy->instr), &pcopy->instr);
358
359 entry->dest.is_ssa = true;
360 nir_ssa_def_init(&pcopy->instr, &entry->dest.ssa,
361 phi->dest.ssa.num_components, src->src.ssa->name);
362
363 struct set_entry *use_entry =
364 _mesa_set_search(src->src.ssa->uses,
365 _mesa_hash_pointer(instr), instr);
366 if (use_entry)
367 /* It is possible that a phi node can use the same source twice
368 * but for different basic blocks. If that happens, entry will
369 * be NULL because we already deleted it. This is safe
370 * because, by the time the loop is done, we will have deleted
371 * all of the sources of the phi from their respective use sets
372 * and moved them to the parallel copy definitions.
373 */
374 _mesa_set_remove(src->src.ssa->uses, use_entry);
375
376 src->src.ssa = &entry->dest.ssa;
377 _mesa_set_add(entry->dest.ssa.uses, _mesa_hash_pointer(instr), instr);
378 }
379
380 nir_parallel_copy_entry *entry = ralloc(state->dead_ctx,
381 nir_parallel_copy_entry);
382 exec_list_push_tail(&block_pcopy->entries, &entry->node);
383
384 entry->dest.is_ssa = true;
385 nir_ssa_def_init(&block_pcopy->instr, &entry->dest.ssa,
386 phi->dest.ssa.num_components, phi->dest.ssa.name);
387
388 nir_src entry_dest_src = {
389 .ssa = &entry->dest.ssa,
390 .is_ssa = true,
391 };
392 nir_ssa_def_rewrite_uses(&phi->dest.ssa, entry_dest_src, state->mem_ctx);
393
394 entry->src.is_ssa = true;
395 entry->src.ssa = &phi->dest.ssa;
396 _mesa_set_add(phi->dest.ssa.uses,
397 _mesa_hash_pointer(&block_pcopy->instr),
398 &block_pcopy->instr);
399 }
400
401 return true;
402 }
403
404 static bool
405 coalesce_phi_nodes_block(nir_block *block, void *void_state)
406 {
407 struct from_ssa_state *state = void_state;
408
409 nir_foreach_instr(block, instr) {
410 /* Phi nodes only ever come at the start of a block */
411 if (instr->type != nir_instr_type_phi)
412 break;
413
414 nir_phi_instr *phi = nir_instr_as_phi(instr);
415
416 assert(phi->dest.is_ssa);
417 merge_node *dest_node = get_merge_node(&phi->dest.ssa, state);
418
419 foreach_list_typed(nir_phi_src, src, node, &phi->srcs) {
420 assert(src->src.is_ssa);
421 merge_node *src_node = get_merge_node(src->src.ssa, state);
422 if (src_node->set != dest_node->set)
423 merge_merge_sets(dest_node->set, src_node->set);
424 }
425 }
426
427 return true;
428 }
429
430 static void
431 agressive_coalesce_parallel_copy(nir_parallel_copy_instr *pcopy,
432 struct from_ssa_state *state)
433 {
434 nir_foreach_parallel_copy_entry(pcopy, entry) {
435 if (!entry->src.is_ssa)
436 continue;
437
438 /* Since load_const instructions are SSA only, we can't replace their
439 * destinations with registers and, therefore, can't coalesce them.
440 */
441 if (entry->src.ssa->parent_instr->type == nir_instr_type_load_const)
442 continue;
443
444 /* Don't try and coalesce these */
445 if (entry->dest.ssa.num_components != entry->src.ssa->num_components)
446 continue;
447
448 merge_node *src_node = get_merge_node(entry->src.ssa, state);
449 merge_node *dest_node = get_merge_node(&entry->dest.ssa, state);
450
451 if (src_node->set == dest_node->set)
452 continue;
453
454 if (!merge_sets_interfere(src_node->set, dest_node->set))
455 merge_merge_sets(src_node->set, dest_node->set);
456 }
457 }
458
459 static bool
460 agressive_coalesce_block(nir_block *block, void *void_state)
461 {
462 struct from_ssa_state *state = void_state;
463
464 nir_parallel_copy_instr *start_pcopy = NULL;
465 nir_foreach_instr(block, instr) {
466 /* Phi nodes only ever come at the start of a block */
467 if (instr->type != nir_instr_type_phi) {
468 if (instr->type != nir_instr_type_parallel_copy)
469 break; /* The parallel copy must be right after the phis */
470
471 start_pcopy = nir_instr_as_parallel_copy(instr);
472
473 agressive_coalesce_parallel_copy(start_pcopy, state);
474
475 break;
476 }
477 }
478
479 nir_parallel_copy_instr *end_pcopy =
480 get_parallel_copy_at_end_of_block(block);
481
482 if (end_pcopy && end_pcopy != start_pcopy)
483 agressive_coalesce_parallel_copy(end_pcopy, state);
484
485 return true;
486 }
487
488 static nir_register *
489 get_register_for_ssa_def(nir_ssa_def *def, struct from_ssa_state *state)
490 {
491 struct hash_entry *entry =
492 _mesa_hash_table_search(state->merge_node_table, def);
493 if (entry) {
494 merge_node *node = (merge_node *)entry->data;
495
496 /* If it doesn't have a register yet, create one. Note that all of
497 * the things in the merge set should be the same so it doesn't
498 * matter which node's definition we use.
499 */
500 if (node->set->reg == NULL) {
501 node->set->reg = nir_local_reg_create(state->impl);
502 node->set->reg->name = def->name;
503 node->set->reg->num_components = def->num_components;
504 node->set->reg->num_array_elems = 0;
505 }
506
507 return node->set->reg;
508 }
509
510 entry = _mesa_hash_table_search(state->ssa_table, def);
511 if (entry) {
512 return (nir_register *)entry->data;
513 } else {
514 /* We leave load_const SSA values alone. They act as immediates to
515 * the backend. If it got coalesced into a phi, that's ok.
516 */
517 if (def->parent_instr->type == nir_instr_type_load_const)
518 return NULL;
519
520 nir_register *reg = nir_local_reg_create(state->impl);
521 reg->name = def->name;
522 reg->num_components = def->num_components;
523 reg->num_array_elems = 0;
524
525 _mesa_hash_table_insert(state->ssa_table, def, reg);
526 return reg;
527 }
528 }
529
530 static bool
531 rewrite_ssa_src(nir_src *src, void *void_state)
532 {
533 struct from_ssa_state *state = void_state;
534
535 if (src->is_ssa) {
536 nir_register *reg = get_register_for_ssa_def(src->ssa, state);
537
538 if (reg == NULL) {
539 assert(src->ssa->parent_instr->type == nir_instr_type_load_const);
540 return true;
541 }
542
543 memset(src, 0, sizeof *src);
544 src->reg.reg = reg;
545
546 /* We don't need to remove it from the uses set because that is going
547 * away. We just need to add it to the one for the register. */
548 _mesa_set_add(reg->uses, _mesa_hash_pointer(state->instr), state->instr);
549 }
550
551 return true;
552 }
553
554 static bool
555 rewrite_ssa_dest(nir_dest *dest, void *void_state)
556 {
557 struct from_ssa_state *state = void_state;
558
559 if (dest->is_ssa) {
560 nir_register *reg = get_register_for_ssa_def(&dest->ssa, state);
561
562 if (reg == NULL) {
563 assert(dest->ssa.parent_instr->type == nir_instr_type_load_const);
564 return true;
565 }
566
567 _mesa_set_destroy(dest->ssa.uses, NULL);
568 _mesa_set_destroy(dest->ssa.if_uses, NULL);
569
570 memset(dest, 0, sizeof *dest);
571 dest->reg.reg = reg;
572
573 _mesa_set_add(reg->defs, _mesa_hash_pointer(state->instr), state->instr);
574 }
575
576 return true;
577 }
578
579 /* Resolves ssa definitions to registers. While we're at it, we also
580 * remove phi nodes and ssa_undef instructions
581 */
582 static bool
583 resolve_registers_block(nir_block *block, void *void_state)
584 {
585 struct from_ssa_state *state = void_state;
586
587 nir_foreach_instr_safe(block, instr) {
588 state->instr = instr;
589 nir_foreach_src(instr, rewrite_ssa_src, state);
590 nir_foreach_dest(instr, rewrite_ssa_dest, state);
591
592 if (instr->type == nir_instr_type_ssa_undef ||
593 instr->type == nir_instr_type_phi) {
594 nir_instr_remove(instr);
595 ralloc_steal(state->dead_ctx, instr);
596 }
597 }
598 state->instr = NULL;
599
600 nir_if *following_if = nir_block_get_following_if(block);
601 if (following_if && following_if->condition.is_ssa) {
602 nir_register *reg = get_register_for_ssa_def(following_if->condition.ssa,
603 state);
604 if (reg) {
605 memset(&following_if->condition, 0, sizeof following_if->condition);
606 following_if->condition.reg.reg = reg;
607
608 _mesa_set_add(reg->if_uses, _mesa_hash_pointer(following_if),
609 following_if);
610 } else {
611 /* FIXME: We really shouldn't hit this. We should be doing
612 * constant control flow propagation.
613 */
614 assert(following_if->condition.ssa->parent_instr->type == nir_instr_type_load_const);
615 }
616 }
617
618 return true;
619 }
620
621 static void
622 emit_copy(nir_parallel_copy_instr *pcopy, nir_src src, nir_src dest_src,
623 void *mem_ctx)
624 {
625 assert(!dest_src.is_ssa &&
626 dest_src.reg.indirect == NULL &&
627 dest_src.reg.base_offset == 0);
628 nir_dest dest = {
629 .reg.reg = dest_src.reg.reg,
630 .reg.indirect = NULL,
631 .reg.base_offset = 0,
632 .is_ssa = false,
633 };
634
635 if (src.is_ssa)
636 assert(src.ssa->num_components >= dest.reg.reg->num_components);
637 else
638 assert(src.reg.reg->num_components >= dest.reg.reg->num_components);
639
640 nir_alu_instr *mov = nir_alu_instr_create(mem_ctx, nir_op_imov);
641 mov->src[0].src = nir_src_copy(src, mem_ctx);
642 mov->dest.dest = nir_dest_copy(dest, mem_ctx);
643 mov->dest.write_mask = (1 << dest.reg.reg->num_components) - 1;
644
645 nir_instr_insert_before(&pcopy->instr, &mov->instr);
646 }
647
648 /* Resolves a single parallel copy operation into a sequence of mov's
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 recieve. 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
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(pcopy, entry) {
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 return;
687 }
688
689 /* The register/source corresponding to the given index */
690 nir_src values[num_copies * 2];
691 memset(values, 0, sizeof values);
692
693 /* The current location of a given piece of data */
694 int loc[num_copies * 2];
695
696 /* The piece of data that the given piece of data is to be copied from */
697 int pred[num_copies * 2];
698
699 /* Initialize loc and pred. We will use -1 for "null" */
700 memset(loc, -1, sizeof loc);
701 memset(pred, -1, sizeof pred);
702
703 /* The destinations we have yet to properly fill */
704 int to_do[num_copies * 2];
705 int to_do_idx = -1;
706
707 /* Now we set everything up:
708 * - All values get assigned a temporary index
709 * - Current locations are set from sources
710 * - Predicessors are recorded from sources and destinations
711 */
712 int num_vals = 0;
713 nir_foreach_parallel_copy_entry(pcopy, entry) {
714 /* Sources may be SSA */
715 if (!entry->src.is_ssa && entry->src.reg.reg == entry->dest.reg.reg)
716 continue;
717
718 int src_idx = -1;
719 for (int i = 0; i < num_vals; ++i) {
720 if (nir_srcs_equal(values[i], entry->src))
721 src_idx = i;
722 }
723 if (src_idx < 0) {
724 src_idx = num_vals++;
725 values[src_idx] = entry->src;
726 }
727
728 nir_src dest_src = {
729 .reg.reg = entry->dest.reg.reg,
730 .reg.indirect = NULL,
731 .reg.base_offset = 0,
732 .is_ssa = false,
733 };
734
735 int dest_idx = -1;
736 for (int i = 0; i < num_vals; ++i) {
737 if (nir_srcs_equal(values[i], dest_src)) {
738 /* Each destination of a parallel copy instruction should be
739 * unique. A destination may get used as a source, so we still
740 * have to walk the list. However, the predecessor should not,
741 * at this point, be set yet, so we should have -1 here.
742 */
743 assert(pred[i] == -1);
744 dest_idx = i;
745 }
746 }
747 if (dest_idx < 0) {
748 dest_idx = num_vals++;
749 values[dest_idx] = dest_src;
750 }
751
752 loc[src_idx] = src_idx;
753 pred[dest_idx] = src_idx;
754
755 to_do[++to_do_idx] = dest_idx;
756 }
757
758 /* Currently empty destinations we can go ahead and fill */
759 int ready[num_copies * 2];
760 int ready_idx = -1;
761
762 /* Mark the ones that are ready for copying. We know an index is a
763 * destination if it has a predecessor and it's ready for copying if
764 * it's not marked as containing data.
765 */
766 for (int i = 0; i < num_vals; i++) {
767 if (pred[i] != -1 && loc[i] == -1)
768 ready[++ready_idx] = i;
769 }
770
771 while (to_do_idx >= 0) {
772 while (ready_idx >= 0) {
773 int b = ready[ready_idx--];
774 int a = pred[b];
775 emit_copy(pcopy, values[loc[a]], values[b], state->mem_ctx);
776
777 /* If any other copies want a they can find it at b */
778 loc[a] = b;
779
780 /* b has been filled, mark it as not needing to be copied */
781 pred[b] = -1;
782
783 /* If a needs to be filled, it's ready for copying now */
784 if (pred[a] != -1)
785 ready[++ready_idx] = a;
786 }
787 int b = to_do[to_do_idx--];
788 if (pred[b] == -1)
789 continue;
790
791 /* If we got here, then we don't have any more trivial copies that we
792 * can do. We have to break a cycle, so we create a new temporary
793 * register for that purpose. Normally, if going out of SSA after
794 * register allocation, you would want to avoid creating temporary
795 * registers. However, we are going out of SSA before register
796 * allocation, so we would rather not create extra register
797 * dependencies for the backend to deal with. If it wants, the
798 * backend can coalesce the (possibly multiple) temporaries.
799 */
800 assert(num_vals < num_copies * 2);
801 nir_register *reg = nir_local_reg_create(state->impl);
802 reg->name = "copy_temp";
803 reg->num_array_elems = 0;
804 if (values[b].is_ssa)
805 reg->num_components = values[b].ssa->num_components;
806 else
807 reg->num_components = values[b].reg.reg->num_components;
808 values[num_vals].is_ssa = false;
809 values[num_vals].reg.reg = reg;
810
811 emit_copy(pcopy, values[b], values[num_vals], state->mem_ctx);
812 loc[b] = num_vals;
813 ready[++ready_idx] = b;
814 num_vals++;
815 }
816
817 nir_instr_remove(&pcopy->instr);
818 }
819
820 /* Resolves the parallel copies in a block. Each block can have at most
821 * two: One at the beginning, right after all the phi noces, and one at
822 * the end (or right before the final jump if it exists).
823 */
824 static bool
825 resolve_parallel_copies_block(nir_block *block, void *void_state)
826 {
827 struct from_ssa_state *state = void_state;
828
829 /* At this point, we have removed all of the phi nodes. If a parallel
830 * copy existed right after the phi nodes in this block, it is now the
831 * first instruction.
832 */
833 nir_instr *first_instr = nir_block_first_instr(block);
834 if (first_instr == NULL)
835 return true; /* Empty, nothing to do. */
836
837 if (first_instr->type == nir_instr_type_parallel_copy) {
838 nir_parallel_copy_instr *pcopy = nir_instr_as_parallel_copy(first_instr);
839
840 resolve_parallel_copy(pcopy, state);
841 }
842
843 /* It's possible that the above code already cleaned up the end parallel
844 * copy. However, doing so removed it form the instructions list so we
845 * won't find it here. Therefore, it's safe to go ahead and just look
846 * for one and clean it up if it exists.
847 */
848 nir_parallel_copy_instr *end_pcopy =
849 get_parallel_copy_at_end_of_block(block);
850 if (end_pcopy)
851 resolve_parallel_copy(end_pcopy, state);
852
853 return true;
854 }
855
856 static void
857 nir_convert_from_ssa_impl(nir_function_impl *impl)
858 {
859 struct from_ssa_state state;
860
861 state.mem_ctx = ralloc_parent(impl);
862 state.dead_ctx = ralloc_context(NULL);
863 state.impl = impl;
864 state.merge_node_table = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
865 _mesa_key_pointer_equal);
866
867 nir_foreach_block(impl, add_parallel_copy_to_end_of_block, &state);
868 nir_foreach_block(impl, isolate_phi_nodes_block, &state);
869
870 /* Mark metadata as dirty before we ask for liveness analysis */
871 nir_metadata_preserve(impl, nir_metadata_block_index |
872 nir_metadata_dominance);
873
874 nir_metadata_require(impl, nir_metadata_live_variables |
875 nir_metadata_dominance);
876
877 nir_foreach_block(impl, coalesce_phi_nodes_block, &state);
878 nir_foreach_block(impl, agressive_coalesce_block, &state);
879
880 state.ssa_table = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
881 _mesa_key_pointer_equal);
882 nir_foreach_block(impl, resolve_registers_block, &state);
883
884 nir_foreach_block(impl, resolve_parallel_copies_block, &state);
885
886 nir_metadata_preserve(impl, nir_metadata_block_index |
887 nir_metadata_dominance);
888
889 /* Clean up dead instructions and the hash tables */
890 _mesa_hash_table_destroy(state.ssa_table, NULL);
891 _mesa_hash_table_destroy(state.merge_node_table, NULL);
892 ralloc_free(state.dead_ctx);
893 }
894
895 void
896 nir_convert_from_ssa(nir_shader *shader)
897 {
898 nir_foreach_overload(shader, overload) {
899 if (overload->impl)
900 nir_convert_from_ssa_impl(overload->impl);
901 }
902 }