xref: /aosp_15_r20/external/mesa3d/src/compiler/nir/nir_opt_peephole_select.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/nir_builder.h"
25 #include "nir.h"
26 #include "nir_builder.h"
27 #include "nir_control_flow.h"
28 #include "nir_search_helpers.h"
29 
30 /*
31  * Implements a small peephole optimization that looks for
32  *
33  * if (cond) {
34  *    <then SSA defs>
35  * } else {
36  *    <else SSA defs>
37  * }
38  * phi
39  * ...
40  * phi
41  *
42  * and replaces it with:
43  *
44  * <then SSA defs>
45  * <else SSA defs>
46  * bcsel
47  * ...
48  * bcsel
49  *
50  * where the SSA defs are ALU operations or other cheap instructions (not
51  * texturing, for example).
52  *
53  * If the number of ALU operations in the branches is greater than the limit
54  * parameter, then the optimization is skipped.  In limit=0 mode, the SSA defs
55  * must only be MOVs which we expect to get copy-propagated away once they're
56  * out of the inner blocks.
57  */
58 
59 static bool
block_check_for_allowed_instrs(nir_block * block,unsigned * count,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)60 block_check_for_allowed_instrs(nir_block *block, unsigned *count,
61                                unsigned limit, bool indirect_load_ok,
62                                bool expensive_alu_ok)
63 {
64    bool alu_ok = limit != 0;
65 
66    /* Used on non-control-flow HW to flatten all IFs. */
67    if (limit == ~0) {
68       nir_foreach_instr(instr, block) {
69          switch (instr->type) {
70          case nir_instr_type_alu:
71          case nir_instr_type_deref:
72          case nir_instr_type_load_const:
73          case nir_instr_type_phi:
74          case nir_instr_type_undef:
75          case nir_instr_type_tex:
76          case nir_instr_type_debug_info:
77             break;
78 
79          case nir_instr_type_intrinsic: {
80             nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
81             switch (intr->intrinsic) {
82             case nir_intrinsic_terminate:
83             case nir_intrinsic_terminate_if:
84                /* For non-CF hardware, we need to be able to move discards up
85                 * and flatten, so let them pass.
86                 */
87                continue;
88             default:
89                if (!nir_intrinsic_can_reorder(intr))
90                   return false;
91             }
92             break;
93          }
94 
95          case nir_instr_type_call:
96          case nir_instr_type_jump:
97          case nir_instr_type_parallel_copy:
98             return false;
99          }
100       }
101       return true;
102    }
103 
104    nir_foreach_instr(instr, block) {
105       switch (instr->type) {
106       case nir_instr_type_intrinsic: {
107          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
108 
109          switch (intrin->intrinsic) {
110          case nir_intrinsic_load_deref: {
111             nir_deref_instr *const deref = nir_src_as_deref(intrin->src[0]);
112 
113             switch (deref->modes) {
114             case nir_var_shader_in:
115             case nir_var_uniform:
116             case nir_var_image:
117                /* Don't try to remove flow control around an indirect load
118                 * because that flow control may be trying to avoid invalid
119                 * loads.
120                 */
121                if (!indirect_load_ok && nir_deref_instr_has_indirect(deref))
122                   return false;
123 
124                break;
125 
126             default:
127                return false;
128             }
129             break;
130          }
131 
132          case nir_intrinsic_load_ubo:
133          case nir_intrinsic_load_ubo_vec4:
134             if (!indirect_load_ok && !nir_src_is_const(intrin->src[1]))
135                return false;
136             if (!(nir_intrinsic_access(intrin) & ACCESS_CAN_SPECULATE))
137                return false;
138             break;
139 
140          case nir_intrinsic_load_global_constant:
141          case nir_intrinsic_load_constant_agx:
142             if (!indirect_load_ok && !nir_src_is_const(intrin->src[0]))
143                return false;
144             if (!(nir_intrinsic_access(intrin) & ACCESS_CAN_SPECULATE))
145                return false;
146             break;
147 
148          case nir_intrinsic_masked_swizzle_amd:
149          case nir_intrinsic_quad_swizzle_amd:
150             if (!nir_intrinsic_fetch_inactive(intrin))
151                return false;
152             FALLTHROUGH;
153          case nir_intrinsic_load_uniform:
154          case nir_intrinsic_load_preamble:
155          case nir_intrinsic_load_helper_invocation:
156          case nir_intrinsic_is_helper_invocation:
157          case nir_intrinsic_load_front_face:
158          case nir_intrinsic_load_view_index:
159          case nir_intrinsic_load_layer_id:
160          case nir_intrinsic_load_frag_coord:
161          case nir_intrinsic_load_sample_pos:
162          case nir_intrinsic_load_sample_pos_or_center:
163          case nir_intrinsic_load_sample_id:
164          case nir_intrinsic_load_sample_mask_in:
165          case nir_intrinsic_load_vertex_id_zero_base:
166          case nir_intrinsic_load_first_vertex:
167          case nir_intrinsic_load_base_instance:
168          case nir_intrinsic_load_instance_id:
169          case nir_intrinsic_load_draw_id:
170          case nir_intrinsic_load_num_workgroups:
171          case nir_intrinsic_load_workgroup_id:
172          case nir_intrinsic_load_local_invocation_id:
173          case nir_intrinsic_load_local_invocation_index:
174          case nir_intrinsic_load_subgroup_id:
175          case nir_intrinsic_load_subgroup_invocation:
176          case nir_intrinsic_load_num_subgroups:
177          case nir_intrinsic_load_frag_shading_rate:
178          case nir_intrinsic_is_sparse_texels_resident:
179          case nir_intrinsic_sparse_residency_code_and:
180          case nir_intrinsic_read_invocation:
181          case nir_intrinsic_quad_broadcast:
182          case nir_intrinsic_quad_swap_horizontal:
183          case nir_intrinsic_quad_swap_vertical:
184          case nir_intrinsic_quad_swap_diagonal:
185          case nir_intrinsic_lane_permute_16_amd:
186          case nir_intrinsic_ddx:
187          case nir_intrinsic_ddx_fine:
188          case nir_intrinsic_ddx_coarse:
189          case nir_intrinsic_ddy:
190          case nir_intrinsic_ddy_fine:
191          case nir_intrinsic_ddy_coarse:
192          case nir_intrinsic_load_const_ir3:
193             if (!alu_ok)
194                return false;
195             break;
196 
197          default:
198             return false;
199          }
200 
201          break;
202       }
203 
204       case nir_instr_type_deref:
205       case nir_instr_type_load_const:
206       case nir_instr_type_undef:
207          break;
208 
209       case nir_instr_type_alu: {
210          nir_alu_instr *mov = nir_instr_as_alu(instr);
211          bool movelike = false;
212 
213          switch (mov->op) {
214          case nir_op_mov:
215          case nir_op_fneg:
216          case nir_op_ineg:
217          case nir_op_fabs:
218          case nir_op_iabs:
219          case nir_op_vec2:
220          case nir_op_vec3:
221          case nir_op_vec4:
222          case nir_op_vec5:
223          case nir_op_vec8:
224          case nir_op_vec16:
225             movelike = true;
226             break;
227 
228          case nir_op_fcos:
229          case nir_op_fdiv:
230          case nir_op_fexp2:
231          case nir_op_flog2:
232          case nir_op_fmod:
233          case nir_op_fpow:
234          case nir_op_frcp:
235          case nir_op_frem:
236          case nir_op_frsq:
237          case nir_op_fsin:
238          case nir_op_idiv:
239          case nir_op_irem:
240          case nir_op_udiv:
241             if (!alu_ok || !expensive_alu_ok)
242                return false;
243 
244             break;
245 
246          default:
247             if (!alu_ok) {
248                /* It must be a move-like operation. */
249                return false;
250             }
251             break;
252          }
253 
254          if (alu_ok) {
255             /* If the ALU operation is an fsat or a move-like operation, do
256              * not count it.  The expectation is that it will eventually be
257              * merged as a destination modifier or source modifier on some
258              * other instruction.
259              */
260             if (mov->op != nir_op_fsat && !movelike)
261                (*count)++;
262          } else {
263             /* The only uses of this definition must be phis in the successor */
264             nir_foreach_use_including_if(use, &mov->def) {
265                if (nir_src_is_if(use) ||
266                    nir_src_parent_instr(use)->type != nir_instr_type_phi ||
267                    nir_src_parent_instr(use)->block != block->successors[0])
268                   return false;
269             }
270          }
271          break;
272       }
273 
274       case nir_instr_type_debug_info:
275          break;
276 
277       default:
278          return false;
279       }
280    }
281 
282    return true;
283 }
284 
285 /**
286  * Try to collapse nested ifs:
287  * This optimization turns
288  *
289  * if (cond1) {
290  *   <allowed instruction>
291  *   if (cond2) {
292  *     <any code>
293  *   } else {
294  *   }
295  * } else {
296  * }
297  *
298  * into
299  *
300  * <allowed instruction>
301  * if (cond1 && cond2) {
302  *   <any code>
303  * } else {
304  * }
305  *
306  */
307 static bool
nir_opt_collapse_if(nir_if * if_stmt,nir_shader * shader,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)308 nir_opt_collapse_if(nir_if *if_stmt, nir_shader *shader, unsigned limit,
309                     bool indirect_load_ok, bool expensive_alu_ok)
310 {
311    /* the if has to be nested */
312    if (if_stmt->cf_node.parent->type != nir_cf_node_if)
313       return false;
314 
315    nir_if *parent_if = nir_cf_node_as_if(if_stmt->cf_node.parent);
316    if (parent_if->control == nir_selection_control_dont_flatten)
317       return false;
318 
319    /* check if the else block is empty */
320    if (!nir_cf_list_is_empty_block(&if_stmt->else_list))
321       return false;
322 
323    /* this opt doesn't make much sense if the branch is empty */
324    if (nir_cf_list_is_empty_block(&if_stmt->then_list))
325       return false;
326 
327    /* the nested if has to be the only cf_node:
328     * i.e. <block> <if_stmt> <block> */
329    if (exec_list_length(&parent_if->then_list) != 3)
330       return false;
331 
332    /* check if the else block of the parent if is empty */
333    if (!nir_cf_list_is_empty_block(&parent_if->else_list))
334       return false;
335 
336    /* check if the block after the nested if is empty except for phis */
337    nir_block *last = nir_if_last_then_block(parent_if);
338    nir_instr *last_instr = nir_block_last_instr(last);
339    if (last_instr && last_instr->type != nir_instr_type_phi)
340       return false;
341 
342    /* check if all outer phis become trivial after merging the ifs */
343    nir_foreach_instr(instr, last) {
344       if (parent_if->control == nir_selection_control_flatten)
345          break;
346 
347       nir_phi_instr *phi = nir_instr_as_phi(instr);
348       nir_phi_src *else_src =
349          nir_phi_get_src_from_block(phi, nir_if_first_else_block(if_stmt));
350 
351       nir_foreach_use(src, &phi->def) {
352          assert(nir_src_parent_instr(src)->type == nir_instr_type_phi);
353          nir_phi_src *phi_src =
354             nir_phi_get_src_from_block(nir_instr_as_phi(nir_src_parent_instr(src)),
355                                        nir_if_first_else_block(parent_if));
356          if (phi_src->src.ssa != else_src->src.ssa)
357             return false;
358       }
359    }
360 
361    if (parent_if->control == nir_selection_control_flatten) {
362       /* Override driver defaults */
363       indirect_load_ok = true;
364       expensive_alu_ok = true;
365    }
366 
367    /* check if the block before the nested if matches the requirements */
368    nir_block *first = nir_if_first_then_block(parent_if);
369    unsigned count = 0;
370    if (!block_check_for_allowed_instrs(first, &count, limit != 0,
371                                        indirect_load_ok, expensive_alu_ok))
372       return false;
373 
374    if (count > limit && parent_if->control != nir_selection_control_flatten)
375       return false;
376 
377    /* trivialize succeeding phis */
378    nir_foreach_instr(instr, last) {
379       nir_phi_instr *phi = nir_instr_as_phi(instr);
380       nir_phi_src *else_src =
381          nir_phi_get_src_from_block(phi, nir_if_first_else_block(if_stmt));
382       nir_foreach_use_safe(src, &phi->def) {
383          nir_phi_src *phi_src =
384             nir_phi_get_src_from_block(nir_instr_as_phi(nir_src_parent_instr(src)),
385                                        nir_if_first_else_block(parent_if));
386          if (phi_src->src.ssa == else_src->src.ssa)
387             nir_src_rewrite(&phi_src->src, &phi->def);
388       }
389    }
390 
391    /* combine the conditions */
392    struct nir_builder b = nir_builder_at(nir_before_cf_node(&if_stmt->cf_node));
393    nir_def *cond = nir_iand(&b, if_stmt->condition.ssa,
394                             parent_if->condition.ssa);
395    nir_src_rewrite(&if_stmt->condition, cond);
396 
397    /* move the whole inner if before the parent if */
398    nir_cf_list tmp;
399    nir_cf_extract(&tmp, nir_before_block(first),
400                   nir_after_block(last));
401    nir_cf_reinsert(&tmp, nir_before_cf_node(&parent_if->cf_node));
402 
403    /* The now empty parent if will be cleaned up by other passes */
404    return true;
405 }
406 
407 /* If we're moving discards out of the if for non-CF hardware, we need to add
408  * the if's condition to it
409  */
410 static void
rewrite_discard_conds(nir_instr * instr,nir_def * if_cond,bool is_else)411 rewrite_discard_conds(nir_instr *instr, nir_def *if_cond, bool is_else)
412 {
413    if (instr->type != nir_instr_type_intrinsic)
414       return;
415    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
416 
417    if (intr->intrinsic != nir_intrinsic_terminate_if && intr->intrinsic != nir_intrinsic_terminate)
418       return;
419 
420    nir_builder b = nir_builder_at(nir_before_instr(instr));
421 
422    if (is_else)
423       if_cond = nir_inot(&b, if_cond);
424 
425    if (intr->intrinsic == nir_intrinsic_terminate_if) {
426       nir_src_rewrite(&intr->src[0], nir_iand(&b, intr->src[0].ssa, if_cond));
427    } else {
428       nir_discard_if(&b, if_cond);
429       nir_instr_remove(instr);
430    }
431 }
432 
433 static bool
nir_opt_peephole_select_block(nir_block * block,nir_shader * shader,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)434 nir_opt_peephole_select_block(nir_block *block, nir_shader *shader,
435                               unsigned limit, bool indirect_load_ok,
436                               bool expensive_alu_ok)
437 {
438    if (nir_cf_node_is_first(&block->cf_node))
439       return false;
440 
441    nir_cf_node *prev_node = nir_cf_node_prev(&block->cf_node);
442    if (prev_node->type != nir_cf_node_if)
443       return false;
444 
445    nir_block *prev_block = nir_cf_node_as_block(nir_cf_node_prev(prev_node));
446 
447    /* If the last instruction before this if/else block is a jump, we can't
448     * append stuff after it because it would break a bunch of assumption about
449     * control flow (nir_validate expects the successor of a return/halt jump
450     * to be the end of the function, which might not match the successor of
451     * the if/else blocks).
452     */
453    if (nir_block_ends_in_return_or_halt(prev_block))
454       return false;
455 
456    nir_if *if_stmt = nir_cf_node_as_if(prev_node);
457 
458    /* first, try to collapse the if */
459    if (nir_opt_collapse_if(if_stmt, shader, limit,
460                            indirect_load_ok, expensive_alu_ok))
461       return true;
462 
463    if (if_stmt->control == nir_selection_control_dont_flatten)
464       return false;
465 
466    nir_block *then_block = nir_if_first_then_block(if_stmt);
467    nir_block *else_block = nir_if_first_else_block(if_stmt);
468 
469    /* We can only have one block in each side ... */
470    if (nir_if_last_then_block(if_stmt) != then_block ||
471        nir_if_last_else_block(if_stmt) != else_block)
472       return false;
473 
474    if (if_stmt->control == nir_selection_control_flatten) {
475       /* Override driver defaults */
476       indirect_load_ok = true;
477       expensive_alu_ok = true;
478    }
479 
480    /* ... and those blocks must only contain "allowed" instructions. */
481    unsigned count = 0;
482    if (!block_check_for_allowed_instrs(then_block, &count, limit,
483                                        indirect_load_ok, expensive_alu_ok) ||
484        !block_check_for_allowed_instrs(else_block, &count, limit,
485                                        indirect_load_ok, expensive_alu_ok))
486       return false;
487 
488    if (count > limit && if_stmt->control != nir_selection_control_flatten)
489       return false;
490 
491    /* At this point, we know that the previous CFG node is an if-then
492     * statement containing only moves to phi nodes in this block.  We can
493     * just remove that entire CF node and replace all of the phi nodes with
494     * selects.
495     */
496 
497    /* First, we move the remaining instructions from the blocks to the
498     * block before.  We have already guaranteed that this is safe by
499     * calling block_check_for_allowed_instrs()
500     */
501    nir_foreach_instr_safe(instr, then_block) {
502       exec_node_remove(&instr->node);
503       instr->block = prev_block;
504       exec_list_push_tail(&prev_block->instr_list, &instr->node);
505       rewrite_discard_conds(instr, if_stmt->condition.ssa, false);
506    }
507 
508    nir_foreach_instr_safe(instr, else_block) {
509       exec_node_remove(&instr->node);
510       instr->block = prev_block;
511       exec_list_push_tail(&prev_block->instr_list, &instr->node);
512       rewrite_discard_conds(instr, if_stmt->condition.ssa, true);
513    }
514 
515    nir_foreach_phi_safe(phi, block) {
516       nir_alu_instr *sel = nir_alu_instr_create(shader, nir_op_bcsel);
517       sel->src[0].src = nir_src_for_ssa(if_stmt->condition.ssa);
518       /* Splat the condition to all channels */
519       memset(sel->src[0].swizzle, 0, sizeof sel->src[0].swizzle);
520 
521       assert(exec_list_length(&phi->srcs) == 2);
522       nir_foreach_phi_src(src, phi) {
523          assert(src->pred == then_block || src->pred == else_block);
524 
525          unsigned idx = src->pred == then_block ? 1 : 2;
526          sel->src[idx].src = nir_src_for_ssa(src->src.ssa);
527       }
528 
529       nir_def_init(&sel->instr, &sel->def,
530                    phi->def.num_components, phi->def.bit_size);
531 
532       nir_def_rewrite_uses(&phi->def,
533                            &sel->def);
534 
535       nir_instr_insert_before(&phi->instr, &sel->instr);
536       nir_instr_remove(&phi->instr);
537    }
538 
539    nir_cf_node_remove(&if_stmt->cf_node);
540    return true;
541 }
542 
543 static bool
nir_opt_peephole_select_impl(nir_function_impl * impl,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)544 nir_opt_peephole_select_impl(nir_function_impl *impl, unsigned limit,
545                              bool indirect_load_ok, bool expensive_alu_ok)
546 {
547    nir_shader *shader = impl->function->shader;
548    bool progress = false;
549 
550    nir_foreach_block_safe(block, impl) {
551       progress |= nir_opt_peephole_select_block(block, shader, limit,
552                                                 indirect_load_ok,
553                                                 expensive_alu_ok);
554    }
555 
556    if (progress) {
557       nir_metadata_preserve(impl, nir_metadata_none);
558    } else {
559       nir_metadata_preserve(impl, nir_metadata_all);
560    }
561 
562    return progress;
563 }
564 
565 bool
nir_opt_peephole_select(nir_shader * shader,unsigned limit,bool indirect_load_ok,bool expensive_alu_ok)566 nir_opt_peephole_select(nir_shader *shader, unsigned limit,
567                         bool indirect_load_ok, bool expensive_alu_ok)
568 {
569    bool progress = false;
570 
571    nir_foreach_function_impl(impl, shader) {
572       progress |= nir_opt_peephole_select_impl(impl, limit,
573                                                indirect_load_ok,
574                                                expensive_alu_ok);
575    }
576 
577    return progress;
578 }
579