• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2018 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 
24 #include "nir.h"
25 #include "nir_builder.h"
26 #include "nir_deref.h"
27 #include "util/hash_table.h"
28 
29 static bool
is_trivial_deref_cast(nir_deref_instr * cast)30 is_trivial_deref_cast(nir_deref_instr *cast)
31 {
32    nir_deref_instr *parent = nir_src_as_deref(cast->parent);
33    if (!parent)
34       return false;
35 
36    return cast->modes == parent->modes &&
37           cast->type == parent->type &&
38           cast->dest.ssa.num_components == parent->dest.ssa.num_components &&
39           cast->dest.ssa.bit_size == parent->dest.ssa.bit_size;
40 }
41 
42 void
nir_deref_path_init(nir_deref_path * path,nir_deref_instr * deref,void * mem_ctx)43 nir_deref_path_init(nir_deref_path *path,
44                     nir_deref_instr *deref, void *mem_ctx)
45 {
46    assert(deref != NULL);
47 
48    /* The length of the short path is at most ARRAY_SIZE - 1 because we need
49     * room for the NULL terminator.
50     */
51    static const int max_short_path_len = ARRAY_SIZE(path->_short_path) - 1;
52 
53    int count = 0;
54 
55    nir_deref_instr **tail = &path->_short_path[max_short_path_len];
56    nir_deref_instr **head = tail;
57 
58    *tail = NULL;
59    for (nir_deref_instr *d = deref; d; d = nir_deref_instr_parent(d)) {
60       if (d->deref_type == nir_deref_type_cast && is_trivial_deref_cast(d))
61          continue;
62       count++;
63       if (count <= max_short_path_len)
64          *(--head) = d;
65    }
66 
67    if (count <= max_short_path_len) {
68       /* If we're under max_short_path_len, just use the short path. */
69       path->path = head;
70       goto done;
71    }
72 
73 #ifndef NDEBUG
74    /* Just in case someone uses short_path by accident */
75    for (unsigned i = 0; i < ARRAY_SIZE(path->_short_path); i++)
76       path->_short_path[i] = (void *)(uintptr_t)0xdeadbeef;
77 #endif
78 
79    path->path = ralloc_array(mem_ctx, nir_deref_instr *, count + 1);
80    head = tail = path->path + count;
81    *tail = NULL;
82    for (nir_deref_instr *d = deref; d; d = nir_deref_instr_parent(d)) {
83       if (d->deref_type == nir_deref_type_cast && is_trivial_deref_cast(d))
84          continue;
85       *(--head) = d;
86    }
87 
88 done:
89    assert(head == path->path);
90    assert(tail == head + count);
91    assert(*tail == NULL);
92 }
93 
94 void
nir_deref_path_finish(nir_deref_path * path)95 nir_deref_path_finish(nir_deref_path *path)
96 {
97    if (path->path < &path->_short_path[0] ||
98        path->path > &path->_short_path[ARRAY_SIZE(path->_short_path) - 1])
99       ralloc_free(path->path);
100 }
101 
102 /**
103  * Recursively removes unused deref instructions
104  */
105 bool
nir_deref_instr_remove_if_unused(nir_deref_instr * instr)106 nir_deref_instr_remove_if_unused(nir_deref_instr *instr)
107 {
108    bool progress = false;
109 
110    for (nir_deref_instr *d = instr; d; d = nir_deref_instr_parent(d)) {
111       /* If anyone is using this deref, leave it alone */
112       assert(d->dest.is_ssa);
113       if (!list_is_empty(&d->dest.ssa.uses))
114          break;
115 
116       nir_instr_remove(&d->instr);
117       progress = true;
118    }
119 
120    return progress;
121 }
122 
123 bool
nir_deref_instr_has_indirect(nir_deref_instr * instr)124 nir_deref_instr_has_indirect(nir_deref_instr *instr)
125 {
126    while (instr->deref_type != nir_deref_type_var) {
127       /* Consider casts to be indirects */
128       if (instr->deref_type == nir_deref_type_cast)
129          return true;
130 
131       if ((instr->deref_type == nir_deref_type_array ||
132            instr->deref_type == nir_deref_type_ptr_as_array) &&
133           !nir_src_is_const(instr->arr.index))
134          return true;
135 
136       instr = nir_deref_instr_parent(instr);
137    }
138 
139    return false;
140 }
141 
142 bool
nir_deref_instr_is_known_out_of_bounds(nir_deref_instr * instr)143 nir_deref_instr_is_known_out_of_bounds(nir_deref_instr *instr)
144 {
145    for (; instr; instr = nir_deref_instr_parent(instr)) {
146       if (instr->deref_type == nir_deref_type_array &&
147           nir_src_is_const(instr->arr.index) &&
148            nir_src_as_uint(instr->arr.index) >=
149            glsl_get_length(nir_deref_instr_parent(instr)->type))
150          return true;
151    }
152 
153    return false;
154 }
155 
156 bool
nir_deref_instr_has_complex_use(nir_deref_instr * deref)157 nir_deref_instr_has_complex_use(nir_deref_instr *deref)
158 {
159    nir_foreach_use(use_src, &deref->dest.ssa) {
160       nir_instr *use_instr = use_src->parent_instr;
161 
162       switch (use_instr->type) {
163       case nir_instr_type_deref: {
164          nir_deref_instr *use_deref = nir_instr_as_deref(use_instr);
165 
166          /* A var deref has no sources */
167          assert(use_deref->deref_type != nir_deref_type_var);
168 
169          /* If a deref shows up in an array index or something like that, it's
170           * a complex use.
171           */
172          if (use_src != &use_deref->parent)
173             return true;
174 
175          /* Anything that isn't a basic struct or array deref is considered to
176           * be a "complex" use.  In particular, we don't allow ptr_as_array
177           * because we assume that opt_deref will turn any non-complex
178           * ptr_as_array derefs into regular array derefs eventually so passes
179           * which only want to handle simple derefs will pick them up in a
180           * later pass.
181           */
182          if (use_deref->deref_type != nir_deref_type_struct &&
183              use_deref->deref_type != nir_deref_type_array_wildcard &&
184              use_deref->deref_type != nir_deref_type_array)
185             return true;
186 
187          if (nir_deref_instr_has_complex_use(use_deref))
188             return true;
189 
190          continue;
191       }
192 
193       case nir_instr_type_intrinsic: {
194          nir_intrinsic_instr *use_intrin = nir_instr_as_intrinsic(use_instr);
195          switch (use_intrin->intrinsic) {
196          case nir_intrinsic_load_deref:
197             assert(use_src == &use_intrin->src[0]);
198             continue;
199 
200          case nir_intrinsic_copy_deref:
201             assert(use_src == &use_intrin->src[0] ||
202                    use_src == &use_intrin->src[1]);
203             continue;
204 
205          case nir_intrinsic_store_deref:
206             /* A use in src[1] of a store means we're taking that pointer and
207              * writing it to a variable.  Because we have no idea who will
208              * read that variable and what they will do with the pointer, it's
209              * considered a "complex" use.  A use in src[0], on the other
210              * hand, is a simple use because we're just going to dereference
211              * it and write a value there.
212              */
213             if (use_src == &use_intrin->src[0])
214                continue;
215             return true;
216 
217          default:
218             return true;
219          }
220          unreachable("Switch default failed");
221       }
222 
223       default:
224          return true;
225       }
226    }
227 
228    nir_foreach_if_use(use, &deref->dest.ssa)
229       return true;
230 
231    return false;
232 }
233 
234 static unsigned
type_scalar_size_bytes(const struct glsl_type * type)235 type_scalar_size_bytes(const struct glsl_type *type)
236 {
237    assert(glsl_type_is_vector_or_scalar(type) ||
238           glsl_type_is_matrix(type));
239    return glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
240 }
241 
242 unsigned
nir_deref_instr_array_stride(nir_deref_instr * deref)243 nir_deref_instr_array_stride(nir_deref_instr *deref)
244 {
245    switch (deref->deref_type) {
246    case nir_deref_type_array:
247    case nir_deref_type_array_wildcard: {
248       const struct glsl_type *arr_type = nir_deref_instr_parent(deref)->type;
249       unsigned stride = glsl_get_explicit_stride(arr_type);
250 
251       if ((glsl_type_is_matrix(arr_type) &&
252            glsl_matrix_type_is_row_major(arr_type)) ||
253           (glsl_type_is_vector(arr_type) && stride == 0))
254          stride = type_scalar_size_bytes(arr_type);
255 
256       return stride;
257    }
258    case nir_deref_type_ptr_as_array:
259       return nir_deref_instr_array_stride(nir_deref_instr_parent(deref));
260    case nir_deref_type_cast:
261       return deref->cast.ptr_stride;
262    default:
263       return 0;
264    }
265 }
266 
267 static unsigned
type_get_array_stride(const struct glsl_type * elem_type,glsl_type_size_align_func size_align)268 type_get_array_stride(const struct glsl_type *elem_type,
269                       glsl_type_size_align_func size_align)
270 {
271    unsigned elem_size, elem_align;
272    size_align(elem_type, &elem_size, &elem_align);
273    return ALIGN_POT(elem_size, elem_align);
274 }
275 
276 static unsigned
struct_type_get_field_offset(const struct glsl_type * struct_type,glsl_type_size_align_func size_align,unsigned field_idx)277 struct_type_get_field_offset(const struct glsl_type *struct_type,
278                              glsl_type_size_align_func size_align,
279                              unsigned field_idx)
280 {
281    assert(glsl_type_is_struct_or_ifc(struct_type));
282    unsigned offset = 0;
283    for (unsigned i = 0; i <= field_idx; i++) {
284       unsigned elem_size, elem_align;
285       size_align(glsl_get_struct_field(struct_type, i), &elem_size, &elem_align);
286       offset = ALIGN_POT(offset, elem_align);
287       if (i < field_idx)
288          offset += elem_size;
289    }
290    return offset;
291 }
292 
293 unsigned
nir_deref_instr_get_const_offset(nir_deref_instr * deref,glsl_type_size_align_func size_align)294 nir_deref_instr_get_const_offset(nir_deref_instr *deref,
295                                  glsl_type_size_align_func size_align)
296 {
297    nir_deref_path path;
298    nir_deref_path_init(&path, deref, NULL);
299 
300    unsigned offset = 0;
301    for (nir_deref_instr **p = &path.path[1]; *p; p++) {
302       switch ((*p)->deref_type) {
303       case nir_deref_type_array:
304          offset += nir_src_as_uint((*p)->arr.index) *
305                    type_get_array_stride((*p)->type, size_align);
306 	 break;
307       case nir_deref_type_struct: {
308          /* p starts at path[1], so this is safe */
309          nir_deref_instr *parent = *(p - 1);
310          offset += struct_type_get_field_offset(parent->type, size_align,
311                                                 (*p)->strct.index);
312 	 break;
313       }
314       case nir_deref_type_cast:
315          /* A cast doesn't contribute to the offset */
316          break;
317       default:
318          unreachable("Unsupported deref type");
319       }
320    }
321 
322    nir_deref_path_finish(&path);
323 
324    return offset;
325 }
326 
327 nir_ssa_def *
nir_build_deref_offset(nir_builder * b,nir_deref_instr * deref,glsl_type_size_align_func size_align)328 nir_build_deref_offset(nir_builder *b, nir_deref_instr *deref,
329                        glsl_type_size_align_func size_align)
330 {
331    nir_deref_path path;
332    nir_deref_path_init(&path, deref, NULL);
333 
334    nir_ssa_def *offset = nir_imm_intN_t(b, 0, deref->dest.ssa.bit_size);
335    for (nir_deref_instr **p = &path.path[1]; *p; p++) {
336       switch ((*p)->deref_type) {
337       case nir_deref_type_array: {
338          nir_ssa_def *index = nir_ssa_for_src(b, (*p)->arr.index, 1);
339          int stride = type_get_array_stride((*p)->type, size_align);
340          offset = nir_iadd(b, offset, nir_amul_imm(b, index, stride));
341          break;
342       }
343       case nir_deref_type_struct: {
344          /* p starts at path[1], so this is safe */
345          nir_deref_instr *parent = *(p - 1);
346          unsigned field_offset =
347             struct_type_get_field_offset(parent->type, size_align,
348                                          (*p)->strct.index);
349          offset = nir_iadd_imm(b, offset, field_offset);
350          break;
351       }
352       case nir_deref_type_cast:
353          /* A cast doesn't contribute to the offset */
354          break;
355       default:
356          unreachable("Unsupported deref type");
357       }
358    }
359 
360    nir_deref_path_finish(&path);
361 
362    return offset;
363 }
364 
365 bool
nir_remove_dead_derefs_impl(nir_function_impl * impl)366 nir_remove_dead_derefs_impl(nir_function_impl *impl)
367 {
368    bool progress = false;
369 
370    nir_foreach_block(block, impl) {
371       nir_foreach_instr_safe(instr, block) {
372          if (instr->type == nir_instr_type_deref &&
373              nir_deref_instr_remove_if_unused(nir_instr_as_deref(instr)))
374             progress = true;
375       }
376    }
377 
378    if (progress)
379       nir_metadata_preserve(impl, nir_metadata_block_index |
380                                   nir_metadata_dominance);
381 
382    return progress;
383 }
384 
385 bool
nir_remove_dead_derefs(nir_shader * shader)386 nir_remove_dead_derefs(nir_shader *shader)
387 {
388    bool progress = false;
389    nir_foreach_function(function, shader) {
390       if (function->impl && nir_remove_dead_derefs_impl(function->impl))
391          progress = true;
392    }
393 
394    return progress;
395 }
396 
397 void
nir_fixup_deref_modes(nir_shader * shader)398 nir_fixup_deref_modes(nir_shader *shader)
399 {
400    nir_foreach_function(function, shader) {
401       if (!function->impl)
402          continue;
403 
404       nir_foreach_block(block, function->impl) {
405          nir_foreach_instr(instr, block) {
406             if (instr->type != nir_instr_type_deref)
407                continue;
408 
409             nir_deref_instr *deref = nir_instr_as_deref(instr);
410             if (deref->deref_type == nir_deref_type_cast)
411                continue;
412 
413             nir_variable_mode parent_modes;
414             if (deref->deref_type == nir_deref_type_var) {
415                parent_modes = deref->var->data.mode;
416             } else {
417                assert(deref->parent.is_ssa);
418                nir_deref_instr *parent =
419                   nir_instr_as_deref(deref->parent.ssa->parent_instr);
420                parent_modes = parent->modes;
421             }
422 
423             deref->modes = parent_modes;
424          }
425       }
426    }
427 }
428 
429 static bool
modes_may_alias(nir_variable_mode a,nir_variable_mode b)430 modes_may_alias(nir_variable_mode a, nir_variable_mode b)
431 {
432    /* Generic pointers can alias with SSBOs */
433    if ((a & (nir_var_mem_ssbo | nir_var_mem_global)) &&
434        (b & (nir_var_mem_ssbo | nir_var_mem_global)))
435       return true;
436 
437    /* Pointers can only alias if they share a mode. */
438    return a & b;
439 }
440 
441 static bool
deref_path_contains_coherent_decoration(nir_deref_path * path)442 deref_path_contains_coherent_decoration(nir_deref_path *path)
443 {
444    assert(path->path[0]->deref_type == nir_deref_type_var);
445 
446    if (path->path[0]->var->data.access & ACCESS_COHERENT)
447       return true;
448 
449    for (nir_deref_instr **p = &path->path[1]; *p; p++) {
450       if ((*p)->deref_type != nir_deref_type_struct)
451          continue;
452 
453       const struct glsl_type *struct_type = (*(p - 1))->type;
454       const struct glsl_struct_field *field =
455          glsl_get_struct_field_data(struct_type, (*p)->strct.index);
456       if (field->memory_coherent)
457          return true;
458    }
459 
460    return false;
461 }
462 
463 nir_deref_compare_result
nir_compare_deref_paths(nir_deref_path * a_path,nir_deref_path * b_path)464 nir_compare_deref_paths(nir_deref_path *a_path,
465                         nir_deref_path *b_path)
466 {
467    if (!modes_may_alias(b_path->path[0]->modes, a_path->path[0]->modes))
468       return nir_derefs_do_not_alias;
469 
470    if (a_path->path[0]->deref_type != b_path->path[0]->deref_type)
471       return nir_derefs_may_alias_bit;
472 
473    if (a_path->path[0]->deref_type == nir_deref_type_var) {
474       if (a_path->path[0]->var != b_path->path[0]->var) {
475          /* Shader and function temporaries aren't backed by memory so two
476           * distinct variables never alias.
477           */
478          static const nir_variable_mode temp_var_modes =
479             nir_var_shader_temp | nir_var_function_temp;
480          if (!(a_path->path[0]->modes & ~temp_var_modes) ||
481              !(b_path->path[0]->modes & ~temp_var_modes))
482             return nir_derefs_do_not_alias;
483 
484          /* If they are both declared coherent or have coherent somewhere in
485           * their path (due to a member of an interface being declared
486           * coherent), we have to assume we that we could have any kind of
487           * aliasing.  Otherwise, they could still alias but the client didn't
488           * tell us and that's their fault.
489           */
490          if (deref_path_contains_coherent_decoration(a_path) &&
491              deref_path_contains_coherent_decoration(b_path))
492             return nir_derefs_may_alias_bit;
493 
494          /* If we can chase the deref all the way back to the variable and
495           * they're not the same variable and at least one is not declared
496           * coherent, we know they can't possibly alias.
497           */
498          return nir_derefs_do_not_alias;
499       }
500    } else {
501       assert(a_path->path[0]->deref_type == nir_deref_type_cast);
502       /* If they're not exactly the same cast, it's hard to compare them so we
503        * just assume they alias.  Comparing casts is tricky as there are lots
504        * of things such as mode, type, etc. to make sure work out; for now, we
505        * just assume nit_opt_deref will combine them and compare the deref
506        * instructions.
507        *
508        * TODO: At some point in the future, we could be clever and understand
509        * that a float[] and int[] have the same layout and aliasing structure
510        * but double[] and vec3[] do not and we could potentially be a bit
511        * smarter here.
512        */
513       if (a_path->path[0] != b_path->path[0])
514          return nir_derefs_may_alias_bit;
515    }
516 
517    /* Start off assuming they fully compare.  We ignore equality for now.  In
518     * the end, we'll determine that by containment.
519     */
520    nir_deref_compare_result result = nir_derefs_may_alias_bit |
521                                      nir_derefs_a_contains_b_bit |
522                                      nir_derefs_b_contains_a_bit;
523 
524    nir_deref_instr **a_p = &a_path->path[1];
525    nir_deref_instr **b_p = &b_path->path[1];
526    while (*a_p != NULL && *a_p == *b_p) {
527       a_p++;
528       b_p++;
529    }
530 
531    /* We're at either the tail or the divergence point between the two deref
532     * paths.  Look to see if either contains cast or a ptr_as_array deref.  If
533     * it does we don't know how to safely make any inferences.  Hopefully,
534     * nir_opt_deref will clean most of these up and we can start inferring
535     * things again.
536     *
537     * In theory, we could do a bit better.  For instance, we could detect the
538     * case where we have exactly one ptr_as_array deref in the chain after the
539     * divergence point and it's matched in both chains and the two chains have
540     * different constant indices.
541     */
542    for (nir_deref_instr **t_p = a_p; *t_p; t_p++) {
543       if ((*t_p)->deref_type == nir_deref_type_cast ||
544           (*t_p)->deref_type == nir_deref_type_ptr_as_array)
545          return nir_derefs_may_alias_bit;
546    }
547    for (nir_deref_instr **t_p = b_p; *t_p; t_p++) {
548       if ((*t_p)->deref_type == nir_deref_type_cast ||
549           (*t_p)->deref_type == nir_deref_type_ptr_as_array)
550          return nir_derefs_may_alias_bit;
551    }
552 
553    while (*a_p != NULL && *b_p != NULL) {
554       nir_deref_instr *a_tail = *(a_p++);
555       nir_deref_instr *b_tail = *(b_p++);
556 
557       switch (a_tail->deref_type) {
558       case nir_deref_type_array:
559       case nir_deref_type_array_wildcard: {
560          assert(b_tail->deref_type == nir_deref_type_array ||
561                 b_tail->deref_type == nir_deref_type_array_wildcard);
562 
563          if (a_tail->deref_type == nir_deref_type_array_wildcard) {
564             if (b_tail->deref_type != nir_deref_type_array_wildcard)
565                result &= ~nir_derefs_b_contains_a_bit;
566          } else if (b_tail->deref_type == nir_deref_type_array_wildcard) {
567             if (a_tail->deref_type != nir_deref_type_array_wildcard)
568                result &= ~nir_derefs_a_contains_b_bit;
569          } else {
570             assert(a_tail->deref_type == nir_deref_type_array &&
571                    b_tail->deref_type == nir_deref_type_array);
572             assert(a_tail->arr.index.is_ssa && b_tail->arr.index.is_ssa);
573 
574             if (nir_src_is_const(a_tail->arr.index) &&
575                 nir_src_is_const(b_tail->arr.index)) {
576                /* If they're both direct and have different offsets, they
577                 * don't even alias much less anything else.
578                 */
579                if (nir_src_as_uint(a_tail->arr.index) !=
580                    nir_src_as_uint(b_tail->arr.index))
581                   return nir_derefs_do_not_alias;
582             } else if (a_tail->arr.index.ssa == b_tail->arr.index.ssa) {
583                /* They're the same indirect, continue on */
584             } else {
585                /* They're not the same index so we can't prove anything about
586                 * containment.
587                 */
588                result &= ~(nir_derefs_a_contains_b_bit | nir_derefs_b_contains_a_bit);
589             }
590          }
591          break;
592       }
593 
594       case nir_deref_type_struct: {
595          /* If they're different struct members, they don't even alias */
596          if (a_tail->strct.index != b_tail->strct.index)
597             return nir_derefs_do_not_alias;
598          break;
599       }
600 
601       default:
602          unreachable("Invalid deref type");
603       }
604    }
605 
606    /* If a is longer than b, then it can't contain b */
607    if (*a_p != NULL)
608       result &= ~nir_derefs_a_contains_b_bit;
609    if (*b_p != NULL)
610       result &= ~nir_derefs_b_contains_a_bit;
611 
612    /* If a contains b and b contains a they must be equal. */
613    if ((result & nir_derefs_a_contains_b_bit) && (result & nir_derefs_b_contains_a_bit))
614       result |= nir_derefs_equal_bit;
615 
616    return result;
617 }
618 
619 nir_deref_compare_result
nir_compare_derefs(nir_deref_instr * a,nir_deref_instr * b)620 nir_compare_derefs(nir_deref_instr *a, nir_deref_instr *b)
621 {
622    if (a == b) {
623       return nir_derefs_equal_bit | nir_derefs_may_alias_bit |
624              nir_derefs_a_contains_b_bit | nir_derefs_b_contains_a_bit;
625    }
626 
627    nir_deref_path a_path, b_path;
628    nir_deref_path_init(&a_path, a, NULL);
629    nir_deref_path_init(&b_path, b, NULL);
630    assert(a_path.path[0]->deref_type == nir_deref_type_var ||
631           a_path.path[0]->deref_type == nir_deref_type_cast);
632    assert(b_path.path[0]->deref_type == nir_deref_type_var ||
633           b_path.path[0]->deref_type == nir_deref_type_cast);
634 
635    nir_deref_compare_result result = nir_compare_deref_paths(&a_path, &b_path);
636 
637    nir_deref_path_finish(&a_path);
638    nir_deref_path_finish(&b_path);
639 
640    return result;
641 }
642 
643 struct rematerialize_deref_state {
644    bool progress;
645    nir_builder builder;
646    nir_block *block;
647    struct hash_table *cache;
648 };
649 
650 static nir_deref_instr *
rematerialize_deref_in_block(nir_deref_instr * deref,struct rematerialize_deref_state * state)651 rematerialize_deref_in_block(nir_deref_instr *deref,
652                              struct rematerialize_deref_state *state)
653 {
654    if (deref->instr.block == state->block)
655       return deref;
656 
657    if (!state->cache) {
658       state->cache = _mesa_pointer_hash_table_create(NULL);
659    }
660 
661    struct hash_entry *cached = _mesa_hash_table_search(state->cache, deref);
662    if (cached)
663       return cached->data;
664 
665    nir_builder *b = &state->builder;
666    nir_deref_instr *new_deref =
667       nir_deref_instr_create(b->shader, deref->deref_type);
668    new_deref->modes = deref->modes;
669    new_deref->type = deref->type;
670 
671    if (deref->deref_type == nir_deref_type_var) {
672       new_deref->var = deref->var;
673    } else {
674       nir_deref_instr *parent = nir_src_as_deref(deref->parent);
675       if (parent) {
676          parent = rematerialize_deref_in_block(parent, state);
677          new_deref->parent = nir_src_for_ssa(&parent->dest.ssa);
678       } else {
679          nir_src_copy(&new_deref->parent, &deref->parent, new_deref);
680       }
681    }
682 
683    switch (deref->deref_type) {
684    case nir_deref_type_var:
685    case nir_deref_type_array_wildcard:
686       /* Nothing more to do */
687       break;
688 
689    case nir_deref_type_cast:
690       new_deref->cast.ptr_stride = deref->cast.ptr_stride;
691       break;
692 
693    case nir_deref_type_array:
694    case nir_deref_type_ptr_as_array:
695       assert(!nir_src_as_deref(deref->arr.index));
696       nir_src_copy(&new_deref->arr.index, &deref->arr.index, new_deref);
697       break;
698 
699    case nir_deref_type_struct:
700       new_deref->strct.index = deref->strct.index;
701       break;
702 
703    default:
704       unreachable("Invalid deref instruction type");
705    }
706 
707    nir_ssa_dest_init(&new_deref->instr, &new_deref->dest,
708                      deref->dest.ssa.num_components,
709                      deref->dest.ssa.bit_size,
710                      deref->dest.ssa.name);
711    nir_builder_instr_insert(b, &new_deref->instr);
712 
713    return new_deref;
714 }
715 
716 static bool
rematerialize_deref_src(nir_src * src,void * _state)717 rematerialize_deref_src(nir_src *src, void *_state)
718 {
719    struct rematerialize_deref_state *state = _state;
720 
721    nir_deref_instr *deref = nir_src_as_deref(*src);
722    if (!deref)
723       return true;
724 
725    nir_deref_instr *block_deref = rematerialize_deref_in_block(deref, state);
726    if (block_deref != deref) {
727       nir_instr_rewrite_src(src->parent_instr, src,
728                             nir_src_for_ssa(&block_deref->dest.ssa));
729       nir_deref_instr_remove_if_unused(deref);
730       state->progress = true;
731    }
732 
733    return true;
734 }
735 
736 /** Re-materialize derefs in every block
737  *
738  * This pass re-materializes deref instructions in every block in which it is
739  * used.  After this pass has been run, every use of a deref will be of a
740  * deref in the same block as the use.  Also, all unused derefs will be
741  * deleted as a side-effect.
742  *
743  * Derefs used as sources of phi instructions are not rematerialized.
744  */
745 bool
nir_rematerialize_derefs_in_use_blocks_impl(nir_function_impl * impl)746 nir_rematerialize_derefs_in_use_blocks_impl(nir_function_impl *impl)
747 {
748    struct rematerialize_deref_state state = { 0 };
749    nir_builder_init(&state.builder, impl);
750 
751    nir_foreach_block_unstructured(block, impl) {
752       state.block = block;
753 
754       /* Start each block with a fresh cache */
755       if (state.cache)
756          _mesa_hash_table_clear(state.cache, NULL);
757 
758       nir_foreach_instr_safe(instr, block) {
759          if (instr->type == nir_instr_type_deref &&
760              nir_deref_instr_remove_if_unused(nir_instr_as_deref(instr)))
761             continue;
762 
763          /* If a deref is used in a phi, we can't rematerialize it, as the new
764           * derefs would appear before the phi, which is not valid.
765           */
766          if (instr->type == nir_instr_type_phi)
767             continue;
768 
769          state.builder.cursor = nir_before_instr(instr);
770          nir_foreach_src(instr, rematerialize_deref_src, &state);
771       }
772 
773 #ifndef NDEBUG
774       nir_if *following_if = nir_block_get_following_if(block);
775       if (following_if)
776          assert(!nir_src_as_deref(following_if->condition));
777 #endif
778    }
779 
780    _mesa_hash_table_destroy(state.cache, NULL);
781 
782    return state.progress;
783 }
784 
785 static void
nir_deref_instr_fixup_child_types(nir_deref_instr * parent)786 nir_deref_instr_fixup_child_types(nir_deref_instr *parent)
787 {
788    nir_foreach_use(use, &parent->dest.ssa) {
789       if (use->parent_instr->type != nir_instr_type_deref)
790          continue;
791 
792       nir_deref_instr *child = nir_instr_as_deref(use->parent_instr);
793       switch (child->deref_type) {
794       case nir_deref_type_var:
795          unreachable("nir_deref_type_var cannot be a child");
796 
797       case nir_deref_type_array:
798       case nir_deref_type_array_wildcard:
799          child->type = glsl_get_array_element(parent->type);
800          break;
801 
802       case nir_deref_type_ptr_as_array:
803          child->type = parent->type;
804          break;
805 
806       case nir_deref_type_struct:
807          child->type = glsl_get_struct_field(parent->type,
808                                              child->strct.index);
809          break;
810 
811       case nir_deref_type_cast:
812          /* We stop the recursion here */
813          continue;
814       }
815 
816       /* Recurse into children */
817       nir_deref_instr_fixup_child_types(child);
818    }
819 }
820 
821 static bool
is_trivial_array_deref_cast(nir_deref_instr * cast)822 is_trivial_array_deref_cast(nir_deref_instr *cast)
823 {
824    assert(is_trivial_deref_cast(cast));
825 
826    nir_deref_instr *parent = nir_src_as_deref(cast->parent);
827 
828    if (parent->deref_type == nir_deref_type_array) {
829       return cast->cast.ptr_stride ==
830              glsl_get_explicit_stride(nir_deref_instr_parent(parent)->type);
831    } else if (parent->deref_type == nir_deref_type_ptr_as_array) {
832       return cast->cast.ptr_stride ==
833              nir_deref_instr_array_stride(parent);
834    } else {
835       return false;
836    }
837 }
838 
839 static bool
is_deref_ptr_as_array(nir_instr * instr)840 is_deref_ptr_as_array(nir_instr *instr)
841 {
842    return instr->type == nir_instr_type_deref &&
843           nir_instr_as_deref(instr)->deref_type == nir_deref_type_ptr_as_array;
844 }
845 
846 static bool
opt_remove_restricting_cast_alignments(nir_deref_instr * cast)847 opt_remove_restricting_cast_alignments(nir_deref_instr *cast)
848 {
849    assert(cast->deref_type == nir_deref_type_cast);
850    if (cast->cast.align_mul == 0)
851       return false;
852 
853    nir_deref_instr *parent = nir_src_as_deref(cast->parent);
854    if (parent == NULL)
855       return false;
856 
857    /* Don't use any default alignment for this check.  We don't want to fall
858     * back to type alignment too early in case we find out later that we're
859     * somehow a child of a packed struct.
860     */
861    uint32_t parent_mul, parent_offset;
862    if (!nir_get_explicit_deref_align(parent, false /* default_to_type_align */,
863                                      &parent_mul, &parent_offset))
864       return false;
865 
866    /* If this cast increases the alignment, we want to keep it.
867     *
868     * There is a possibility that the larger alignment provided by this cast
869     * somehow disagrees with the smaller alignment further up the deref chain.
870     * In that case, we choose to favor the alignment closer to the actual
871     * memory operation which, in this case, is the cast and not its parent so
872     * keeping the cast alignment is the right thing to do.
873     */
874    if (parent_mul < cast->cast.align_mul)
875       return false;
876 
877    /* If we've gotten here, we have a parent deref with an align_mul at least
878     * as large as ours so we can potentially throw away the alignment
879     * information on this deref.  There are two cases to consider here:
880     *
881     *  1. We can chase the deref all the way back to the variable.  In this
882     *     case, we have "perfect" knowledge, modulo indirect array derefs.
883     *     Unless we've done something wrong in our indirect/wildcard stride
884     *     calculations, our knowledge from the deref walk is better than the
885     *     client's.
886     *
887     *  2. We can't chase it all the way back to the variable.  In this case,
888     *     because our call to nir_get_explicit_deref_align(parent, ...) above
889     *     above passes default_to_type_align=false, the only way we can even
890     *     get here is if something further up the deref chain has a cast with
891     *     an alignment which can only happen if we get an alignment from the
892     *     client (most likely a decoration in the SPIR-V).  If the client has
893     *     provided us with two conflicting alignments in the deref chain,
894     *     that's their fault and we can do whatever we want.
895     *
896     * In either case, we should be without our rights, at this point, to throw
897     * away the alignment information on this deref.  However, to be "nice" to
898     * weird clients, we do one more check.  It really shouldn't happen but
899     * it's possible that the parent's alignment offset disagrees with the
900     * cast's alignment offset.  In this case, we consider the cast as
901     * providing more information (or at least more valid information) and keep
902     * it even if the align_mul from the parent is larger.
903     */
904    assert(cast->cast.align_mul <= parent_mul);
905    if (parent_offset % cast->cast.align_mul != cast->cast.align_offset)
906       return false;
907 
908    /* If we got here, the parent has better alignment information than the
909     * child and we can get rid of the child alignment information.
910     */
911    cast->cast.align_mul = 0;
912    cast->cast.align_offset = 0;
913    return true;
914 }
915 
916 /**
917  * Remove casts that just wrap other casts.
918  */
919 static bool
opt_remove_cast_cast(nir_deref_instr * cast)920 opt_remove_cast_cast(nir_deref_instr *cast)
921 {
922    nir_deref_instr *first_cast = cast;
923 
924    while (true) {
925       nir_deref_instr *parent = nir_deref_instr_parent(first_cast);
926       if (parent == NULL || parent->deref_type != nir_deref_type_cast)
927          break;
928       first_cast = parent;
929    }
930    if (cast == first_cast)
931       return false;
932 
933    nir_instr_rewrite_src(&cast->instr, &cast->parent,
934                          nir_src_for_ssa(first_cast->parent.ssa));
935    return true;
936 }
937 
938 /* Restrict variable modes in casts.
939  *
940  * If we know from something higher up the deref chain that the deref has a
941  * specific mode, we can cast to more general and back but we can never cast
942  * across modes.  For non-cast derefs, we should only ever do anything here if
943  * the parent eventually comes from a cast that we restricted earlier.
944  */
945 static bool
opt_restrict_deref_modes(nir_deref_instr * deref)946 opt_restrict_deref_modes(nir_deref_instr *deref)
947 {
948    if (deref->deref_type == nir_deref_type_var) {
949       assert(deref->modes == deref->var->data.mode);
950       return false;
951    }
952 
953    nir_deref_instr *parent = nir_src_as_deref(deref->parent);
954    if (parent == NULL || parent->modes == deref->modes)
955       return false;
956 
957    assert(parent->modes & deref->modes);
958    deref->modes &= parent->modes;
959    return true;
960 }
961 
962 static bool
opt_remove_sampler_cast(nir_deref_instr * cast)963 opt_remove_sampler_cast(nir_deref_instr *cast)
964 {
965    assert(cast->deref_type == nir_deref_type_cast);
966    nir_deref_instr *parent = nir_src_as_deref(cast->parent);
967    if (parent == NULL)
968       return false;
969 
970    /* Strip both types down to their non-array type and bail if there are any
971     * discrepancies in array lengths.
972     */
973    const struct glsl_type *parent_type = parent->type;
974    const struct glsl_type *cast_type = cast->type;
975    while (glsl_type_is_array(parent_type) && glsl_type_is_array(cast_type)) {
976       if (glsl_get_length(parent_type) != glsl_get_length(cast_type))
977          return false;
978       parent_type = glsl_get_array_element(parent_type);
979       cast_type = glsl_get_array_element(cast_type);
980    }
981 
982    if (glsl_type_is_array(parent_type) || glsl_type_is_array(cast_type))
983       return false;
984 
985    if (!glsl_type_is_sampler(parent_type) ||
986        cast_type != glsl_bare_sampler_type())
987       return false;
988 
989    /* We're a cast from a more detailed sampler type to a bare sampler */
990    nir_ssa_def_rewrite_uses(&cast->dest.ssa,
991                             nir_src_for_ssa(&parent->dest.ssa));
992    nir_instr_remove(&cast->instr);
993 
994    /* Recursively crawl the deref tree and clean up types */
995    nir_deref_instr_fixup_child_types(parent);
996 
997    return true;
998 }
999 
1000 /**
1001  * Is this casting a struct to a contained struct.
1002  * struct a { struct b field0 };
1003  * ssa_5 is structa;
1004  * deref_cast (structb *)ssa_5 (function_temp structb);
1005  * converts to
1006  * deref_struct &ssa_5->field0 (function_temp structb);
1007  * This allows subsequent copy propagation to work.
1008  */
1009 static bool
opt_replace_struct_wrapper_cast(nir_builder * b,nir_deref_instr * cast)1010 opt_replace_struct_wrapper_cast(nir_builder *b, nir_deref_instr *cast)
1011 {
1012    nir_deref_instr *parent = nir_src_as_deref(cast->parent);
1013    if (!parent)
1014       return false;
1015 
1016    if (cast->cast.align_mul > 0)
1017       return false;
1018 
1019    if (!glsl_type_is_struct(parent->type))
1020       return false;
1021 
1022    if (glsl_get_struct_field_offset(parent->type, 0) != 0)
1023       return false;
1024 
1025    if (cast->type != glsl_get_struct_field(parent->type, 0))
1026       return false;
1027 
1028    nir_deref_instr *replace = nir_build_deref_struct(b, parent, 0);
1029    nir_ssa_def_rewrite_uses(&cast->dest.ssa, nir_src_for_ssa(&replace->dest.ssa));
1030    nir_deref_instr_remove_if_unused(cast);
1031    return true;
1032 }
1033 
1034 static bool
opt_deref_cast(nir_builder * b,nir_deref_instr * cast)1035 opt_deref_cast(nir_builder *b, nir_deref_instr *cast)
1036 {
1037    bool progress = false;
1038 
1039    progress |= opt_remove_restricting_cast_alignments(cast);
1040 
1041    if (opt_replace_struct_wrapper_cast(b, cast))
1042       return true;
1043 
1044    if (opt_remove_sampler_cast(cast))
1045       return true;
1046 
1047    progress |= opt_remove_cast_cast(cast);
1048    if (!is_trivial_deref_cast(cast))
1049       return progress;
1050 
1051    /* If this deref still contains useful alignment information, we don't want
1052     * to delete it.
1053     */
1054    if (cast->cast.align_mul > 0)
1055       return progress;
1056 
1057    bool trivial_array_cast = is_trivial_array_deref_cast(cast);
1058 
1059    assert(cast->dest.is_ssa);
1060    assert(cast->parent.is_ssa);
1061 
1062    nir_foreach_use_safe(use_src, &cast->dest.ssa) {
1063       /* If this isn't a trivial array cast, we can't propagate into
1064        * ptr_as_array derefs.
1065        */
1066       if (is_deref_ptr_as_array(use_src->parent_instr) &&
1067           !trivial_array_cast)
1068          continue;
1069 
1070       nir_instr_rewrite_src(use_src->parent_instr, use_src, cast->parent);
1071       progress = true;
1072    }
1073 
1074    /* If uses would be a bit crazy */
1075    assert(list_is_empty(&cast->dest.ssa.if_uses));
1076 
1077    if (nir_deref_instr_remove_if_unused(cast))
1078       progress = true;
1079 
1080    return progress;
1081 }
1082 
1083 static bool
opt_deref_ptr_as_array(nir_builder * b,nir_deref_instr * deref)1084 opt_deref_ptr_as_array(nir_builder *b, nir_deref_instr *deref)
1085 {
1086    assert(deref->deref_type == nir_deref_type_ptr_as_array);
1087 
1088    nir_deref_instr *parent = nir_deref_instr_parent(deref);
1089 
1090    if (nir_src_is_const(deref->arr.index) &&
1091        nir_src_as_int(deref->arr.index) == 0) {
1092       /* If it's a ptr_as_array deref with an index of 0, it does nothing
1093        * and we can just replace its uses with its parent.
1094        *
1095        * The source of a ptr_as_array deref always has a deref_type of
1096        * nir_deref_type_array or nir_deref_type_cast.  If it's a cast, it
1097        * may be trivial and we may be able to get rid of that too.  Any
1098        * trivial cast of trivial cast cases should be handled already by
1099        * opt_deref_cast() above.
1100        */
1101       if (parent->deref_type == nir_deref_type_cast &&
1102           is_trivial_deref_cast(parent))
1103          parent = nir_deref_instr_parent(parent);
1104       nir_ssa_def_rewrite_uses(&deref->dest.ssa,
1105                                nir_src_for_ssa(&parent->dest.ssa));
1106       nir_instr_remove(&deref->instr);
1107       return true;
1108    }
1109 
1110    if (parent->deref_type != nir_deref_type_array &&
1111        parent->deref_type != nir_deref_type_ptr_as_array)
1112       return false;
1113 
1114    assert(parent->parent.is_ssa);
1115    assert(parent->arr.index.is_ssa);
1116    assert(deref->arr.index.is_ssa);
1117 
1118    nir_ssa_def *new_idx = nir_iadd(b, parent->arr.index.ssa,
1119                                       deref->arr.index.ssa);
1120 
1121    deref->deref_type = parent->deref_type;
1122    nir_instr_rewrite_src(&deref->instr, &deref->parent, parent->parent);
1123    nir_instr_rewrite_src(&deref->instr, &deref->arr.index,
1124                          nir_src_for_ssa(new_idx));
1125    return true;
1126 }
1127 
1128 static bool
is_vector_bitcast_deref(nir_deref_instr * cast,nir_component_mask_t mask,bool is_write)1129 is_vector_bitcast_deref(nir_deref_instr *cast,
1130                         nir_component_mask_t mask,
1131                         bool is_write)
1132 {
1133    if (cast->deref_type != nir_deref_type_cast)
1134       return false;
1135 
1136    /* Don't throw away useful alignment information */
1137    if (cast->cast.align_mul > 0)
1138       return false;
1139 
1140    /* It has to be a cast of another deref */
1141    nir_deref_instr *parent = nir_src_as_deref(cast->parent);
1142    if (parent == NULL)
1143       return false;
1144 
1145    /* The parent has to be a vector or scalar */
1146    if (!glsl_type_is_vector_or_scalar(parent->type))
1147       return false;
1148 
1149    /* Don't bother with 1-bit types */
1150    unsigned cast_bit_size = glsl_get_bit_size(cast->type);
1151    unsigned parent_bit_size = glsl_get_bit_size(parent->type);
1152    if (cast_bit_size == 1 || parent_bit_size == 1)
1153       return false;
1154 
1155    /* A strided vector type means it's not tightly packed */
1156    if (glsl_get_explicit_stride(cast->type) ||
1157        glsl_get_explicit_stride(parent->type))
1158       return false;
1159 
1160    assert(cast_bit_size > 0 && cast_bit_size % 8 == 0);
1161    assert(parent_bit_size > 0 && parent_bit_size % 8 == 0);
1162    unsigned bytes_used = util_last_bit(mask) * (cast_bit_size / 8);
1163    unsigned parent_bytes = glsl_get_vector_elements(parent->type) *
1164                            (parent_bit_size / 8);
1165    if (bytes_used > parent_bytes)
1166       return false;
1167 
1168    if (is_write && !nir_component_mask_can_reinterpret(mask, cast_bit_size,
1169                                                        parent_bit_size))
1170       return false;
1171 
1172    return true;
1173 }
1174 
1175 static nir_ssa_def *
resize_vector(nir_builder * b,nir_ssa_def * data,unsigned num_components)1176 resize_vector(nir_builder *b, nir_ssa_def *data, unsigned num_components)
1177 {
1178    if (num_components == data->num_components)
1179       return data;
1180 
1181    unsigned swiz[NIR_MAX_VEC_COMPONENTS] = { 0, };
1182    for (unsigned i = 0; i < MIN2(num_components, data->num_components); i++)
1183       swiz[i] = i;
1184 
1185    return nir_swizzle(b, data, swiz, num_components);
1186 }
1187 
1188 static bool
opt_load_vec_deref(nir_builder * b,nir_intrinsic_instr * load)1189 opt_load_vec_deref(nir_builder *b, nir_intrinsic_instr *load)
1190 {
1191    nir_deref_instr *deref = nir_src_as_deref(load->src[0]);
1192    nir_component_mask_t read_mask =
1193       nir_ssa_def_components_read(&load->dest.ssa);
1194 
1195    /* LLVM loves take advantage of the fact that vec3s in OpenCL are
1196     * vec4-aligned and so it can just read/write them as vec4s.  This
1197     * results in a LOT of vec4->vec3 casts on loads and stores.
1198     */
1199    if (is_vector_bitcast_deref(deref, read_mask, false)) {
1200       const unsigned old_num_comps = load->dest.ssa.num_components;
1201       const unsigned old_bit_size = load->dest.ssa.bit_size;
1202 
1203       nir_deref_instr *parent = nir_src_as_deref(deref->parent);
1204       const unsigned new_num_comps = glsl_get_vector_elements(parent->type);
1205       const unsigned new_bit_size = glsl_get_bit_size(parent->type);
1206 
1207       /* Stomp it to reference the parent */
1208       nir_instr_rewrite_src(&load->instr, &load->src[0],
1209                             nir_src_for_ssa(&parent->dest.ssa));
1210       assert(load->dest.is_ssa);
1211       load->dest.ssa.bit_size = new_bit_size;
1212       load->dest.ssa.num_components = new_num_comps;
1213       load->num_components = new_num_comps;
1214 
1215       b->cursor = nir_after_instr(&load->instr);
1216       nir_ssa_def *data = &load->dest.ssa;
1217       if (old_bit_size != new_bit_size)
1218          data = nir_bitcast_vector(b, &load->dest.ssa, old_bit_size);
1219       data = resize_vector(b, data, old_num_comps);
1220 
1221       nir_ssa_def_rewrite_uses_after(&load->dest.ssa, nir_src_for_ssa(data),
1222                                      data->parent_instr);
1223       return true;
1224    }
1225 
1226    return false;
1227 }
1228 
1229 static bool
opt_store_vec_deref(nir_builder * b,nir_intrinsic_instr * store)1230 opt_store_vec_deref(nir_builder *b, nir_intrinsic_instr *store)
1231 {
1232    nir_deref_instr *deref = nir_src_as_deref(store->src[0]);
1233    nir_component_mask_t write_mask = nir_intrinsic_write_mask(store);
1234 
1235    /* LLVM loves take advantage of the fact that vec3s in OpenCL are
1236     * vec4-aligned and so it can just read/write them as vec4s.  This
1237     * results in a LOT of vec4->vec3 casts on loads and stores.
1238     */
1239    if (is_vector_bitcast_deref(deref, write_mask, true)) {
1240       assert(store->src[1].is_ssa);
1241       nir_ssa_def *data = store->src[1].ssa;
1242 
1243       const unsigned old_bit_size = data->bit_size;
1244 
1245       nir_deref_instr *parent = nir_src_as_deref(deref->parent);
1246       const unsigned new_num_comps = glsl_get_vector_elements(parent->type);
1247       const unsigned new_bit_size = glsl_get_bit_size(parent->type);
1248 
1249       nir_instr_rewrite_src(&store->instr, &store->src[0],
1250                             nir_src_for_ssa(&parent->dest.ssa));
1251 
1252       /* Restrict things down as needed so the bitcast doesn't fail */
1253       data = nir_channels(b, data, (1 << util_last_bit(write_mask)) - 1);
1254       if (old_bit_size != new_bit_size)
1255          data = nir_bitcast_vector(b, data, new_bit_size);
1256       data = resize_vector(b, data, new_num_comps);
1257       nir_instr_rewrite_src(&store->instr, &store->src[1],
1258                             nir_src_for_ssa(data));
1259       store->num_components = new_num_comps;
1260 
1261       /* Adjust the write mask */
1262       write_mask = nir_component_mask_reinterpret(write_mask, old_bit_size,
1263                                                   new_bit_size);
1264       nir_intrinsic_set_write_mask(store, write_mask);
1265       return true;
1266    }
1267 
1268    return false;
1269 }
1270 
1271 static bool
opt_known_deref_mode_is(nir_builder * b,nir_intrinsic_instr * intrin)1272 opt_known_deref_mode_is(nir_builder *b, nir_intrinsic_instr *intrin)
1273 {
1274    nir_variable_mode modes = nir_intrinsic_memory_modes(intrin);
1275    nir_deref_instr *deref = nir_src_as_deref(intrin->src[0]);
1276    if (deref == NULL)
1277       return false;
1278 
1279    nir_ssa_def *deref_is = NULL;
1280 
1281    if (nir_deref_mode_must_be(deref, modes))
1282       deref_is = nir_imm_true(b);
1283 
1284    if (!nir_deref_mode_may_be(deref, modes))
1285       deref_is = nir_imm_false(b);
1286 
1287    if (deref_is == NULL)
1288       return false;
1289 
1290    nir_ssa_def_rewrite_uses(&intrin->dest.ssa, nir_src_for_ssa(deref_is));
1291    nir_instr_remove(&intrin->instr);
1292    return true;
1293 }
1294 
1295 bool
nir_opt_deref_impl(nir_function_impl * impl)1296 nir_opt_deref_impl(nir_function_impl *impl)
1297 {
1298    bool progress = false;
1299 
1300    nir_builder b;
1301    nir_builder_init(&b, impl);
1302 
1303    nir_foreach_block(block, impl) {
1304       nir_foreach_instr_safe(instr, block) {
1305          b.cursor = nir_before_instr(instr);
1306 
1307          switch (instr->type) {
1308          case nir_instr_type_deref: {
1309             nir_deref_instr *deref = nir_instr_as_deref(instr);
1310 
1311             if (opt_restrict_deref_modes(deref))
1312                progress = true;
1313 
1314             switch (deref->deref_type) {
1315             case nir_deref_type_ptr_as_array:
1316                if (opt_deref_ptr_as_array(&b, deref))
1317                   progress = true;
1318                break;
1319 
1320             case nir_deref_type_cast:
1321                if (opt_deref_cast(&b, deref))
1322                   progress = true;
1323                break;
1324 
1325             default:
1326                /* Do nothing */
1327                break;
1328             }
1329             break;
1330          }
1331 
1332          case nir_instr_type_intrinsic: {
1333             nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
1334             switch (intrin->intrinsic) {
1335             case nir_intrinsic_load_deref:
1336                if (opt_load_vec_deref(&b, intrin))
1337                   progress = true;
1338                break;
1339 
1340             case nir_intrinsic_store_deref:
1341                if (opt_store_vec_deref(&b, intrin))
1342                   progress = true;
1343                break;
1344 
1345             case nir_intrinsic_deref_mode_is:
1346                if (opt_known_deref_mode_is(&b, intrin))
1347                   progress = true;
1348                break;
1349 
1350             default:
1351                /* Do nothing */
1352                break;
1353             }
1354             break;
1355          }
1356 
1357          default:
1358             /* Do nothing */
1359             break;
1360          }
1361       }
1362    }
1363 
1364    if (progress) {
1365       nir_metadata_preserve(impl, nir_metadata_block_index |
1366                                   nir_metadata_dominance);
1367    } else {
1368       nir_metadata_preserve(impl, nir_metadata_all);
1369    }
1370 
1371    return progress;
1372 }
1373 
1374 bool
nir_opt_deref(nir_shader * shader)1375 nir_opt_deref(nir_shader *shader)
1376 {
1377    bool progress = false;
1378 
1379    nir_foreach_function(func, shader) {
1380       if (func->impl && nir_opt_deref_impl(func->impl))
1381          progress = true;
1382    }
1383 
1384    return progress;
1385 }
1386