xref: /aosp_15_r20/external/mesa3d/src/compiler/nir/nir_search.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2014 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_search.h"
25 #include <inttypes.h>
26 #include "util/half_float.h"
27 #include "nir_builder.h"
28 #include "nir_worklist.h"
29 
30 /* This should be the same as nir_search_max_comm_ops in nir_algebraic.py. */
31 #define NIR_SEARCH_MAX_COMM_OPS 8
32 
33 struct match_state {
34    bool inexact_match;
35    bool has_exact_alu;
36    uint8_t comm_op_direction;
37    unsigned variables_seen;
38 
39    /* Used for running the automaton on newly-constructed instructions. */
40    struct util_dynarray *states;
41    const struct per_op_table *pass_op_table;
42    const nir_algebraic_table *table;
43 
44    nir_alu_src variables[NIR_SEARCH_MAX_VARIABLES];
45    struct hash_table *range_ht;
46 };
47 
48 static bool
49 match_expression(const nir_algebraic_table *table, const nir_search_expression *expr, nir_alu_instr *instr,
50                  unsigned num_components, const uint8_t *swizzle,
51                  struct match_state *state);
52 static bool
53 nir_algebraic_automaton(nir_instr *instr, struct util_dynarray *states,
54                         const struct per_op_table *pass_op_table);
55 
56 static const uint8_t identity_swizzle[NIR_MAX_VEC_COMPONENTS] = {
57    0,
58    1,
59    2,
60    3,
61    4,
62    5,
63    6,
64    7,
65    8,
66    9,
67    10,
68    11,
69    12,
70    13,
71    14,
72    15,
73 };
74 
75 /**
76  * Check if a source produces a value of the given type.
77  *
78  * Used for satisfying 'a@type' constraints.
79  */
80 static bool
src_is_type(nir_src src,nir_alu_type type)81 src_is_type(nir_src src, nir_alu_type type)
82 {
83    assert(type != nir_type_invalid);
84 
85    if (src.ssa->parent_instr->type == nir_instr_type_alu) {
86       nir_alu_instr *src_alu = nir_instr_as_alu(src.ssa->parent_instr);
87       nir_alu_type output_type = nir_op_infos[src_alu->op].output_type;
88 
89       if (type == nir_type_bool) {
90          switch (src_alu->op) {
91          case nir_op_iand:
92          case nir_op_ior:
93          case nir_op_ixor:
94             return src_is_type(src_alu->src[0].src, nir_type_bool) &&
95                    src_is_type(src_alu->src[1].src, nir_type_bool);
96          case nir_op_inot:
97             return src_is_type(src_alu->src[0].src, nir_type_bool);
98          default:
99             break;
100          }
101       }
102 
103       return nir_alu_type_get_base_type(output_type) == type;
104    } else if (src.ssa->parent_instr->type == nir_instr_type_intrinsic) {
105       nir_intrinsic_instr *intr = nir_instr_as_intrinsic(src.ssa->parent_instr);
106 
107       if (type == nir_type_bool) {
108          return intr->intrinsic == nir_intrinsic_load_front_face ||
109                 intr->intrinsic == nir_intrinsic_load_helper_invocation;
110       }
111    }
112 
113    /* don't know */
114    return false;
115 }
116 
117 static bool
nir_op_matches_search_op(nir_op nop,uint16_t sop)118 nir_op_matches_search_op(nir_op nop, uint16_t sop)
119 {
120    if (sop <= nir_last_opcode)
121       return nop == sop;
122 
123 #define MATCH_FCONV_CASE(op)           \
124    case nir_search_op_##op:            \
125       return nop == nir_op_##op##16 || \
126              nop == nir_op_##op##32 || \
127              nop == nir_op_##op##64;
128 
129 #define MATCH_ICONV_CASE(op)           \
130    case nir_search_op_##op:            \
131       return nop == nir_op_##op##8 ||  \
132              nop == nir_op_##op##16 || \
133              nop == nir_op_##op##32 || \
134              nop == nir_op_##op##64;
135 
136    switch (sop) {
137       MATCH_FCONV_CASE(i2f)
138       MATCH_FCONV_CASE(u2f)
139       MATCH_FCONV_CASE(f2f)
140       MATCH_ICONV_CASE(f2u)
141       MATCH_ICONV_CASE(f2i)
142       MATCH_ICONV_CASE(u2u)
143       MATCH_ICONV_CASE(i2i)
144       MATCH_FCONV_CASE(b2f)
145       MATCH_ICONV_CASE(b2i)
146    default:
147       unreachable("Invalid nir_search_op");
148    }
149 
150 #undef MATCH_FCONV_CASE
151 #undef MATCH_ICONV_CASE
152 }
153 
154 uint16_t
nir_search_op_for_nir_op(nir_op nop)155 nir_search_op_for_nir_op(nir_op nop)
156 {
157 #define MATCH_FCONV_CASE(op) \
158    case nir_op_##op##16:     \
159    case nir_op_##op##32:     \
160    case nir_op_##op##64:     \
161       return nir_search_op_##op;
162 
163 #define MATCH_ICONV_CASE(op) \
164    case nir_op_##op##8:      \
165    case nir_op_##op##16:     \
166    case nir_op_##op##32:     \
167    case nir_op_##op##64:     \
168       return nir_search_op_##op;
169 
170    switch (nop) {
171       MATCH_FCONV_CASE(i2f)
172       MATCH_FCONV_CASE(u2f)
173       MATCH_FCONV_CASE(f2f)
174       MATCH_ICONV_CASE(f2u)
175       MATCH_ICONV_CASE(f2i)
176       MATCH_ICONV_CASE(u2u)
177       MATCH_ICONV_CASE(i2i)
178       MATCH_FCONV_CASE(b2f)
179       MATCH_ICONV_CASE(b2i)
180    default:
181       return nop;
182    }
183 
184 #undef MATCH_FCONV_CASE
185 #undef MATCH_ICONV_CASE
186 }
187 
188 static nir_op
nir_op_for_search_op(uint16_t sop,unsigned bit_size)189 nir_op_for_search_op(uint16_t sop, unsigned bit_size)
190 {
191    if (sop <= nir_last_opcode)
192       return sop;
193 
194 #define RET_FCONV_CASE(op)                \
195    case nir_search_op_##op:               \
196       switch (bit_size) {                 \
197       case 16:                            \
198          return nir_op_##op##16;          \
199       case 32:                            \
200          return nir_op_##op##32;          \
201       case 64:                            \
202          return nir_op_##op##64;          \
203       default:                            \
204          unreachable("Invalid bit size"); \
205       }
206 
207 #define RET_ICONV_CASE(op)                \
208    case nir_search_op_##op:               \
209       switch (bit_size) {                 \
210       case 8:                             \
211          return nir_op_##op##8;           \
212       case 16:                            \
213          return nir_op_##op##16;          \
214       case 32:                            \
215          return nir_op_##op##32;          \
216       case 64:                            \
217          return nir_op_##op##64;          \
218       default:                            \
219          unreachable("Invalid bit size"); \
220       }
221 
222    switch (sop) {
223       RET_FCONV_CASE(i2f)
224       RET_FCONV_CASE(u2f)
225       RET_FCONV_CASE(f2f)
226       RET_ICONV_CASE(f2u)
227       RET_ICONV_CASE(f2i)
228       RET_ICONV_CASE(u2u)
229       RET_ICONV_CASE(i2i)
230       RET_FCONV_CASE(b2f)
231       RET_ICONV_CASE(b2i)
232    default:
233       unreachable("Invalid nir_search_op");
234    }
235 
236 #undef RET_FCONV_CASE
237 #undef RET_ICONV_CASE
238 }
239 
240 static bool
match_value(const nir_algebraic_table * table,const nir_search_value * value,nir_alu_instr * instr,unsigned src,unsigned num_components,const uint8_t * swizzle,struct match_state * state)241 match_value(const nir_algebraic_table *table,
242             const nir_search_value *value, nir_alu_instr *instr, unsigned src,
243             unsigned num_components, const uint8_t *swizzle,
244             struct match_state *state)
245 {
246    uint8_t new_swizzle[NIR_MAX_VEC_COMPONENTS];
247 
248    /* If the source is an explicitly sized source, then we need to reset
249     * both the number of components and the swizzle.
250     */
251    if (nir_op_infos[instr->op].input_sizes[src] != 0) {
252       num_components = nir_op_infos[instr->op].input_sizes[src];
253       swizzle = identity_swizzle;
254    }
255 
256    for (unsigned i = 0; i < num_components; ++i)
257       new_swizzle[i] = instr->src[src].swizzle[swizzle[i]];
258 
259    /* If the value has a specific bit size and it doesn't match, bail */
260    if (value->bit_size > 0 &&
261        nir_src_bit_size(instr->src[src].src) != value->bit_size)
262       return false;
263 
264    switch (value->type) {
265    case nir_search_value_expression:
266       if (instr->src[src].src.ssa->parent_instr->type != nir_instr_type_alu)
267          return false;
268 
269       return match_expression(table, nir_search_value_as_expression(value),
270                               nir_instr_as_alu(instr->src[src].src.ssa->parent_instr),
271                               num_components, new_swizzle, state);
272 
273    case nir_search_value_variable: {
274       nir_search_variable *var = nir_search_value_as_variable(value);
275       assert(var->variable < NIR_SEARCH_MAX_VARIABLES);
276 
277       if (state->variables_seen & (1 << var->variable)) {
278          if (state->variables[var->variable].src.ssa != instr->src[src].src.ssa)
279             return false;
280 
281          for (unsigned i = 0; i < num_components; ++i) {
282             if (state->variables[var->variable].swizzle[i] != new_swizzle[i])
283                return false;
284          }
285 
286          return true;
287       } else {
288          if (var->is_constant &&
289              instr->src[src].src.ssa->parent_instr->type != nir_instr_type_load_const)
290             return false;
291 
292          if (var->cond_index != -1 && !table->variable_cond[var->cond_index](state->range_ht, instr,
293                                                                              src, num_components, new_swizzle))
294             return false;
295 
296          if (var->type != nir_type_invalid &&
297              !src_is_type(instr->src[src].src, var->type))
298             return false;
299 
300          state->variables_seen |= (1 << var->variable);
301          state->variables[var->variable].src = instr->src[src].src;
302 
303          for (unsigned i = 0; i < NIR_MAX_VEC_COMPONENTS; ++i) {
304             if (i < num_components)
305                state->variables[var->variable].swizzle[i] = new_swizzle[i];
306             else
307                state->variables[var->variable].swizzle[i] = 0;
308          }
309 
310          return true;
311       }
312    }
313 
314    case nir_search_value_constant: {
315       nir_search_constant *const_val = nir_search_value_as_constant(value);
316 
317       if (!nir_src_is_const(instr->src[src].src))
318          return false;
319 
320       switch (const_val->type) {
321       case nir_type_float: {
322          nir_load_const_instr *const load =
323             nir_instr_as_load_const(instr->src[src].src.ssa->parent_instr);
324 
325          /* There are 8-bit and 1-bit integer types, but there are no 8-bit or
326           * 1-bit float types.  This prevents potential assertion failures in
327           * nir_src_comp_as_float.
328           */
329          if (load->def.bit_size < 16)
330             return false;
331 
332          for (unsigned i = 0; i < num_components; ++i) {
333             double val = nir_src_comp_as_float(instr->src[src].src,
334                                                new_swizzle[i]);
335             if (val != const_val->data.d)
336                return false;
337          }
338          return true;
339       }
340 
341       case nir_type_int:
342       case nir_type_uint:
343       case nir_type_bool: {
344          unsigned bit_size = nir_src_bit_size(instr->src[src].src);
345          uint64_t mask = u_uintN_max(bit_size);
346          for (unsigned i = 0; i < num_components; ++i) {
347             uint64_t val = nir_src_comp_as_uint(instr->src[src].src,
348                                                 new_swizzle[i]);
349             if ((val & mask) != (const_val->data.u & mask))
350                return false;
351          }
352          return true;
353       }
354 
355       default:
356          unreachable("Invalid alu source type");
357       }
358    }
359 
360    default:
361       unreachable("Invalid search value type");
362    }
363 }
364 
365 static bool
match_expression(const nir_algebraic_table * table,const nir_search_expression * expr,nir_alu_instr * instr,unsigned num_components,const uint8_t * swizzle,struct match_state * state)366 match_expression(const nir_algebraic_table *table, const nir_search_expression *expr, nir_alu_instr *instr,
367                  unsigned num_components, const uint8_t *swizzle,
368                  struct match_state *state)
369 {
370    if (expr->cond_index != -1 && !table->expression_cond[expr->cond_index](instr))
371       return false;
372 
373    if (expr->nsz && nir_alu_instr_is_signed_zero_preserve(instr))
374       return false;
375 
376    if (expr->nnan && nir_alu_instr_is_nan_preserve(instr))
377       return false;
378 
379    if (expr->ninf && nir_alu_instr_is_inf_preserve(instr))
380       return false;
381 
382    if (!nir_op_matches_search_op(instr->op, expr->opcode))
383       return false;
384 
385    if (expr->value.bit_size > 0 &&
386        instr->def.bit_size != expr->value.bit_size)
387       return false;
388 
389    state->inexact_match = expr->inexact || state->inexact_match;
390    state->has_exact_alu = (instr->exact && !expr->ignore_exact) || state->has_exact_alu;
391    if (state->inexact_match && state->has_exact_alu)
392       return false;
393 
394    assert(nir_op_infos[instr->op].num_inputs > 0);
395 
396    /* If we have an explicitly sized destination, we can only handle the
397     * identity swizzle.  While dot(vec3(a, b, c).zxy) is a valid
398     * expression, we don't have the information right now to propagate that
399     * swizzle through.  We can only properly propagate swizzles if the
400     * instruction is vectorized.
401     */
402    if (nir_op_infos[instr->op].output_size != 0) {
403       for (unsigned i = 0; i < num_components; i++) {
404          if (swizzle[i] != i)
405             return false;
406       }
407    }
408 
409    /* If this is a commutative expression and it's one of the first few, look
410     * up its direction for the current search operation.  We'll use that value
411     * to possibly flip the sources for the match.
412     */
413    unsigned comm_op_flip =
414       (expr->comm_expr_idx >= 0 &&
415        expr->comm_expr_idx < NIR_SEARCH_MAX_COMM_OPS)
416          ? ((state->comm_op_direction >> expr->comm_expr_idx) & 1)
417          : 0;
418 
419    bool matched = true;
420    for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
421       /* 2src_commutative instructions that have 3 sources are only commutative
422        * in the first two sources.  Source 2 is always source 2.
423        */
424       if (!match_value(table, &state->table->values[expr->srcs[i]].value, instr,
425                        i < 2 ? i ^ comm_op_flip : i,
426                        num_components, swizzle, state)) {
427          matched = false;
428          break;
429       }
430    }
431 
432    return matched;
433 }
434 
435 static unsigned
replace_bitsize(const nir_search_value * value,unsigned search_bitsize,struct match_state * state)436 replace_bitsize(const nir_search_value *value, unsigned search_bitsize,
437                 struct match_state *state)
438 {
439    if (value->bit_size > 0)
440       return value->bit_size;
441    if (value->bit_size < 0)
442       return nir_src_bit_size(state->variables[-value->bit_size - 1].src);
443    return search_bitsize;
444 }
445 
446 static nir_alu_src
construct_value(nir_builder * build,const nir_search_value * value,unsigned num_components,unsigned search_bitsize,struct match_state * state,nir_instr * instr)447 construct_value(nir_builder *build,
448                 const nir_search_value *value,
449                 unsigned num_components, unsigned search_bitsize,
450                 struct match_state *state,
451                 nir_instr *instr)
452 {
453    switch (value->type) {
454    case nir_search_value_expression: {
455       const nir_search_expression *expr = nir_search_value_as_expression(value);
456       unsigned dst_bit_size = replace_bitsize(value, search_bitsize, state);
457       nir_op op = nir_op_for_search_op(expr->opcode, dst_bit_size);
458 
459       if (nir_op_infos[op].output_size != 0)
460          num_components = nir_op_infos[op].output_size;
461 
462       nir_alu_instr *alu = nir_alu_instr_create(build->shader, op);
463       nir_def_init(&alu->instr, &alu->def, num_components,
464                    dst_bit_size);
465 
466       /* We have no way of knowing what values in a given search expression
467        * map to a particular replacement value.  Therefore, if the
468        * expression we are replacing has any exact values, the entire
469        * replacement should be exact.
470        */
471       alu->exact = state->has_exact_alu || expr->exact;
472       alu->fp_fast_math = nir_instr_as_alu(instr)->fp_fast_math;
473 
474       for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) {
475          /* If the source is an explicitly sized source, then we need to reset
476           * the number of components to match.
477           */
478          if (nir_op_infos[alu->op].input_sizes[i] != 0)
479             num_components = nir_op_infos[alu->op].input_sizes[i];
480 
481          alu->src[i] = construct_value(build, &state->table->values[expr->srcs[i]].value,
482                                        num_components, search_bitsize,
483                                        state, instr);
484       }
485 
486       nir_builder_instr_insert(build, &alu->instr);
487 
488       assert(alu->def.index ==
489              util_dynarray_num_elements(state->states, uint16_t));
490       util_dynarray_append(state->states, uint16_t, 0);
491       nir_algebraic_automaton(&alu->instr, state->states, state->pass_op_table);
492 
493       nir_alu_src val;
494       val.src = nir_src_for_ssa(&alu->def);
495       memcpy(val.swizzle, identity_swizzle, sizeof val.swizzle);
496 
497       return val;
498    }
499 
500    case nir_search_value_variable: {
501       const nir_search_variable *var = nir_search_value_as_variable(value);
502       assert(state->variables_seen & (1 << var->variable));
503 
504       nir_alu_src val = { NIR_SRC_INIT };
505       nir_alu_src_copy(&val, &state->variables[var->variable]);
506       assert(!var->is_constant);
507 
508       for (unsigned i = 0; i < NIR_MAX_VEC_COMPONENTS; i++)
509          val.swizzle[i] = state->variables[var->variable].swizzle[var->swizzle[i]];
510 
511       return val;
512    }
513 
514    case nir_search_value_constant: {
515       const nir_search_constant *c = nir_search_value_as_constant(value);
516       unsigned bit_size = replace_bitsize(value, search_bitsize, state);
517 
518       nir_def *cval;
519       switch (c->type) {
520       case nir_type_float:
521          cval = nir_imm_floatN_t(build, c->data.d, bit_size);
522          break;
523 
524       case nir_type_int:
525       case nir_type_uint:
526          cval = nir_imm_intN_t(build, c->data.i, bit_size);
527          break;
528 
529       case nir_type_bool:
530          cval = nir_imm_boolN_t(build, c->data.u, bit_size);
531          break;
532 
533       default:
534          unreachable("Invalid alu source type");
535       }
536 
537       assert(cval->index ==
538              util_dynarray_num_elements(state->states, uint16_t));
539       util_dynarray_append(state->states, uint16_t, 0);
540       nir_algebraic_automaton(cval->parent_instr, state->states,
541                               state->pass_op_table);
542 
543       nir_alu_src val;
544       val.src = nir_src_for_ssa(cval);
545       memset(val.swizzle, 0, sizeof val.swizzle);
546 
547       return val;
548    }
549 
550    default:
551       unreachable("Invalid search value type");
552    }
553 }
554 
555 UNUSED static void
dump_value(const nir_algebraic_table * table,const nir_search_value * val)556 dump_value(const nir_algebraic_table *table, const nir_search_value *val)
557 {
558    switch (val->type) {
559    case nir_search_value_constant: {
560       const nir_search_constant *sconst = nir_search_value_as_constant(val);
561       switch (sconst->type) {
562       case nir_type_float:
563          fprintf(stderr, "%f", sconst->data.d);
564          break;
565       case nir_type_int:
566          fprintf(stderr, "%" PRId64, sconst->data.i);
567          break;
568       case nir_type_uint:
569          fprintf(stderr, "0x%" PRIx64, sconst->data.u);
570          break;
571       case nir_type_bool:
572          fprintf(stderr, "%s", sconst->data.u != 0 ? "True" : "False");
573          break;
574       default:
575          unreachable("bad const type");
576       }
577       break;
578    }
579 
580    case nir_search_value_variable: {
581       const nir_search_variable *var = nir_search_value_as_variable(val);
582       if (var->is_constant)
583          fprintf(stderr, "#");
584       fprintf(stderr, "%c", var->variable + 'a');
585       break;
586    }
587 
588    case nir_search_value_expression: {
589       const nir_search_expression *expr = nir_search_value_as_expression(val);
590       fprintf(stderr, "(");
591       if (expr->inexact)
592          fprintf(stderr, "~");
593       switch (expr->opcode) {
594 #define CASE(n)            \
595    case nir_search_op_##n: \
596       fprintf(stderr, #n); \
597       break;
598          CASE(b2f)
599          CASE(b2i)
600          CASE(i2i)
601          CASE(f2i)
602          CASE(i2f)
603 #undef CASE
604       default:
605          fprintf(stderr, "%s", nir_op_infos[expr->opcode].name);
606       }
607 
608       unsigned num_srcs = 1;
609       if (expr->opcode <= nir_last_opcode)
610          num_srcs = nir_op_infos[expr->opcode].num_inputs;
611 
612       for (unsigned i = 0; i < num_srcs; i++) {
613          fprintf(stderr, " ");
614          dump_value(table, &table->values[expr->srcs[i]].value);
615       }
616 
617       fprintf(stderr, ")");
618       break;
619    }
620    }
621 
622    if (val->bit_size > 0)
623       fprintf(stderr, "@%d", val->bit_size);
624 }
625 
626 static void
add_uses_to_worklist(nir_instr * instr,nir_instr_worklist * worklist,struct util_dynarray * states,const struct per_op_table * pass_op_table)627 add_uses_to_worklist(nir_instr *instr,
628                      nir_instr_worklist *worklist,
629                      struct util_dynarray *states,
630                      const struct per_op_table *pass_op_table)
631 {
632    nir_def *def = nir_instr_def(instr);
633 
634    nir_foreach_use_safe(use_src, def) {
635       if (nir_algebraic_automaton(nir_src_parent_instr(use_src), states, pass_op_table))
636          nir_instr_worklist_push_tail(worklist, nir_src_parent_instr(use_src));
637    }
638 }
639 
640 static void
nir_algebraic_update_automaton(nir_instr * new_instr,nir_instr_worklist * algebraic_worklist,struct util_dynarray * states,const struct per_op_table * pass_op_table)641 nir_algebraic_update_automaton(nir_instr *new_instr,
642                                nir_instr_worklist *algebraic_worklist,
643                                struct util_dynarray *states,
644                                const struct per_op_table *pass_op_table)
645 {
646 
647    nir_instr_worklist *automaton_worklist = nir_instr_worklist_create();
648 
649    /* Walk through the tree of uses of our new instruction's SSA value,
650     * recursively updating the automaton state until it stabilizes.
651     */
652    add_uses_to_worklist(new_instr, automaton_worklist, states, pass_op_table);
653 
654    nir_instr *instr;
655    while ((instr = nir_instr_worklist_pop_head(automaton_worklist))) {
656       nir_instr_worklist_push_tail(algebraic_worklist, instr);
657       add_uses_to_worklist(instr, automaton_worklist, states, pass_op_table);
658    }
659 
660    nir_instr_worklist_destroy(automaton_worklist);
661 }
662 
663 static nir_def *
nir_replace_instr(nir_builder * build,nir_alu_instr * instr,struct hash_table * range_ht,struct util_dynarray * states,const nir_algebraic_table * table,const nir_search_expression * search,const nir_search_value * replace,nir_instr_worklist * algebraic_worklist,struct exec_list * dead_instrs)664 nir_replace_instr(nir_builder *build, nir_alu_instr *instr,
665                   struct hash_table *range_ht,
666                   struct util_dynarray *states,
667                   const nir_algebraic_table *table,
668                   const nir_search_expression *search,
669                   const nir_search_value *replace,
670                   nir_instr_worklist *algebraic_worklist,
671                   struct exec_list *dead_instrs)
672 {
673    uint8_t swizzle[NIR_MAX_VEC_COMPONENTS] = { 0 };
674 
675    for (unsigned i = 0; i < instr->def.num_components; ++i)
676       swizzle[i] = i;
677 
678    struct match_state state;
679    state.inexact_match = false;
680    state.has_exact_alu = false;
681    state.range_ht = range_ht;
682    state.pass_op_table = table->pass_op_table;
683    state.table = table;
684 
685    STATIC_ASSERT(sizeof(state.comm_op_direction) * 8 >= NIR_SEARCH_MAX_COMM_OPS);
686 
687    unsigned comm_expr_combinations =
688       1 << MIN2(search->comm_exprs, NIR_SEARCH_MAX_COMM_OPS);
689 
690    bool found = false;
691    for (unsigned comb = 0; comb < comm_expr_combinations; comb++) {
692       /* The bitfield of directions is just the current iteration.  Hooray for
693        * binary.
694        */
695       state.comm_op_direction = comb;
696       state.variables_seen = 0;
697 
698       if (match_expression(table, search, instr,
699                            instr->def.num_components,
700                            swizzle, &state)) {
701          found = true;
702          break;
703       }
704    }
705    if (!found)
706       return NULL;
707 
708 #if 0
709    fprintf(stderr, "matched: ");
710    dump_value(table, &search->value);
711    fprintf(stderr, " -> ");
712    dump_value(table, replace);
713    fprintf(stderr, " ssa_%d\n", instr->def.index);
714 #endif
715 
716    /* If the instruction at the root of the expression tree being replaced is
717     * a unary operation, insert the replacement instructions at the location
718     * of the source of the unary operation.  Otherwise, insert the replacement
719     * instructions at the location of the expression tree root.
720     *
721     * For the unary operation case, this is done to prevent some spurious code
722     * motion that can dramatically extend live ranges.  Imagine an expression
723     * like -(A+B) where the addtion and the negation are separated by flow
724     * control and thousands of instructions.  If this expression is replaced
725     * with -A+-B, inserting the new instructions at the site of the negation
726     * could extend the live range of A and B dramtically.  This could increase
727     * register pressure and cause spilling.
728     *
729     * It may well be that moving instructions around is a good thing, but
730     * keeping algebraic optimizations and code motion optimizations separate
731     * seems safest.
732     */
733    nir_alu_instr *const src_instr = nir_src_as_alu_instr(instr->src[0].src);
734    if (src_instr != NULL &&
735        (instr->op == nir_op_fneg || instr->op == nir_op_fabs ||
736         instr->op == nir_op_ineg || instr->op == nir_op_iabs ||
737         instr->op == nir_op_inot)) {
738       /* Insert new instructions *after*.  Otherwise a hypothetical
739        * replacement fneg(X) -> fabs(X) would insert the fabs() instruction
740        * before X!  This can also occur for things like fneg(X.wzyx) -> X.wzyx
741        * in vector mode.  A move instruction to handle the swizzle will get
742        * inserted before X.
743        *
744        * This manifested in a single OpenGL ES 2.0 CTS vertex shader test on
745        * older Intel GPU that use vector-mode vertex processing.
746        */
747       build->cursor = nir_after_instr(&src_instr->instr);
748    } else {
749       build->cursor = nir_before_instr(&instr->instr);
750    }
751 
752    state.states = states;
753 
754    nir_alu_src val = construct_value(build, replace,
755                                      instr->def.num_components,
756                                      instr->def.bit_size,
757                                      &state, &instr->instr);
758 
759    /* Note that NIR builder will elide the MOV if it's a no-op, which may
760     * allow more work to be done in a single pass through algebraic.
761     */
762    nir_def *ssa_val =
763       nir_mov_alu(build, val, instr->def.num_components);
764    if (ssa_val->index == util_dynarray_num_elements(states, uint16_t)) {
765       util_dynarray_append(states, uint16_t, 0);
766       nir_algebraic_automaton(ssa_val->parent_instr, states, table->pass_op_table);
767    }
768 
769    /* Rewrite the uses of the old SSA value to the new one, and recurse
770     * through the uses updating the automaton's state.
771     */
772    nir_def_rewrite_uses(&instr->def, ssa_val);
773    nir_algebraic_update_automaton(ssa_val->parent_instr, algebraic_worklist,
774                                   states, table->pass_op_table);
775 
776    /* Nothing uses the instr any more, so drop it out of the program.  Note
777     * that the instr may be in the worklist still, so we can't free it
778     * directly.
779     */
780    assert(instr->instr.pass_flags == 0);
781    instr->instr.pass_flags = 1;
782    nir_instr_remove(&instr->instr);
783    exec_list_push_tail(dead_instrs, &instr->instr.node);
784 
785    return ssa_val;
786 }
787 
788 static bool
nir_algebraic_automaton(nir_instr * instr,struct util_dynarray * states,const struct per_op_table * pass_op_table)789 nir_algebraic_automaton(nir_instr *instr, struct util_dynarray *states,
790                         const struct per_op_table *pass_op_table)
791 {
792    switch (instr->type) {
793    case nir_instr_type_alu: {
794       nir_alu_instr *alu = nir_instr_as_alu(instr);
795       nir_op op = alu->op;
796       uint16_t search_op = nir_search_op_for_nir_op(op);
797       const struct per_op_table *tbl = &pass_op_table[search_op];
798       if (tbl->num_filtered_states == 0)
799          return false;
800 
801       /* Calculate the index into the transition table. Note the index
802        * calculated must match the iteration order of Python's
803        * itertools.product(), which was used to emit the transition
804        * table.
805        */
806       unsigned index = 0;
807       for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++) {
808          index *= tbl->num_filtered_states;
809          if (tbl->filter)
810             index += tbl->filter[*util_dynarray_element(states, uint16_t,
811                                                         alu->src[i].src.ssa->index)];
812       }
813 
814       uint16_t *state = util_dynarray_element(states, uint16_t,
815                                               alu->def.index);
816       if (*state != tbl->table[index]) {
817          *state = tbl->table[index];
818          return true;
819       }
820       return false;
821    }
822 
823    case nir_instr_type_load_const: {
824       nir_load_const_instr *load_const = nir_instr_as_load_const(instr);
825       uint16_t *state = util_dynarray_element(states, uint16_t,
826                                               load_const->def.index);
827       if (*state != CONST_STATE) {
828          *state = CONST_STATE;
829          return true;
830       }
831       return false;
832    }
833 
834    default:
835       return false;
836    }
837 }
838 
839 static bool
nir_algebraic_instr(nir_builder * build,nir_instr * instr,struct hash_table * range_ht,const bool * condition_flags,const nir_algebraic_table * table,struct util_dynarray * states,nir_instr_worklist * worklist,struct exec_list * dead_instrs)840 nir_algebraic_instr(nir_builder *build, nir_instr *instr,
841                     struct hash_table *range_ht,
842                     const bool *condition_flags,
843                     const nir_algebraic_table *table,
844                     struct util_dynarray *states,
845                     nir_instr_worklist *worklist,
846                     struct exec_list *dead_instrs)
847 {
848 
849    if (instr->type != nir_instr_type_alu)
850       return false;
851 
852    nir_alu_instr *alu = nir_instr_as_alu(instr);
853 
854    unsigned bit_size = alu->def.bit_size;
855    const unsigned execution_mode =
856       build->shader->info.float_controls_execution_mode;
857    const bool ignore_inexact =
858       nir_alu_instr_is_signed_zero_inf_nan_preserve(alu) ||
859       nir_is_denorm_flush_to_zero(execution_mode, bit_size);
860 
861    int xform_idx = *util_dynarray_element(states, uint16_t,
862                                           alu->def.index);
863    for (const struct transform *xform = &table->transforms[table->transform_offsets[xform_idx]];
864         xform->condition_offset != ~0;
865         xform++) {
866       if (condition_flags[xform->condition_offset] &&
867           !(table->values[xform->search].expression.inexact && ignore_inexact) &&
868           nir_replace_instr(build, alu, range_ht, states, table,
869                             &table->values[xform->search].expression,
870                             &table->values[xform->replace].value, worklist, dead_instrs)) {
871          _mesa_hash_table_clear(range_ht, NULL);
872          return true;
873       }
874    }
875 
876    return false;
877 }
878 
879 bool
nir_algebraic_impl(nir_function_impl * impl,const bool * condition_flags,const nir_algebraic_table * table)880 nir_algebraic_impl(nir_function_impl *impl,
881                    const bool *condition_flags,
882                    const nir_algebraic_table *table)
883 {
884    bool progress = false;
885 
886    nir_builder build = nir_builder_create(impl);
887 
888    /* Note: it's important here that we're allocating a zeroed array, since
889     * state 0 is the default state, which means we don't have to visit
890     * anything other than constants and ALU instructions.
891     */
892    struct util_dynarray states = { 0 };
893    if (!util_dynarray_resize(&states, uint16_t, impl->ssa_alloc)) {
894       nir_metadata_preserve(impl, nir_metadata_all);
895       return false;
896    }
897    memset(states.data, 0, states.size);
898 
899    struct hash_table *range_ht = _mesa_pointer_hash_table_create(NULL);
900 
901    nir_instr_worklist *worklist = nir_instr_worklist_create();
902 
903    /* Walk top-to-bottom setting up the automaton state. */
904    nir_foreach_block(block, impl) {
905       nir_foreach_instr(instr, block) {
906          nir_algebraic_automaton(instr, &states, table->pass_op_table);
907       }
908    }
909 
910    /* Put our instrs in the worklist such that we're popping the last instr
911     * first.  This will encourage us to match the biggest source patterns when
912     * possible.
913     */
914    nir_foreach_block_reverse(block, impl) {
915       nir_foreach_instr_reverse(instr, block) {
916          instr->pass_flags = 0;
917          if (instr->type == nir_instr_type_alu)
918             nir_instr_worklist_push_tail(worklist, instr);
919       }
920    }
921 
922    struct exec_list dead_instrs;
923    exec_list_make_empty(&dead_instrs);
924 
925    nir_instr *instr;
926    while ((instr = nir_instr_worklist_pop_head(worklist))) {
927       /* The worklist can have an instr pushed to it multiple times if it was
928        * the src of multiple instrs that also got optimized, so make sure that
929        * we don't try to re-optimize an instr we already handled.
930        */
931       if (instr->pass_flags)
932          continue;
933 
934       progress |= nir_algebraic_instr(&build, instr,
935                                       range_ht, condition_flags,
936                                       table, &states, worklist, &dead_instrs);
937    }
938 
939    nir_instr_free_list(&dead_instrs);
940 
941    nir_instr_worklist_destroy(worklist);
942    ralloc_free(range_ht);
943    util_dynarray_fini(&states);
944 
945    if (progress) {
946       nir_metadata_preserve(impl, nir_metadata_control_flow);
947    } else {
948       nir_metadata_preserve(impl, nir_metadata_all);
949    }
950 
951    return progress;
952 }
953