• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005-2007  Brian Paul   All Rights Reserved.
3  * Copyright (C) 2008  VMware, Inc.   All Rights Reserved.
4  * Copyright © 2014 Intel Corporation
5  * Copyright © 2017 Advanced Micro Devices, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the next
15  * paragraph) shall be included in all copies or substantial portions of the
16  * Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24  * DEALINGS IN THE SOFTWARE.
25  */
26 
27 /**
28  * \file
29  *
30  * Lower sampler and image references of (non-bindless) uniforms by removing
31  * struct dereferences, and synthesizing new uniform variables without structs
32  * if required.
33  *
34  * This will allow backends to have a simple, uniform treatment of bindless and
35  * non-bindless samplers and images.
36  *
37  * Example:
38  *
39  *   struct S {
40  *      sampler2D tex[2];
41  *      sampler2D other;
42  *   };
43  *   uniform S s[2];
44  *
45  *   tmp = texture(s[n].tex[m], coord);
46  *
47  * Becomes:
48  *
49  *   decl_var uniform INTERP_MODE_NONE sampler2D[2][2] lower@s.tex (...)
50  *
51  *   vec1 32 ssa_idx = $(2 * n + m)
52  *   vec4 32 ssa_out = tex ssa_coord (coord), lower@s.tex[n][m] (texture), lower@s.tex[n][m] (sampler)
53  *
54  * and lower@s.tex has var->data.binding set to the base index as defined by
55  * the opaque uniform mapping.
56  */
57 
58 #include "compiler/nir/nir.h"
59 #include "compiler/nir/nir_builder.h"
60 #include "compiler/nir/nir_deref.h"
61 #include "gl_nir.h"
62 
63 #include "util/compiler.h"
64 #include "main/shader_types.h"
65 
66 struct lower_samplers_as_deref_state {
67    nir_shader *shader;
68    const struct gl_shader_program *shader_program;
69    struct hash_table *remap_table;
70 };
71 
72 /* Prepare for removing struct derefs.  This pre-pass generates the name
73  * of the lowered deref, and calculates the lowered type and location.
74  * After that, once looking up (or creating if needed) the lowered var,
75  * constructing the new chain of deref instructions is a simple loop
76  * that skips the struct deref's
77  *
78  * path:     appended to as we descend down the chain of deref instrs
79  *           and remove struct derefs
80  * location: increased as we descend down and remove struct derefs
81  * type:     updated as we recurse back up the chain of deref instrs
82  *           with the resulting type after removing struct derefs
83  */
84 static void
remove_struct_derefs_prep(nir_deref_instr ** p,char ** name,unsigned * location,const struct glsl_type ** type)85 remove_struct_derefs_prep(nir_deref_instr **p, char **name,
86                           unsigned *location, const struct glsl_type **type)
87 {
88    nir_deref_instr *cur = p[0], *next = p[1];
89 
90    if (!next) {
91       *type = cur->type;
92       return;
93    }
94 
95    switch (next->deref_type) {
96    case nir_deref_type_array: {
97       unsigned length = glsl_get_length(cur->type);
98 
99       remove_struct_derefs_prep(&p[1], name, location, type);
100 
101       *type = glsl_array_type(*type, length, glsl_get_explicit_stride(cur->type));
102       break;
103    }
104 
105    case nir_deref_type_struct: {
106       *location += glsl_get_struct_location_offset(cur->type, next->strct.index);
107       ralloc_asprintf_append(name, ".%s",
108                              glsl_get_struct_elem_name(cur->type, next->strct.index));
109 
110       remove_struct_derefs_prep(&p[1], name, location, type);
111       break;
112    }
113 
114    default:
115       unreachable("Invalid deref type");
116       break;
117    }
118 }
119 
120 static void
record_images_used(struct shader_info * info,nir_intrinsic_instr * instr)121 record_images_used(struct shader_info *info,
122                    nir_intrinsic_instr *instr)
123 {
124    nir_variable *var = nir_intrinsic_get_var(instr, 0);
125 
126    /* Structs have been lowered already, so get_aoa_size is sufficient. */
127    const unsigned size =
128       glsl_type_is_array(var->type) ? glsl_get_aoa_size(var->type) : 1;
129 
130    BITSET_SET_RANGE(info->images_used, var->data.binding,
131                     var->data.binding + (MAX2(size, 1) - 1));
132 
133    enum glsl_sampler_dim sampler_dim =
134       glsl_get_sampler_dim(glsl_without_array(var->type));
135    if (sampler_dim == GLSL_SAMPLER_DIM_BUF) {
136       BITSET_SET_RANGE(info->image_buffers, var->data.binding,
137                        var->data.binding + (MAX2(size, 1) - 1));
138    }
139    if (sampler_dim == GLSL_SAMPLER_DIM_MS) {
140       BITSET_SET_RANGE(info->msaa_images, var->data.binding,
141                        var->data.binding + (MAX2(size, 1) - 1));
142    }
143 }
144 
145 
146 static nir_deref_instr *
lower_deref(nir_builder * b,struct lower_samplers_as_deref_state * state,nir_deref_instr * deref)147 lower_deref(nir_builder *b, struct lower_samplers_as_deref_state *state,
148             nir_deref_instr *deref)
149 {
150    nir_variable *var = nir_deref_instr_get_variable(deref);
151    gl_shader_stage stage = state->shader->info.stage;
152 
153    if (!(var->data.mode & (nir_var_uniform | nir_var_image)) ||
154        var->data.bindless)
155       return NULL;
156 
157    nir_deref_path path;
158    nir_deref_path_init(&path, deref, state->remap_table);
159    assert(path.path[0]->deref_type == nir_deref_type_var);
160 
161    char *name = ralloc_asprintf(state->remap_table, "lower@%s", var->name);
162    unsigned location = var->data.location;
163    const struct glsl_type *type = NULL;
164    unsigned binding;
165 
166    /*
167     * We end up needing to do this in two passes, in order to generate
168     * the name of the lowered var (and detecting whether there even are
169     * any struct deref's), and then the second pass to construct the
170     * actual deref instructions after looking up / generating a new
171     * nir_variable (since we need to construct the deref_var first)
172     */
173 
174    remove_struct_derefs_prep(path.path, &name, &location, &type);
175 
176    if (state->shader_program && var->data.how_declared != nir_var_hidden) {
177       /* For GLSL programs, look up the bindings in the uniform storage. */
178       assert(location < state->shader_program->data->NumUniformStorage &&
179              state->shader_program->data->UniformStorage[location].opaque[stage].active);
180 
181       binding = state->shader_program->data->UniformStorage[location].opaque[stage].index;
182    } else {
183       /* For ARB programs, built-in shaders, or internally generated sampler
184        * variables in GLSL programs, assume that whoever created the shader
185        * set the bindings correctly already.
186        */
187       assert(var->data.explicit_binding);
188       binding = var->data.binding;
189    }
190 
191    if (var->type == type) {
192       /* Fast path: We did not encounter any struct derefs. */
193       var->data.binding = binding;
194       return deref;
195    }
196 
197    uint32_t hash = _mesa_hash_string(name);
198    struct hash_entry *h =
199       _mesa_hash_table_search_pre_hashed(state->remap_table, hash, name);
200 
201    if (h) {
202       var = (nir_variable *)h->data;
203    } else {
204       var = nir_variable_create(state->shader, var->data.mode, type, name);
205       var->data.binding = binding;
206 
207       /* Don't set var->data.location.  The old structure location could be
208        * used to index into gl_uniform_storage, assuming the full structure
209        * was walked in order.  With the new split variables, this invariant
210        * no longer holds and there's no meaningful way to start from a base
211        * location and access a particular array element.  Just leave it 0.
212        */
213 
214       _mesa_hash_table_insert_pre_hashed(state->remap_table, hash, name, var);
215    }
216 
217    /* construct a new deref based on lowered var (skipping the struct deref's
218     * from the original deref:
219     */
220    nir_deref_instr *new_deref = nir_build_deref_var(b, var);
221    for (nir_deref_instr **p = &path.path[1]; *p; p++) {
222       if ((*p)->deref_type == nir_deref_type_struct)
223          continue;
224 
225       assert((*p)->deref_type == nir_deref_type_array);
226 
227       new_deref = nir_build_deref_array(b, new_deref,
228                                         (*p)->arr.index.ssa);
229    }
230 
231    return new_deref;
232 }
233 
234 static void
record_textures_used(struct shader_info * info,nir_deref_instr * deref,nir_texop op)235 record_textures_used(struct shader_info *info,
236                      nir_deref_instr *deref,
237                      nir_texop op)
238 {
239    nir_variable *var = nir_deref_instr_get_variable(deref);
240 
241    /* Structs have been lowered already, so get_aoa_size is sufficient. */
242    const unsigned size =
243       glsl_type_is_array(var->type) ? glsl_get_aoa_size(var->type) : 1;
244 
245    BITSET_SET_RANGE(info->textures_used, var->data.binding,
246                     var->data.binding + (MAX2(size, 1) - 1));
247 
248    if (op == nir_texop_txf ||
249        op == nir_texop_txf_ms ||
250        op == nir_texop_txf_ms_mcs_intel) {
251       BITSET_SET_RANGE(info->textures_used_by_txf, var->data.binding,
252                        var->data.binding + (MAX2(size, 1) - 1));
253    }
254 }
255 
256 static void
record_samplers_used(struct shader_info * info,nir_deref_instr * deref,nir_texop op)257 record_samplers_used(struct shader_info *info,
258                      nir_deref_instr *deref,
259                      nir_texop op)
260 {
261    nir_variable *var = nir_deref_instr_get_variable(deref);
262 
263    /* Structs have been lowered already, so get_aoa_size is sufficient. */
264    const unsigned size =
265       glsl_type_is_array(var->type) ? glsl_get_aoa_size(var->type) : 1;
266 
267    BITSET_SET_RANGE(info->samplers_used, var->data.binding,
268                     var->data.binding + (MAX2(size, 1) - 1));
269 }
270 
271 static bool
lower_sampler(nir_tex_instr * instr,struct lower_samplers_as_deref_state * state,nir_builder * b)272 lower_sampler(nir_tex_instr *instr, struct lower_samplers_as_deref_state *state,
273               nir_builder *b)
274 {
275    int texture_idx =
276       nir_tex_instr_src_index(instr, nir_tex_src_texture_deref);
277    int sampler_idx =
278       nir_tex_instr_src_index(instr, nir_tex_src_sampler_deref);
279 
280    b->cursor = nir_before_instr(&instr->instr);
281 
282    if (texture_idx >= 0) {
283       nir_deref_instr *texture_deref =
284          lower_deref(b, state, nir_src_as_deref(instr->src[texture_idx].src));
285       /* only lower non-bindless: */
286       if (texture_deref) {
287          nir_src_rewrite(&instr->src[texture_idx].src, &texture_deref->def);
288          record_textures_used(&b->shader->info, texture_deref, instr->op);
289       }
290    }
291 
292    if (sampler_idx >= 0) {
293       nir_deref_instr *sampler_deref =
294          lower_deref(b, state, nir_src_as_deref(instr->src[sampler_idx].src));
295       /* only lower non-bindless: */
296       if (sampler_deref) {
297          nir_src_rewrite(&instr->src[sampler_idx].src, &sampler_deref->def);
298          record_samplers_used(&b->shader->info, sampler_deref, instr->op);
299       }
300    }
301 
302    return true;
303 }
304 
305 static bool
lower_intrinsic(nir_intrinsic_instr * instr,struct lower_samplers_as_deref_state * state,nir_builder * b)306 lower_intrinsic(nir_intrinsic_instr *instr,
307                 struct lower_samplers_as_deref_state *state,
308                 nir_builder *b)
309 {
310    if (instr->intrinsic == nir_intrinsic_image_deref_load ||
311        instr->intrinsic == nir_intrinsic_image_deref_store ||
312        instr->intrinsic == nir_intrinsic_image_deref_atomic ||
313        instr->intrinsic == nir_intrinsic_image_deref_atomic_swap ||
314        instr->intrinsic == nir_intrinsic_image_deref_size ||
315        instr->intrinsic == nir_intrinsic_image_deref_samples_identical ||
316        instr->intrinsic == nir_intrinsic_image_deref_descriptor_amd ||
317        instr->intrinsic == nir_intrinsic_image_deref_samples) {
318 
319       b->cursor = nir_before_instr(&instr->instr);
320       nir_deref_instr *deref =
321          lower_deref(b, state, nir_src_as_deref(instr->src[0]));
322 
323       record_images_used(&state->shader->info, instr);
324 
325       /* don't lower bindless: */
326       if (!deref)
327          return false;
328       nir_src_rewrite(&instr->src[0], &deref->def);
329       return true;
330    }
331    if (instr->intrinsic == nir_intrinsic_image_deref_order ||
332        instr->intrinsic == nir_intrinsic_image_deref_format)
333       unreachable("how did you even manage this?");
334 
335    return false;
336 }
337 
338 static bool
lower_instr(nir_builder * b,nir_instr * instr,void * cb_data)339 lower_instr(nir_builder *b, nir_instr *instr, void *cb_data)
340 {
341    struct lower_samplers_as_deref_state *state = cb_data;
342 
343    if (instr->type == nir_instr_type_tex)
344       return lower_sampler(nir_instr_as_tex(instr), state, b);
345 
346    if (instr->type == nir_instr_type_intrinsic)
347       return lower_intrinsic(nir_instr_as_intrinsic(instr), state, b);
348 
349    return false;
350 }
351 
352 bool
gl_nir_lower_samplers_as_deref(nir_shader * shader,const struct gl_shader_program * shader_program)353 gl_nir_lower_samplers_as_deref(nir_shader *shader,
354                                const struct gl_shader_program *shader_program)
355 {
356    struct lower_samplers_as_deref_state state;
357 
358    state.shader = shader;
359    state.shader_program = shader_program;
360    state.remap_table = _mesa_hash_table_create(NULL, _mesa_hash_string,
361                                                _mesa_key_string_equal);
362 
363    bool progress = nir_shader_instructions_pass(shader, lower_instr,
364                                                 nir_metadata_control_flow,
365                                                 &state);
366 
367    if (progress) {
368       nir_remove_dead_derefs(shader);
369       if (!shader->info.internal && shader_program) {
370          /* try to apply bindings for unused samplers to avoid index zero clobbering in backends */
371          nir_foreach_uniform_variable(var, shader) {
372             /* ignore hidden variables */
373             if (!glsl_type_is_sampler(glsl_without_array(var->type)) ||
374                 var->data.how_declared == nir_var_hidden)
375                continue;
376             bool found = false;
377             hash_table_foreach(state.remap_table, entry) {
378                if (var == entry->data) {
379                   found = true;
380                   break;
381                }
382             }
383             if (!found) {
384                /* same as lower_deref() */
385                var->data.binding = shader_program->data->UniformStorage[var->data.location].opaque[shader->info.stage].index;
386             }
387          }
388       }
389    }
390 
391    /* keys are freed automatically by ralloc */
392    _mesa_hash_table_destroy(state.remap_table, NULL);
393 
394    return progress;
395 }
396