1 /*
2 * Copyright © 2021 Valve 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
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24 /**
25 * Lower constant arrays to uniform arrays.
26 *
27 * Some driver backends (such as i965 and nouveau) don't handle constant arrays
28 * gracefully, instead treating them as ordinary writable temporary arrays.
29 * Since arrays can be large, this often means spilling them to scratch memory,
30 * which usually involves a large number of instructions.
31 *
32 * This must be called prior to gl_nir_set_uniform_initializers(); we need the
33 * linker to process our new uniform's constant initializer.
34 *
35 * This should be called after optimizations, since those can result in
36 * splitting and removing arrays that are indexed by constant expressions.
37 */
38 #include "nir.h"
39 #include "nir_builder.h"
40 #include "nir_deref.h"
41
42 struct var_info {
43 nir_variable *var;
44
45 bool is_constant;
46 bool found_read;
47
48 /* Block that has all the variable stores. All the blocks with reads
49 * should be dominated by this block.
50 */
51 nir_block *block;
52 };
53
54 static void
set_const_initialiser(nir_deref_instr ** p,nir_constant * top_level_init,nir_src * const_src,unsigned writemask)55 set_const_initialiser(nir_deref_instr **p, nir_constant *top_level_init,
56 nir_src *const_src, unsigned writemask)
57 {
58 assert(*p);
59
60 nir_constant *ret = top_level_init;
61 for (; *p; p++) {
62 if ((*p)->deref_type == nir_deref_type_array) {
63 assert(nir_src_is_const((*p)->arr.index));
64
65 uint64_t idx = nir_src_as_uint((*p)->arr.index);
66
67 /* Just return if this is an out of bounds write */
68 if (idx >= ret->num_elements)
69 return;
70
71 ret = ret->elements[idx];
72 } else if ((*p)->deref_type == nir_deref_type_struct) {
73 ret = ret->elements[(*p)->strct.index];
74 } else {
75 unreachable("Unsupported deref type");
76 }
77 }
78
79 /* Now that we have selected the corrent nir_constant we copy the constant
80 * values to it.
81 */
82 nir_instr *src_instr = const_src->ssa->parent_instr;
83 assert(src_instr->type == nir_instr_type_load_const);
84 nir_load_const_instr *load = nir_instr_as_load_const(src_instr);
85
86 for (unsigned i = 0; i < load->def.num_components; i++) {
87 if (!(writemask & (1 << i)))
88 continue;
89
90 memcpy(ret->values + i, load->value + i, sizeof(*load->value));
91 }
92
93 return;
94 }
95
96 static nir_constant *
rebuild_const_array_initialiser(const struct glsl_type * type,void * mem_ctx)97 rebuild_const_array_initialiser(const struct glsl_type *type, void *mem_ctx)
98 {
99 nir_constant *ret = rzalloc(mem_ctx, nir_constant);
100
101 if (glsl_type_is_matrix(type) && glsl_get_matrix_columns(type) > 1) {
102 ret->num_elements = glsl_get_matrix_columns(type);
103 ret->elements = ralloc_array(mem_ctx, nir_constant *, ret->num_elements);
104
105 for (unsigned i = 0; i < ret->num_elements; i++) {
106 ret->elements[i] = rzalloc(mem_ctx, nir_constant);
107 }
108
109 return ret;
110 }
111
112 if (glsl_type_is_array(type) || glsl_type_is_struct(type)) {
113 ret->num_elements = glsl_get_length(type);
114 ret->elements = ralloc_array(mem_ctx, nir_constant *, ret->num_elements);
115
116 for (unsigned i = 0; i < ret->num_elements; i++) {
117 if (glsl_type_is_array(type)) {
118 ret->elements[i] =
119 rebuild_const_array_initialiser(glsl_get_array_element(type), mem_ctx);
120 } else {
121 ret->elements[i] =
122 rebuild_const_array_initialiser(glsl_get_struct_field(type, i), mem_ctx);
123 }
124 }
125 }
126
127 return ret;
128 }
129
130 static bool
lower_const_array_to_uniform(nir_shader * shader,struct var_info * info,struct hash_table * const_array_vars,unsigned * free_uni_components,unsigned * const_count,bool * progress)131 lower_const_array_to_uniform(nir_shader *shader, struct var_info *info,
132 struct hash_table *const_array_vars,
133 unsigned *free_uni_components,
134 unsigned *const_count, bool *progress)
135 {
136 nir_variable *var = info->var;
137
138 if (!info->is_constant)
139 return true;
140
141 if (!glsl_type_is_array(var->type))
142 return true;
143
144 /* TODO: Add support for 8bit and 16bit types */
145 if (!glsl_type_is_32bit(glsl_without_array(var->type)) &&
146 !glsl_type_is_64bit(glsl_without_array(var->type)))
147 return true;
148
149 /* How many uniform component slots are required? */
150 unsigned component_slots = glsl_get_component_slots(var->type);
151
152 /* We would utilize more than is available, bail out. */
153 if (component_slots > *free_uni_components)
154 return false;
155
156 *free_uni_components -= component_slots;
157
158 /* In the very unlikely event of 4294967295 constant arrays in a single
159 * shader, don't promote this to a uniform.
160 */
161 unsigned limit = ~0;
162 if (*const_count == limit)
163 return false;
164
165 nir_variable *uni = rzalloc(shader, nir_variable);
166
167 /* Rebuild constant initialiser */
168 nir_constant *const_init = rebuild_const_array_initialiser(var->type, uni);
169
170 /* Set constant initialiser */
171 nir_function_impl *impl = nir_shader_get_entrypoint(shader);
172 nir_foreach_block(block, impl) {
173 nir_foreach_instr(instr, block) {
174 if (instr->type != nir_instr_type_intrinsic)
175 continue;
176
177 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
178 assert(intrin->intrinsic != nir_intrinsic_copy_deref);
179 if (intrin->intrinsic != nir_intrinsic_store_deref)
180 continue;
181
182 nir_deref_instr *deref = nir_src_as_deref(intrin->src[0]);
183 nir_variable *deref_var = nir_deref_instr_get_variable(deref);
184 if (var != deref_var)
185 continue;
186
187 nir_deref_path path;
188 nir_deref_path_init(&path, deref, NULL);
189 assert(path.path[0]->deref_type == nir_deref_type_var);
190
191 nir_deref_instr **p = &path.path[1];
192 set_const_initialiser(p, const_init, &intrin->src[1],
193 nir_intrinsic_write_mask(intrin));
194
195 nir_deref_path_finish(&path);
196 }
197 }
198
199 uni->constant_initializer = const_init;
200 uni->data.how_declared = nir_var_hidden;
201 uni->data.read_only = true;
202 uni->data.mode = nir_var_uniform;
203 uni->type = info->var->type;
204 uni->name = ralloc_asprintf(uni, "constarray_%x_%u",
205 *const_count, shader->info.stage);
206
207 nir_shader_add_variable(shader, uni);
208
209 *const_count = *const_count + 1;
210
211 _mesa_hash_table_insert(const_array_vars, info->var, uni);
212
213 *progress = true;
214
215 return true;
216 }
217
218 static unsigned
count_uniforms(nir_shader * shader)219 count_uniforms(nir_shader *shader)
220 {
221 unsigned total = 0;
222
223 nir_foreach_variable_with_modes(var, shader, nir_var_uniform) {
224 total += glsl_get_component_slots(var->type);
225 }
226
227 return total;
228 }
229
230 bool
nir_lower_const_arrays_to_uniforms(nir_shader * shader,unsigned max_uniform_components)231 nir_lower_const_arrays_to_uniforms(nir_shader *shader,
232 unsigned max_uniform_components)
233 {
234 /* This only works with a single entrypoint */
235 nir_function_impl *impl = nir_shader_get_entrypoint(shader);
236
237 unsigned num_locals = nir_function_impl_index_vars(impl);
238 if (num_locals == 0) {
239 nir_shader_preserve_all_metadata(shader);
240 return false;
241 }
242
243 bool progress = false;
244 unsigned uniform_components = count_uniforms(shader);
245 unsigned free_uni_components = max_uniform_components - uniform_components;
246 unsigned const_count = 0;
247
248 struct var_info *var_infos = ralloc_array(NULL, struct var_info, num_locals);
249 nir_foreach_function_temp_variable(var, impl) {
250 var_infos[var->index] = (struct var_info){
251 .var = var,
252 .is_constant = true,
253 .found_read = false,
254 };
255 }
256
257 nir_metadata_require(impl, nir_metadata_dominance);
258
259 struct hash_table *const_array_vars =
260 _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal);
261
262 /* First, walk through the shader and figure out what variables we can
263 * lower to a uniform.
264 */
265 nir_foreach_block(block, impl) {
266 nir_foreach_instr(instr, block) {
267 if (instr->type == nir_instr_type_deref) {
268 /* If we ever see a complex use of a deref_var, we have to assume
269 * that variable is non-constant because we can't guarantee we
270 * will find all of the writers of that variable.
271 */
272 nir_deref_instr *deref = nir_instr_as_deref(instr);
273 if (deref->deref_type == nir_deref_type_var &&
274 deref->var->data.mode == nir_var_function_temp &&
275 nir_deref_instr_has_complex_use(deref, 0))
276 var_infos[deref->var->index].is_constant = false;
277 continue;
278 }
279
280 if (instr->type != nir_instr_type_intrinsic)
281 continue;
282
283 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
284
285 bool src_is_const = false;
286 nir_deref_instr *src_deref = NULL, *dst_deref = NULL;
287 switch (intrin->intrinsic) {
288 case nir_intrinsic_store_deref:
289 dst_deref = nir_src_as_deref(intrin->src[0]);
290 src_is_const = nir_src_is_const(intrin->src[1]);
291 break;
292
293 case nir_intrinsic_load_deref:
294 src_deref = nir_src_as_deref(intrin->src[0]);
295 break;
296
297 case nir_intrinsic_copy_deref:
298 assert(!"Lowering of copy_deref with const arrays to uniform is prohibited");
299 break;
300
301 default:
302 continue;
303 }
304
305 if (dst_deref && nir_deref_mode_must_be(dst_deref, nir_var_function_temp)) {
306 nir_variable *var = nir_deref_instr_get_variable(dst_deref);
307 if (var == NULL)
308 continue;
309
310 assert(var->data.mode == nir_var_function_temp);
311
312 struct var_info *info = &var_infos[var->index];
313 if (!info->is_constant)
314 continue;
315
316 if (!info->block)
317 info->block = block;
318
319 /* We only consider variables constant if they only have constant
320 * stores, all the stores come before any reads, and all stores
321 * come from the same block. We also can't handle indirect stores.
322 */
323 if (!src_is_const || info->found_read || block != info->block ||
324 nir_deref_instr_has_indirect(dst_deref)) {
325 info->is_constant = false;
326 }
327 }
328
329 if (src_deref && nir_deref_mode_must_be(src_deref, nir_var_function_temp)) {
330 nir_variable *var = nir_deref_instr_get_variable(src_deref);
331 if (var == NULL)
332 continue;
333
334 assert(var->data.mode == nir_var_function_temp);
335
336 /* We only consider variables constant if all the reads are
337 * dominated by the block that writes to it.
338 */
339 struct var_info *info = &var_infos[var->index];
340 if (!info->is_constant)
341 continue;
342
343 if (!info->block || !nir_block_dominates(info->block, block))
344 info->is_constant = false;
345
346 info->found_read = true;
347 }
348 }
349 }
350
351 /* Now lower the constants to uniforms */
352 for (int i = 0; i < num_locals; i++) {
353 struct var_info *info = &var_infos[i];
354 if (!lower_const_array_to_uniform(shader, info, const_array_vars,
355 &free_uni_components, &const_count,
356 &progress))
357 break;
358 }
359
360 /* Finally rewrite its uses */
361 nir_builder b = nir_builder_create(impl);
362 nir_foreach_block(block, impl) {
363 nir_foreach_instr_safe(instr, block) {
364
365 if (instr->type != nir_instr_type_intrinsic)
366 continue;
367
368 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
369 if (intrin->intrinsic != nir_intrinsic_load_deref)
370 continue;
371
372 nir_deref_instr *deref = nir_src_as_deref(intrin->src[0]);
373 nir_variable *var = nir_deref_instr_get_variable(deref);
374
375 struct hash_entry *entry =
376 _mesa_hash_table_search(const_array_vars, var);
377 if (!entry)
378 continue;
379
380 b.cursor = nir_before_instr(instr);
381
382 nir_variable *uni = (nir_variable *)entry->data;
383 nir_deref_instr *new_deref_instr = nir_build_deref_var(&b, uni);
384
385 nir_deref_path path;
386 nir_deref_path_init(&path, deref, NULL);
387 assert(path.path[0]->deref_type == nir_deref_type_var);
388
389 nir_deref_instr **p = &path.path[1];
390 for (; *p; p++) {
391 if ((*p)->deref_type == nir_deref_type_array) {
392 new_deref_instr = nir_build_deref_array(&b, new_deref_instr,
393 (*p)->arr.index.ssa);
394 } else if ((*p)->deref_type == nir_deref_type_struct) {
395 new_deref_instr = nir_build_deref_struct(&b, new_deref_instr,
396 (*p)->strct.index);
397 } else {
398 unreachable("Unsupported deref type");
399 }
400 }
401 nir_deref_path_finish(&path);
402
403 nir_def *new_def = nir_load_deref(&b, new_deref_instr);
404
405 nir_def_replace(&intrin->def, new_def);
406 }
407 }
408
409 nir_metadata_preserve(impl, nir_metadata_control_flow);
410
411 ralloc_free(var_infos);
412 _mesa_hash_table_destroy(const_array_vars, NULL);
413
414 return progress;
415 }
416