Path: blob/21.2-virgl/src/compiler/nir/nir_from_ssa.c
4549 views
/*1* Copyright © 2014 Intel Corporation2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20* IN THE SOFTWARE.21*22* Authors:23* Jason Ekstrand ([email protected])24*25*/2627#include "nir.h"28#include "nir_builder.h"29#include "nir_vla.h"3031/*32* This file implements an out-of-SSA pass as described in "Revisiting33* Out-of-SSA Translation for Correctness, Code Quality, and Efficiency" by34* Boissinot et al.35*/3637struct from_ssa_state {38nir_builder builder;39void *dead_ctx;40bool phi_webs_only;41struct hash_table *merge_node_table;42nir_instr *instr;43bool progress;44};4546/* Returns if def @a comes after def @b.47*48* The core observation that makes the Boissinot algorithm efficient49* is that, given two properly sorted sets, we can check for50* interference in these sets via a linear walk. This is accomplished51* by doing single combined walk over union of the two sets in DFS52* order. It doesn't matter what DFS we do so long as we're53* consistent. Fortunately, the dominance algorithm we ran prior to54* this pass did such a walk and recorded the pre- and post-indices in55* the blocks.56*57* We treat SSA undefs as always coming before other instruction types.58*/59static bool60def_after(nir_ssa_def *a, nir_ssa_def *b)61{62if (a->parent_instr->type == nir_instr_type_ssa_undef)63return false;6465if (b->parent_instr->type == nir_instr_type_ssa_undef)66return true;6768/* If they're in the same block, we can rely on whichever instruction69* comes first in the block.70*/71if (a->parent_instr->block == b->parent_instr->block)72return a->parent_instr->index > b->parent_instr->index;7374/* Otherwise, if blocks are distinct, we sort them in DFS pre-order */75return a->parent_instr->block->dom_pre_index >76b->parent_instr->block->dom_pre_index;77}7879/* Returns true if a dominates b */80static bool81ssa_def_dominates(nir_ssa_def *a, nir_ssa_def *b)82{83if (a->parent_instr->type == nir_instr_type_ssa_undef) {84/* SSA undefs always dominate */85return true;86} if (def_after(a, b)) {87return false;88} else if (a->parent_instr->block == b->parent_instr->block) {89return def_after(b, a);90} else {91return nir_block_dominates(a->parent_instr->block,92b->parent_instr->block);93}94}959697/* The following data structure, which I have named merge_set is a way of98* representing a set registers of non-interfering registers. This is99* based on the concept of a "dominance forest" presented in "Fast Copy100* Coalescing and Live-Range Identification" by Budimlic et al. but the101* implementation concept is taken from "Revisiting Out-of-SSA Translation102* for Correctness, Code Quality, and Efficiency" by Boissinot et al.103*104* Each SSA definition is associated with a merge_node and the association105* is represented by a combination of a hash table and the "def" parameter106* in the merge_node structure. The merge_set stores a linked list of107* merge_nodes in dominance order of the ssa definitions. (Since the108* liveness analysis pass indexes the SSA values in dominance order for us,109* this is an easy thing to keep up.) It is assumed that no pair of the110* nodes in a given set interfere. Merging two sets or checking for111* interference can be done in a single linear-time merge-sort walk of the112* two lists of nodes.113*/114struct merge_set;115116typedef struct {117struct exec_node node;118struct merge_set *set;119nir_ssa_def *def;120} merge_node;121122typedef struct merge_set {123struct exec_list nodes;124unsigned size;125bool divergent;126nir_register *reg;127} merge_set;128129#if 0130static void131merge_set_dump(merge_set *set, FILE *fp)132{133nir_ssa_def *dom[set->size];134int dom_idx = -1;135136foreach_list_typed(merge_node, node, node, &set->nodes) {137while (dom_idx >= 0 && !ssa_def_dominates(dom[dom_idx], node->def))138dom_idx--;139140for (int i = 0; i <= dom_idx; i++)141fprintf(fp, " ");142143fprintf(fp, "ssa_%d\n", node->def->index);144145dom[++dom_idx] = node->def;146}147}148#endif149150static merge_node *151get_merge_node(nir_ssa_def *def, struct from_ssa_state *state)152{153struct hash_entry *entry =154_mesa_hash_table_search(state->merge_node_table, def);155if (entry)156return entry->data;157158merge_set *set = ralloc(state->dead_ctx, merge_set);159exec_list_make_empty(&set->nodes);160set->size = 1;161set->divergent = def->divergent;162set->reg = NULL;163164merge_node *node = ralloc(state->dead_ctx, merge_node);165node->set = set;166node->def = def;167exec_list_push_head(&set->nodes, &node->node);168169_mesa_hash_table_insert(state->merge_node_table, def, node);170171return node;172}173174static bool175merge_nodes_interfere(merge_node *a, merge_node *b)176{177/* There's no need to check for interference within the same set,178* because we assume, that sets themselves are already179* interference-free.180*/181if (a->set == b->set)182return false;183184return nir_ssa_defs_interfere(a->def, b->def);185}186187/* Merges b into a */188static merge_set *189merge_merge_sets(merge_set *a, merge_set *b)190{191struct exec_node *an = exec_list_get_head(&a->nodes);192struct exec_node *bn = exec_list_get_head(&b->nodes);193while (!exec_node_is_tail_sentinel(bn)) {194merge_node *a_node = exec_node_data(merge_node, an, node);195merge_node *b_node = exec_node_data(merge_node, bn, node);196197if (exec_node_is_tail_sentinel(an) ||198def_after(a_node->def, b_node->def)) {199struct exec_node *next = bn->next;200exec_node_remove(bn);201exec_node_insert_node_before(an, bn);202exec_node_data(merge_node, bn, node)->set = a;203bn = next;204} else {205an = an->next;206}207}208209a->size += b->size;210b->size = 0;211a->divergent |= b->divergent;212213return a;214}215216/* Checks for any interference between two merge sets217*218* This is an implementation of Algorithm 2 in "Revisiting Out-of-SSA219* Translation for Correctness, Code Quality, and Efficiency" by220* Boissinot et al.221*/222static bool223merge_sets_interfere(merge_set *a, merge_set *b)224{225NIR_VLA(merge_node *, dom, a->size + b->size);226int dom_idx = -1;227228struct exec_node *an = exec_list_get_head(&a->nodes);229struct exec_node *bn = exec_list_get_head(&b->nodes);230while (!exec_node_is_tail_sentinel(an) ||231!exec_node_is_tail_sentinel(bn)) {232233merge_node *current;234if (exec_node_is_tail_sentinel(an)) {235current = exec_node_data(merge_node, bn, node);236bn = bn->next;237} else if (exec_node_is_tail_sentinel(bn)) {238current = exec_node_data(merge_node, an, node);239an = an->next;240} else {241merge_node *a_node = exec_node_data(merge_node, an, node);242merge_node *b_node = exec_node_data(merge_node, bn, node);243244if (def_after(b_node->def, a_node->def)) {245current = a_node;246an = an->next;247} else {248current = b_node;249bn = bn->next;250}251}252253while (dom_idx >= 0 &&254!ssa_def_dominates(dom[dom_idx]->def, current->def))255dom_idx--;256257if (dom_idx >= 0 && merge_nodes_interfere(current, dom[dom_idx]))258return true;259260dom[++dom_idx] = current;261}262263return false;264}265266static bool267add_parallel_copy_to_end_of_block(nir_block *block, void *dead_ctx)268{269270bool need_end_copy = false;271if (block->successors[0]) {272nir_instr *instr = nir_block_first_instr(block->successors[0]);273if (instr && instr->type == nir_instr_type_phi)274need_end_copy = true;275}276277if (block->successors[1]) {278nir_instr *instr = nir_block_first_instr(block->successors[1]);279if (instr && instr->type == nir_instr_type_phi)280need_end_copy = true;281}282283if (need_end_copy) {284/* If one of our successors has at least one phi node, we need to285* create a parallel copy at the end of the block but before the jump286* (if there is one).287*/288nir_parallel_copy_instr *pcopy =289nir_parallel_copy_instr_create(dead_ctx);290291nir_instr_insert(nir_after_block_before_jump(block), &pcopy->instr);292}293294return true;295}296297static nir_parallel_copy_instr *298get_parallel_copy_at_end_of_block(nir_block *block)299{300nir_instr *last_instr = nir_block_last_instr(block);301if (last_instr == NULL)302return NULL;303304/* The last instruction may be a jump in which case the parallel copy is305* right before it.306*/307if (last_instr->type == nir_instr_type_jump)308last_instr = nir_instr_prev(last_instr);309310if (last_instr && last_instr->type == nir_instr_type_parallel_copy)311return nir_instr_as_parallel_copy(last_instr);312else313return NULL;314}315316/** Isolate phi nodes with parallel copies317*318* In order to solve the dependency problems with the sources and319* destinations of phi nodes, we first isolate them by adding parallel320* copies to the beginnings and ends of basic blocks. For every block with321* phi nodes, we add a parallel copy immediately following the last phi322* node that copies the destinations of all of the phi nodes to new SSA323* values. We also add a parallel copy to the end of every block that has324* a successor with phi nodes that, for each phi node in each successor,325* copies the corresponding sorce of the phi node and adjust the phi to326* used the destination of the parallel copy.327*328* In SSA form, each value has exactly one definition. What this does is329* ensure that each value used in a phi also has exactly one use. The330* destinations of phis are only used by the parallel copy immediately331* following the phi nodes and. Thanks to the parallel copy at the end of332* the predecessor block, the sources of phi nodes are are the only use of333* that value. This allows us to immediately assign all the sources and334* destinations of any given phi node to the same register without worrying335* about interference at all. We do coalescing to get rid of the parallel336* copies where possible.337*338* Before this pass can be run, we have to iterate over the blocks with339* add_parallel_copy_to_end_of_block to ensure that the parallel copies at340* the ends of blocks exist. We can create the ones at the beginnings as341* we go, but the ones at the ends of blocks need to be created ahead of342* time because of potential back-edges in the CFG.343*/344static bool345isolate_phi_nodes_block(nir_block *block, void *dead_ctx)346{347nir_instr *last_phi_instr = NULL;348nir_foreach_instr(instr, block) {349/* Phi nodes only ever come at the start of a block */350if (instr->type != nir_instr_type_phi)351break;352353last_phi_instr = instr;354}355356/* If we don't have any phis, then there's nothing for us to do. */357if (last_phi_instr == NULL)358return true;359360/* If we have phi nodes, we need to create a parallel copy at the361* start of this block but after the phi nodes.362*/363nir_parallel_copy_instr *block_pcopy =364nir_parallel_copy_instr_create(dead_ctx);365nir_instr_insert_after(last_phi_instr, &block_pcopy->instr);366367nir_foreach_instr(instr, block) {368/* Phi nodes only ever come at the start of a block */369if (instr->type != nir_instr_type_phi)370break;371372nir_phi_instr *phi = nir_instr_as_phi(instr);373assert(phi->dest.is_ssa);374nir_foreach_phi_src(src, phi) {375nir_parallel_copy_instr *pcopy =376get_parallel_copy_at_end_of_block(src->pred);377assert(pcopy);378379nir_parallel_copy_entry *entry = rzalloc(dead_ctx,380nir_parallel_copy_entry);381nir_ssa_dest_init(&pcopy->instr, &entry->dest,382phi->dest.ssa.num_components,383phi->dest.ssa.bit_size, NULL);384entry->dest.ssa.divergent = nir_src_is_divergent(src->src);385exec_list_push_tail(&pcopy->entries, &entry->node);386387assert(src->src.is_ssa);388nir_instr_rewrite_src(&pcopy->instr, &entry->src, src->src);389390nir_instr_rewrite_src(&phi->instr, &src->src,391nir_src_for_ssa(&entry->dest.ssa));392}393394nir_parallel_copy_entry *entry = rzalloc(dead_ctx,395nir_parallel_copy_entry);396nir_ssa_dest_init(&block_pcopy->instr, &entry->dest,397phi->dest.ssa.num_components, phi->dest.ssa.bit_size,398NULL);399entry->dest.ssa.divergent = phi->dest.ssa.divergent;400exec_list_push_tail(&block_pcopy->entries, &entry->node);401402nir_ssa_def_rewrite_uses(&phi->dest.ssa,403&entry->dest.ssa);404405nir_instr_rewrite_src(&block_pcopy->instr, &entry->src,406nir_src_for_ssa(&phi->dest.ssa));407}408409return true;410}411412static bool413coalesce_phi_nodes_block(nir_block *block, struct from_ssa_state *state)414{415nir_foreach_instr(instr, block) {416/* Phi nodes only ever come at the start of a block */417if (instr->type != nir_instr_type_phi)418break;419420nir_phi_instr *phi = nir_instr_as_phi(instr);421422assert(phi->dest.is_ssa);423merge_node *dest_node = get_merge_node(&phi->dest.ssa, state);424425nir_foreach_phi_src(src, phi) {426assert(src->src.is_ssa);427merge_node *src_node = get_merge_node(src->src.ssa, state);428if (src_node->set != dest_node->set)429merge_merge_sets(dest_node->set, src_node->set);430}431}432433return true;434}435436static void437aggressive_coalesce_parallel_copy(nir_parallel_copy_instr *pcopy,438struct from_ssa_state *state)439{440nir_foreach_parallel_copy_entry(entry, pcopy) {441if (!entry->src.is_ssa)442continue;443444/* Since load_const instructions are SSA only, we can't replace their445* destinations with registers and, therefore, can't coalesce them.446*/447if (entry->src.ssa->parent_instr->type == nir_instr_type_load_const)448continue;449450/* Don't try and coalesce these */451if (entry->dest.ssa.num_components != entry->src.ssa->num_components)452continue;453454merge_node *src_node = get_merge_node(entry->src.ssa, state);455merge_node *dest_node = get_merge_node(&entry->dest.ssa, state);456457if (src_node->set == dest_node->set)458continue;459460/* TODO: We can probably do better here but for now we should be safe if461* we just don't coalesce things with different divergence.462*/463if (dest_node->set->divergent != src_node->set->divergent)464continue;465466if (!merge_sets_interfere(src_node->set, dest_node->set))467merge_merge_sets(src_node->set, dest_node->set);468}469}470471static bool472aggressive_coalesce_block(nir_block *block, struct from_ssa_state *state)473{474nir_parallel_copy_instr *start_pcopy = NULL;475nir_foreach_instr(instr, block) {476/* Phi nodes only ever come at the start of a block */477if (instr->type != nir_instr_type_phi) {478if (instr->type != nir_instr_type_parallel_copy)479break; /* The parallel copy must be right after the phis */480481start_pcopy = nir_instr_as_parallel_copy(instr);482483aggressive_coalesce_parallel_copy(start_pcopy, state);484485break;486}487}488489nir_parallel_copy_instr *end_pcopy =490get_parallel_copy_at_end_of_block(block);491492if (end_pcopy && end_pcopy != start_pcopy)493aggressive_coalesce_parallel_copy(end_pcopy, state);494495return true;496}497498static nir_register *499create_reg_for_ssa_def(nir_ssa_def *def, nir_function_impl *impl)500{501nir_register *reg = nir_local_reg_create(impl);502503reg->num_components = def->num_components;504reg->bit_size = def->bit_size;505reg->num_array_elems = 0;506507return reg;508}509510static bool511rewrite_ssa_def(nir_ssa_def *def, void *void_state)512{513struct from_ssa_state *state = void_state;514nir_register *reg;515516struct hash_entry *entry =517_mesa_hash_table_search(state->merge_node_table, def);518if (entry) {519/* In this case, we're part of a phi web. Use the web's register. */520merge_node *node = (merge_node *)entry->data;521522/* If it doesn't have a register yet, create one. Note that all of523* the things in the merge set should be the same so it doesn't524* matter which node's definition we use.525*/526if (node->set->reg == NULL) {527node->set->reg = create_reg_for_ssa_def(def, state->builder.impl);528node->set->reg->divergent = node->set->divergent;529}530531reg = node->set->reg;532} else {533if (state->phi_webs_only)534return true;535536/* We leave load_const SSA values alone. They act as immediates to537* the backend. If it got coalesced into a phi, that's ok.538*/539if (def->parent_instr->type == nir_instr_type_load_const)540return true;541542reg = create_reg_for_ssa_def(def, state->builder.impl);543}544545nir_ssa_def_rewrite_uses_src(def, nir_src_for_reg(reg));546assert(nir_ssa_def_is_unused(def));547548if (def->parent_instr->type == nir_instr_type_ssa_undef) {549/* If it's an ssa_undef instruction, remove it since we know we just got550* rid of all its uses.551*/552nir_instr *parent_instr = def->parent_instr;553nir_instr_remove(parent_instr);554ralloc_steal(state->dead_ctx, parent_instr);555state->progress = true;556return true;557}558559assert(def->parent_instr->type != nir_instr_type_load_const);560561/* At this point we know a priori that this SSA def is part of a562* nir_dest. We can use exec_node_data to get the dest pointer.563*/564nir_dest *dest = exec_node_data(nir_dest, def, ssa);565566nir_instr_rewrite_dest(state->instr, dest, nir_dest_for_reg(reg));567state->progress = true;568return true;569}570571/* Resolves ssa definitions to registers. While we're at it, we also572* remove phi nodes.573*/574static void575resolve_registers_block(nir_block *block, struct from_ssa_state *state)576{577nir_foreach_instr_safe(instr, block) {578state->instr = instr;579nir_foreach_ssa_def(instr, rewrite_ssa_def, state);580581if (instr->type == nir_instr_type_phi) {582nir_instr_remove(instr);583ralloc_steal(state->dead_ctx, instr);584state->progress = true;585}586}587state->instr = NULL;588}589590static void591emit_copy(nir_builder *b, nir_src src, nir_src dest_src)592{593assert(!dest_src.is_ssa &&594dest_src.reg.indirect == NULL &&595dest_src.reg.base_offset == 0);596597assert(!nir_src_is_divergent(src) || nir_src_is_divergent(dest_src));598599if (src.is_ssa)600assert(src.ssa->num_components >= dest_src.reg.reg->num_components);601else602assert(src.reg.reg->num_components >= dest_src.reg.reg->num_components);603604nir_alu_instr *mov = nir_alu_instr_create(b->shader, nir_op_mov);605nir_src_copy(&mov->src[0].src, &src, mov);606mov->dest.dest = nir_dest_for_reg(dest_src.reg.reg);607mov->dest.write_mask = (1 << dest_src.reg.reg->num_components) - 1;608609nir_builder_instr_insert(b, &mov->instr);610}611612/* Resolves a single parallel copy operation into a sequence of movs613*614* This is based on Algorithm 1 from "Revisiting Out-of-SSA Translation for615* Correctness, Code Quality, and Efficiency" by Boissinot et al.616* However, I never got the algorithm to work as written, so this version617* is slightly modified.618*619* The algorithm works by playing this little shell game with the values.620* We start by recording where every source value is and which source value621* each destination value should receive. We then grab any copy whose622* destination is "empty", i.e. not used as a source, and do the following:623* - Find where its source value currently lives624* - Emit the move instruction625* - Set the location of the source value to the destination626* - Mark the location containing the source value627* - Mark the destination as no longer needing to be copied628*629* When we run out of "empty" destinations, we have a cycle and so we630* create a temporary register, copy to that register, and mark the value631* we copied as living in that temporary. Now, the cycle is broken, so we632* can continue with the above steps.633*/634static void635resolve_parallel_copy(nir_parallel_copy_instr *pcopy,636struct from_ssa_state *state)637{638unsigned num_copies = 0;639nir_foreach_parallel_copy_entry(entry, pcopy) {640/* Sources may be SSA */641if (!entry->src.is_ssa && entry->src.reg.reg == entry->dest.reg.reg)642continue;643644num_copies++;645}646647if (num_copies == 0) {648/* Hooray, we don't need any copies! */649nir_instr_remove(&pcopy->instr);650return;651}652653/* The register/source corresponding to the given index */654NIR_VLA_ZERO(nir_src, values, num_copies * 2);655656/* The current location of a given piece of data. We will use -1 for "null" */657NIR_VLA_FILL(int, loc, num_copies * 2, -1);658659/* The piece of data that the given piece of data is to be copied from. We will use -1 for "null" */660NIR_VLA_FILL(int, pred, num_copies * 2, -1);661662/* The destinations we have yet to properly fill */663NIR_VLA(int, to_do, num_copies * 2);664int to_do_idx = -1;665666state->builder.cursor = nir_before_instr(&pcopy->instr);667668/* Now we set everything up:669* - All values get assigned a temporary index670* - Current locations are set from sources671* - Predicessors are recorded from sources and destinations672*/673int num_vals = 0;674nir_foreach_parallel_copy_entry(entry, pcopy) {675/* Sources may be SSA */676if (!entry->src.is_ssa && entry->src.reg.reg == entry->dest.reg.reg)677continue;678679int src_idx = -1;680for (int i = 0; i < num_vals; ++i) {681if (nir_srcs_equal(values[i], entry->src))682src_idx = i;683}684if (src_idx < 0) {685src_idx = num_vals++;686values[src_idx] = entry->src;687}688689nir_src dest_src = nir_src_for_reg(entry->dest.reg.reg);690691int dest_idx = -1;692for (int i = 0; i < num_vals; ++i) {693if (nir_srcs_equal(values[i], dest_src)) {694/* Each destination of a parallel copy instruction should be695* unique. A destination may get used as a source, so we still696* have to walk the list. However, the predecessor should not,697* at this point, be set yet, so we should have -1 here.698*/699assert(pred[i] == -1);700dest_idx = i;701}702}703if (dest_idx < 0) {704dest_idx = num_vals++;705values[dest_idx] = dest_src;706}707708loc[src_idx] = src_idx;709pred[dest_idx] = src_idx;710711to_do[++to_do_idx] = dest_idx;712}713714/* Currently empty destinations we can go ahead and fill */715NIR_VLA(int, ready, num_copies * 2);716int ready_idx = -1;717718/* Mark the ones that are ready for copying. We know an index is a719* destination if it has a predecessor and it's ready for copying if720* it's not marked as containing data.721*/722for (int i = 0; i < num_vals; i++) {723if (pred[i] != -1 && loc[i] == -1)724ready[++ready_idx] = i;725}726727while (to_do_idx >= 0) {728while (ready_idx >= 0) {729int b = ready[ready_idx--];730int a = pred[b];731emit_copy(&state->builder, values[loc[a]], values[b]);732733/* b has been filled, mark it as not needing to be copied */734pred[b] = -1;735736/* The next bit only applies if the source and destination have the737* same divergence. If they differ (it must be convergent ->738* divergent), then we can't guarantee we won't need the convergent739* version of again.740*/741if (nir_src_is_divergent(values[a]) ==742nir_src_is_divergent(values[b])) {743/* If any other copies want a they can find it at b but only if the744* two have the same divergence.745*/746loc[a] = b;747748/* If a needs to be filled... */749if (pred[a] != -1) {750/* If any other copies want a they can find it at b */751loc[a] = b;752753/* It's ready for copying now */754ready[++ready_idx] = a;755}756}757}758int b = to_do[to_do_idx--];759if (pred[b] == -1)760continue;761762/* If we got here, then we don't have any more trivial copies that we763* can do. We have to break a cycle, so we create a new temporary764* register for that purpose. Normally, if going out of SSA after765* register allocation, you would want to avoid creating temporary766* registers. However, we are going out of SSA before register767* allocation, so we would rather not create extra register768* dependencies for the backend to deal with. If it wants, the769* backend can coalesce the (possibly multiple) temporaries.770*/771assert(num_vals < num_copies * 2);772nir_register *reg = nir_local_reg_create(state->builder.impl);773reg->num_array_elems = 0;774if (values[b].is_ssa) {775reg->num_components = values[b].ssa->num_components;776reg->bit_size = values[b].ssa->bit_size;777} else {778reg->num_components = values[b].reg.reg->num_components;779reg->bit_size = values[b].reg.reg->bit_size;780}781reg->divergent = nir_src_is_divergent(values[b]);782values[num_vals].is_ssa = false;783values[num_vals].reg.reg = reg;784785emit_copy(&state->builder, values[b], values[num_vals]);786loc[b] = num_vals;787ready[++ready_idx] = b;788num_vals++;789}790791nir_instr_remove(&pcopy->instr);792}793794/* Resolves the parallel copies in a block. Each block can have at most795* two: One at the beginning, right after all the phi noces, and one at796* the end (or right before the final jump if it exists).797*/798static bool799resolve_parallel_copies_block(nir_block *block, struct from_ssa_state *state)800{801/* At this point, we have removed all of the phi nodes. If a parallel802* copy existed right after the phi nodes in this block, it is now the803* first instruction.804*/805nir_instr *first_instr = nir_block_first_instr(block);806if (first_instr == NULL)807return true; /* Empty, nothing to do. */808809if (first_instr->type == nir_instr_type_parallel_copy) {810nir_parallel_copy_instr *pcopy = nir_instr_as_parallel_copy(first_instr);811812resolve_parallel_copy(pcopy, state);813}814815/* It's possible that the above code already cleaned up the end parallel816* copy. However, doing so removed it form the instructions list so we817* won't find it here. Therefore, it's safe to go ahead and just look818* for one and clean it up if it exists.819*/820nir_parallel_copy_instr *end_pcopy =821get_parallel_copy_at_end_of_block(block);822if (end_pcopy)823resolve_parallel_copy(end_pcopy, state);824825return true;826}827828static bool829nir_convert_from_ssa_impl(nir_function_impl *impl, bool phi_webs_only)830{831struct from_ssa_state state;832833nir_builder_init(&state.builder, impl);834state.dead_ctx = ralloc_context(NULL);835state.phi_webs_only = phi_webs_only;836state.merge_node_table = _mesa_pointer_hash_table_create(NULL);837state.progress = false;838839nir_foreach_block(block, impl) {840add_parallel_copy_to_end_of_block(block, state.dead_ctx);841}842843nir_foreach_block(block, impl) {844isolate_phi_nodes_block(block, state.dead_ctx);845}846847/* Mark metadata as dirty before we ask for liveness analysis */848nir_metadata_preserve(impl, nir_metadata_block_index |849nir_metadata_dominance);850851nir_metadata_require(impl, nir_metadata_instr_index |852nir_metadata_live_ssa_defs |853nir_metadata_dominance);854855nir_foreach_block(block, impl) {856coalesce_phi_nodes_block(block, &state);857}858859nir_foreach_block(block, impl) {860aggressive_coalesce_block(block, &state);861}862863nir_foreach_block(block, impl) {864resolve_registers_block(block, &state);865}866867nir_foreach_block(block, impl) {868resolve_parallel_copies_block(block, &state);869}870871nir_metadata_preserve(impl, nir_metadata_block_index |872nir_metadata_dominance);873874/* Clean up dead instructions and the hash tables */875_mesa_hash_table_destroy(state.merge_node_table, NULL);876ralloc_free(state.dead_ctx);877return state.progress;878}879880bool881nir_convert_from_ssa(nir_shader *shader, bool phi_webs_only)882{883bool progress = false;884885nir_foreach_function(function, shader) {886if (function->impl)887progress |= nir_convert_from_ssa_impl(function->impl, phi_webs_only);888}889890return progress;891}892893894static void895place_phi_read(nir_builder *b, nir_register *reg,896nir_ssa_def *def, nir_block *block, unsigned depth)897{898if (block != def->parent_instr->block) {899/* Try to go up the single-successor tree */900bool all_single_successors = true;901set_foreach(block->predecessors, entry) {902nir_block *pred = (nir_block *)entry->key;903if (pred->successors[0] && pred->successors[1]) {904all_single_successors = false;905break;906}907}908909if (all_single_successors && depth < 32) {910/* All predecessors of this block have exactly one successor and it911* is this block so they must eventually lead here without912* intersecting each other. Place the reads in the predecessors913* instead of this block.914*915* We only let this function recurse 32 times because it can recurse916* indefinitely in the presence of infinite loops. Because we're917* crawling a single-successor chain, it doesn't matter where we918* place it so it's ok to stop at an arbitrary distance.919*920* TODO: One day, we could detect back edges and avoid the recursion921* that way.922*/923set_foreach(block->predecessors, entry) {924place_phi_read(b, reg, def, (nir_block *)entry->key, depth + 1);925}926return;927}928}929930b->cursor = nir_after_block_before_jump(block);931nir_store_reg(b, reg, def, ~0);932}933934/** Lower all of the phi nodes in a block to movs to and from a register935*936* This provides a very quick-and-dirty out-of-SSA pass that you can run on a937* single block to convert all of its phis to a register and some movs.938* The code that is generated, while not optimal for actual codegen in a939* back-end, is easy to generate, correct, and will turn into the same set of940* phis after you call regs_to_ssa and do some copy propagation.941*942* The one intelligent thing this pass does is that it places the moves from943* the phi sources as high up the predecessor tree as possible instead of in944* the exact predecessor. This means that, in particular, it will crawl into945* the deepest nesting of any if-ladders. In order to ensure that doing so is946* safe, it stops as soon as one of the predecessors has multiple successors.947*/948bool949nir_lower_phis_to_regs_block(nir_block *block)950{951nir_builder b;952nir_builder_init(&b, nir_cf_node_get_function(&block->cf_node));953954bool progress = false;955nir_foreach_instr_safe(instr, block) {956if (instr->type != nir_instr_type_phi)957break;958959nir_phi_instr *phi = nir_instr_as_phi(instr);960assert(phi->dest.is_ssa);961962nir_register *reg = create_reg_for_ssa_def(&phi->dest.ssa, b.impl);963964b.cursor = nir_after_instr(&phi->instr);965nir_ssa_def *def = nir_load_reg(&b, reg);966967nir_ssa_def_rewrite_uses(&phi->dest.ssa, def);968969nir_foreach_phi_src(src, phi) {970assert(src->src.is_ssa);971place_phi_read(&b, reg, src->src.ssa, src->pred, 0);972}973974nir_instr_remove(&phi->instr);975976progress = true;977}978979return progress;980}981982struct ssa_def_to_reg_state {983nir_function_impl *impl;984bool progress;985};986987static bool988dest_replace_ssa_with_reg(nir_dest *dest, void *void_state)989{990struct ssa_def_to_reg_state *state = void_state;991992if (!dest->is_ssa)993return true;994995nir_register *reg = create_reg_for_ssa_def(&dest->ssa, state->impl);996997nir_ssa_def_rewrite_uses_src(&dest->ssa, nir_src_for_reg(reg));998999nir_instr *instr = dest->ssa.parent_instr;1000*dest = nir_dest_for_reg(reg);1001dest->reg.parent_instr = instr;1002list_addtail(&dest->reg.def_link, ®->defs);10031004state->progress = true;10051006return true;1007}10081009static bool1010ssa_def_is_local_to_block(nir_ssa_def *def, UNUSED void *state)1011{1012nir_block *block = def->parent_instr->block;1013nir_foreach_use(use_src, def) {1014if (use_src->parent_instr->block != block ||1015use_src->parent_instr->type == nir_instr_type_phi) {1016return false;1017}1018}10191020if (!list_is_empty(&def->if_uses))1021return false;10221023return true;1024}10251026/** Lower all of the SSA defs in a block to registers1027*1028* This performs the very simple operation of blindly replacing all of the SSA1029* defs in the given block with registers. If not used carefully, this may1030* result in phi nodes with register sources which is technically invalid.1031* Fortunately, the register-based into-SSA pass handles them anyway.1032*/1033bool1034nir_lower_ssa_defs_to_regs_block(nir_block *block)1035{1036nir_function_impl *impl = nir_cf_node_get_function(&block->cf_node);1037nir_shader *shader = impl->function->shader;10381039struct ssa_def_to_reg_state state = {1040.impl = impl,1041.progress = false,1042};10431044nir_foreach_instr(instr, block) {1045if (instr->type == nir_instr_type_ssa_undef) {1046/* Undefs are just a read of something never written. */1047nir_ssa_undef_instr *undef = nir_instr_as_ssa_undef(instr);1048nir_register *reg = create_reg_for_ssa_def(&undef->def, state.impl);1049nir_ssa_def_rewrite_uses_src(&undef->def, nir_src_for_reg(reg));1050} else if (instr->type == nir_instr_type_load_const) {1051/* Constant loads are SSA-only, we need to insert a move */1052nir_load_const_instr *load = nir_instr_as_load_const(instr);1053nir_register *reg = create_reg_for_ssa_def(&load->def, state.impl);1054nir_ssa_def_rewrite_uses_src(&load->def, nir_src_for_reg(reg));10551056nir_alu_instr *mov = nir_alu_instr_create(shader, nir_op_mov);1057mov->src[0].src = nir_src_for_ssa(&load->def);1058mov->dest.dest = nir_dest_for_reg(reg);1059mov->dest.write_mask = (1 << reg->num_components) - 1;1060nir_instr_insert(nir_after_instr(&load->instr), &mov->instr);1061} else if (nir_foreach_ssa_def(instr, ssa_def_is_local_to_block, NULL)) {1062/* If the SSA def produced by this instruction is only in the block1063* in which it is defined and is not used by ifs or phis, then we1064* don't have a reason to convert it to a register.1065*/1066} else {1067nir_foreach_dest(instr, dest_replace_ssa_with_reg, &state);1068}1069}10701071return state.progress;1072}107310741075