1 /*
2  * Copyright © 2016 Red Hat
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 FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 
24 /* Lowering pass that lowers accesses to built-in uniform variables.
25  * Built-in uniforms are not necessarily packed the same way that
26  * normal uniform structs are, for example:
27  *
28  *    struct gl_FogParameters {
29  *       vec4 color;
30  *       float density;
31  *       float start;
32  *       float end;
33  *       float scale;
34  *    };
35  *
36  * is packed into vec4[2], whereas the same struct would be packed
37  * (by gallium), as vec4[5] if it where not built-in.  Because of
38  * this, we need to replace (for example) access like:
39  *
40  *    vec1 ssa_1 = intrinsic load_var () (gl_Fog.start) ()
41  *
42  * with:
43  *
44  *    vec4 ssa_2 = intrinsic load_var () (fog.params) ()
45  *    vec1 ssa_1 = ssa_2.y
46  *
47  * with appropriate substitutions in the uniform variables list:
48  *
49  *    decl_var uniform INTERP_MODE_NONE gl_FogParameters gl_Fog (0, 0)
50  *
51  * would become:
52  *
53  *    decl_var uniform INTERP_MODE_NONE vec4 state.fog.color (0, 0)
54  *    decl_var uniform INTERP_MODE_NONE vec4 state.fog.params (0, 1)
55  *
56  * See in particular 'struct gl_builtin_uniform_element'.
57  */
58 
59 #include "compiler/nir/nir.h"
60 #include "compiler/nir/nir_builder.h"
61 #include "compiler/nir/nir_deref.h"
62 #include "st_nir.h"
63 #include "compiler/glsl/ir.h"
64 #include "uniforms.h"
65 #include "program/prog_instruction.h"
66 
67 typedef struct {
68    nir_shader *shader;
69    nir_builder builder;
70    void *mem_ctx;
71 } lower_builtin_state;
72 
73 static const struct gl_builtin_uniform_element *
get_element(const struct gl_builtin_uniform_desc * desc,nir_deref_path * path)74 get_element(const struct gl_builtin_uniform_desc *desc, nir_deref_path *path)
75 {
76    int idx = 1;
77 
78    assert(path->path[0]->deref_type == nir_deref_type_var);
79 
80    if ((desc->num_elements == 1) && (desc->elements[0].field == NULL))
81       return NULL;
82 
83    /* we handle arrays in get_variable(): */
84    if (path->path[idx]->deref_type == nir_deref_type_array)
85       idx++;
86 
87    /* don't need to deal w/ non-struct or array of non-struct: */
88    if (!path->path[idx])
89       return NULL;
90 
91    if (path->path[idx]->deref_type != nir_deref_type_struct)
92       return NULL;
93 
94    assert(path->path[idx]->strct.index < desc->num_elements);
95 
96    return &desc->elements[path->path[idx]->strct.index ];
97 }
98 
99 static nir_variable *
get_variable(lower_builtin_state * state,nir_deref_path * path,const struct gl_builtin_uniform_element * element)100 get_variable(lower_builtin_state *state, nir_deref_path *path,
101              const struct gl_builtin_uniform_element *element)
102 {
103    nir_shader *shader = state->shader;
104    gl_state_index16 tokens[STATE_LENGTH];
105    int idx = 1;
106 
107    memcpy(tokens, element->tokens, sizeof(tokens));
108 
109    if (path->path[idx]->deref_type == nir_deref_type_array) {
110       /* we need to fixup the array index slot: */
111       switch (tokens[0]) {
112       case STATE_MODELVIEW_MATRIX:
113       case STATE_MODELVIEW_MATRIX_INVERSE:
114       case STATE_MODELVIEW_MATRIX_TRANSPOSE:
115       case STATE_MODELVIEW_MATRIX_INVTRANS:
116       case STATE_PROJECTION_MATRIX:
117       case STATE_PROJECTION_MATRIX_INVERSE:
118       case STATE_PROJECTION_MATRIX_TRANSPOSE:
119       case STATE_PROJECTION_MATRIX_INVTRANS:
120       case STATE_MVP_MATRIX:
121       case STATE_MVP_MATRIX_INVERSE:
122       case STATE_MVP_MATRIX_TRANSPOSE:
123       case STATE_MVP_MATRIX_INVTRANS:
124       case STATE_TEXTURE_MATRIX:
125       case STATE_TEXTURE_MATRIX_INVERSE:
126       case STATE_TEXTURE_MATRIX_TRANSPOSE:
127       case STATE_TEXTURE_MATRIX_INVTRANS:
128       case STATE_PROGRAM_MATRIX:
129       case STATE_PROGRAM_MATRIX_INVERSE:
130       case STATE_PROGRAM_MATRIX_TRANSPOSE:
131       case STATE_PROGRAM_MATRIX_INVTRANS:
132       case STATE_LIGHT:
133       case STATE_LIGHTPROD:
134       case STATE_TEXGEN:
135       case STATE_TEXENV_COLOR:
136       case STATE_CLIPPLANE:
137          tokens[1] = nir_src_as_uint(path->path[idx]->arr.index);
138          break;
139       }
140    }
141 
142    char *name = _mesa_program_state_string(tokens);
143 
144    nir_foreach_uniform_variable(var, shader) {
145       if (strcmp(var->name, name) == 0) {
146          free(name);
147          return var;
148       }
149    }
150 
151    /* variable doesn't exist yet, so create it: */
152    nir_variable *var =
153       nir_variable_create(shader, nir_var_uniform, glsl_vec4_type(), name);
154 
155    var->num_state_slots = 1;
156    var->state_slots = rzalloc_array(var, nir_state_slot, 1);
157    memcpy(var->state_slots[0].tokens, tokens,
158           sizeof(var->state_slots[0].tokens));
159 
160    free(name);
161 
162    return var;
163 }
164 
165 static bool
lower_builtin_block(lower_builtin_state * state,nir_block * block)166 lower_builtin_block(lower_builtin_state *state, nir_block *block)
167 {
168    nir_builder *b = &state->builder;
169    bool progress = false;
170 
171    nir_foreach_instr_safe(instr, block) {
172       if (instr->type != nir_instr_type_intrinsic)
173          continue;
174 
175       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
176 
177       if (intrin->intrinsic != nir_intrinsic_load_deref)
178          continue;
179 
180       nir_variable *var =
181          nir_deref_instr_get_variable(nir_src_as_deref(intrin->src[0]));
182       if (var->data.mode != nir_var_uniform)
183          continue;
184 
185       /* built-in's will always start with "gl_" */
186       if (strncmp(var->name, "gl_", 3) != 0)
187          continue;
188 
189       const struct gl_builtin_uniform_desc *desc =
190          _mesa_glsl_get_builtin_uniform_desc(var->name);
191 
192       /* if no descriptor, it isn't something we need to handle specially: */
193       if (!desc)
194          continue;
195 
196       nir_deref_path path;
197       nir_deref_path_init(&path, nir_src_as_deref(intrin->src[0]), NULL);
198 
199       const struct gl_builtin_uniform_element *element = get_element(desc, &path);
200 
201       /* matrix elements (array_deref) do not need special handling: */
202       if (!element) {
203          nir_deref_path_finish(&path);
204          continue;
205       }
206 
207       /* remove existing var from uniform list: */
208       exec_node_remove(&var->node);
209       /* the _self_link() ensures we can remove multiple times, rather than
210        * trying to keep track of what we have already removed:
211        */
212       exec_node_self_link(&var->node);
213 
214       nir_variable *new_var = get_variable(state, &path, element);
215       nir_deref_path_finish(&path);
216 
217       b->cursor = nir_before_instr(instr);
218 
219       nir_ssa_def *def = nir_load_var(b, new_var);
220 
221       /* swizzle the result: */
222       unsigned swiz[NIR_MAX_VEC_COMPONENTS] = {0};
223       for (unsigned i = 0; i < 4; i++) {
224          swiz[i] = GET_SWZ(element->swizzle, i);
225          assert(swiz[i] <= SWIZZLE_W);
226       }
227       def = nir_swizzle(b, def, swiz, intrin->num_components);
228 
229       /* and rewrite uses of original instruction: */
230       assert(intrin->dest.is_ssa);
231       nir_ssa_def_rewrite_uses(&intrin->dest.ssa, def);
232 
233       /* at this point intrin should be unused.  We need to remove it
234        * (rather than waiting for DCE pass) to avoid dangling reference
235        * to remove'd var.  And we have to remove the original uniform
236        * var since we don't want it to get uniform space allocated.
237        */
238       nir_instr_remove(&intrin->instr);
239 
240       progress = true;
241    }
242 
243    return progress;
244 }
245 
246 static void
lower_builtin_impl(lower_builtin_state * state,nir_function_impl * impl)247 lower_builtin_impl(lower_builtin_state *state, nir_function_impl *impl)
248 {
249    nir_builder_init(&state->builder, impl);
250    state->mem_ctx = ralloc_parent(impl);
251 
252    bool progress = false;
253    nir_foreach_block(block, impl) {
254       progress |= lower_builtin_block(state, block);
255    }
256 
257    if (progress)
258       nir_remove_dead_derefs_impl(impl);
259 
260    nir_metadata_preserve(impl, nir_metadata_block_index |
261                                nir_metadata_dominance);
262 }
263 
264 void
st_nir_lower_builtin(nir_shader * shader)265 st_nir_lower_builtin(nir_shader *shader)
266 {
267    lower_builtin_state state;
268    state.shader = shader;
269    nir_foreach_function(function, shader) {
270       if (function->impl)
271          lower_builtin_impl(&state, function->impl);
272    }
273 }
274