iris: Only enable GL_AMD_depth_clamp_separate on Gen9+
[mesa.git] / src / compiler / nir / nir_loop_analyze.c
1 /*
2 * Copyright © 2015 Thomas Helland
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_constant_expressions.h"
26 #include "nir_loop_analyze.h"
27
28 typedef enum {
29 undefined,
30 invariant,
31 not_invariant,
32 basic_induction
33 } nir_loop_variable_type;
34
35 struct nir_basic_induction_var;
36
37 typedef struct {
38 /* A link for the work list */
39 struct list_head process_link;
40
41 bool in_loop;
42
43 /* The ssa_def associated with this info */
44 nir_ssa_def *def;
45
46 /* The type of this ssa_def */
47 nir_loop_variable_type type;
48
49 /* If this is of type basic_induction */
50 struct nir_basic_induction_var *ind;
51
52 /* True if variable is in an if branch */
53 bool in_if_branch;
54
55 /* True if variable is in a nested loop */
56 bool in_nested_loop;
57
58 } nir_loop_variable;
59
60 typedef struct nir_basic_induction_var {
61 nir_op alu_op; /* The type of alu-operation */
62 nir_loop_variable *alu_def; /* The def of the alu-operation */
63 nir_loop_variable *invariant; /* The invariant alu-operand */
64 nir_loop_variable *def_outside_loop; /* The phi-src outside the loop */
65 } nir_basic_induction_var;
66
67 typedef struct {
68 /* The loop we store information for */
69 nir_loop *loop;
70
71 /* Loop_variable for all ssa_defs in function */
72 nir_loop_variable *loop_vars;
73
74 /* A list of the loop_vars to analyze */
75 struct list_head process_list;
76
77 nir_variable_mode indirect_mask;
78
79 } loop_info_state;
80
81 static nir_loop_variable *
82 get_loop_var(nir_ssa_def *value, loop_info_state *state)
83 {
84 return &(state->loop_vars[value->index]);
85 }
86
87 typedef struct {
88 loop_info_state *state;
89 bool in_if_branch;
90 bool in_nested_loop;
91 } init_loop_state;
92
93 static bool
94 init_loop_def(nir_ssa_def *def, void *void_init_loop_state)
95 {
96 init_loop_state *loop_init_state = void_init_loop_state;
97 nir_loop_variable *var = get_loop_var(def, loop_init_state->state);
98
99 if (loop_init_state->in_nested_loop) {
100 var->in_nested_loop = true;
101 } else if (loop_init_state->in_if_branch) {
102 var->in_if_branch = true;
103 } else {
104 /* Add to the tail of the list. That way we start at the beginning of
105 * the defs in the loop instead of the end when walking the list. This
106 * means less recursive calls. Only add defs that are not in nested
107 * loops or conditional blocks.
108 */
109 list_addtail(&var->process_link, &loop_init_state->state->process_list);
110 }
111
112 var->in_loop = true;
113
114 return true;
115 }
116
117 /** Calculate an estimated cost in number of instructions
118 *
119 * We do this so that we don't unroll loops which will later get massively
120 * inflated due to int64 or fp64 lowering. The estimates provided here don't
121 * have to be massively accurate; they just have to be good enough that loop
122 * unrolling doesn't cause things to blow up too much.
123 */
124 static unsigned
125 instr_cost(nir_instr *instr, const nir_shader_compiler_options *options)
126 {
127 if (instr->type == nir_instr_type_intrinsic ||
128 instr->type == nir_instr_type_tex)
129 return 1;
130
131 if (instr->type != nir_instr_type_alu)
132 return 0;
133
134 nir_alu_instr *alu = nir_instr_as_alu(instr);
135 const nir_op_info *info = &nir_op_infos[alu->op];
136
137 /* Assume everything 16 or 32-bit is cheap.
138 *
139 * There are no 64-bit ops that don't have a 64-bit thing as their
140 * destination or first source.
141 */
142 if (nir_dest_bit_size(alu->dest.dest) < 64 &&
143 nir_src_bit_size(alu->src[0].src) < 64)
144 return 1;
145
146 bool is_fp64 = nir_dest_bit_size(alu->dest.dest) == 64 &&
147 nir_alu_type_get_base_type(info->output_type) == nir_type_float;
148 for (unsigned i = 0; i < info->num_inputs; i++) {
149 if (nir_src_bit_size(alu->src[i].src) == 64 &&
150 nir_alu_type_get_base_type(info->input_types[i]) == nir_type_float)
151 is_fp64 = true;
152 }
153
154 if (is_fp64) {
155 /* If it's something lowered normally, it's expensive. */
156 unsigned cost = 1;
157 if (options->lower_doubles_options &
158 nir_lower_doubles_op_to_options_mask(alu->op))
159 cost *= 20;
160
161 /* If it's full software, it's even more expensive */
162 if (options->lower_doubles_options & nir_lower_fp64_full_software)
163 cost *= 100;
164
165 return cost;
166 } else {
167 if (options->lower_int64_options &
168 nir_lower_int64_op_to_options_mask(alu->op)) {
169 /* These require a doing the division algorithm. */
170 if (alu->op == nir_op_idiv || alu->op == nir_op_udiv ||
171 alu->op == nir_op_imod || alu->op == nir_op_umod ||
172 alu->op == nir_op_irem)
173 return 100;
174
175 /* Other int64 lowering isn't usually all that expensive */
176 return 5;
177 }
178
179 return 1;
180 }
181 }
182
183 static bool
184 init_loop_block(nir_block *block, loop_info_state *state,
185 bool in_if_branch, bool in_nested_loop,
186 const nir_shader_compiler_options *options)
187 {
188 init_loop_state init_state = {.in_if_branch = in_if_branch,
189 .in_nested_loop = in_nested_loop,
190 .state = state };
191
192 nir_foreach_instr(instr, block) {
193 state->loop->info->instr_cost += instr_cost(instr, options);
194 nir_foreach_ssa_def(instr, init_loop_def, &init_state);
195 }
196
197 return true;
198 }
199
200 static inline bool
201 is_var_alu(nir_loop_variable *var)
202 {
203 return var->def->parent_instr->type == nir_instr_type_alu;
204 }
205
206 static inline bool
207 is_var_constant(nir_loop_variable *var)
208 {
209 return var->def->parent_instr->type == nir_instr_type_load_const;
210 }
211
212 static inline bool
213 is_var_phi(nir_loop_variable *var)
214 {
215 return var->def->parent_instr->type == nir_instr_type_phi;
216 }
217
218 static inline bool
219 mark_invariant(nir_ssa_def *def, loop_info_state *state)
220 {
221 nir_loop_variable *var = get_loop_var(def, state);
222
223 if (var->type == invariant)
224 return true;
225
226 if (!var->in_loop) {
227 var->type = invariant;
228 return true;
229 }
230
231 if (var->type == not_invariant)
232 return false;
233
234 if (is_var_alu(var)) {
235 nir_alu_instr *alu = nir_instr_as_alu(def->parent_instr);
236
237 for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs; i++) {
238 if (!mark_invariant(alu->src[i].src.ssa, state)) {
239 var->type = not_invariant;
240 return false;
241 }
242 }
243 var->type = invariant;
244 return true;
245 }
246
247 /* Phis shouldn't be invariant except if one operand is invariant, and the
248 * other is the phi itself. These should be removed by opt_remove_phis.
249 * load_consts are already set to invariant and constant during init,
250 * and so should return earlier. Remaining op_codes are set undefined.
251 */
252 var->type = not_invariant;
253 return false;
254 }
255
256 static void
257 compute_invariance_information(loop_info_state *state)
258 {
259 /* An expression is invariant in a loop L if:
260 * (base cases)
261 * – it’s a constant
262 * – it’s a variable use, all of whose single defs are outside of L
263 * (inductive cases)
264 * – it’s a pure computation all of whose args are loop invariant
265 * – it’s a variable use whose single reaching def, and the
266 * rhs of that def is loop-invariant
267 */
268 list_for_each_entry_safe(nir_loop_variable, var, &state->process_list,
269 process_link) {
270 assert(!var->in_if_branch && !var->in_nested_loop);
271
272 if (mark_invariant(var->def, state))
273 list_del(&var->process_link);
274 }
275 }
276
277 static bool
278 compute_induction_information(loop_info_state *state)
279 {
280 bool found_induction_var = false;
281 list_for_each_entry_safe(nir_loop_variable, var, &state->process_list,
282 process_link) {
283
284 /* It can't be an induction variable if it is invariant. Invariants and
285 * things in nested loops or conditionals should have been removed from
286 * the list by compute_invariance_information().
287 */
288 assert(!var->in_if_branch && !var->in_nested_loop &&
289 var->type != invariant);
290
291 /* We are only interested in checking phis for the basic induction
292 * variable case as its simple to detect. All basic induction variables
293 * have a phi node
294 */
295 if (!is_var_phi(var))
296 continue;
297
298 nir_phi_instr *phi = nir_instr_as_phi(var->def->parent_instr);
299 nir_basic_induction_var *biv = rzalloc(state, nir_basic_induction_var);
300
301 nir_foreach_phi_src(src, phi) {
302 nir_loop_variable *src_var = get_loop_var(src->src.ssa, state);
303
304 /* If one of the sources is in an if branch or nested loop then don't
305 * attempt to go any further.
306 */
307 if (src_var->in_if_branch || src_var->in_nested_loop)
308 break;
309
310 /* Detect inductions variables that are incremented in both branches
311 * of an unnested if rather than in a loop block.
312 */
313 if (is_var_phi(src_var)) {
314 nir_phi_instr *src_phi =
315 nir_instr_as_phi(src_var->def->parent_instr);
316
317 nir_op alu_op = nir_num_opcodes; /* avoid uninitialized warning */
318 nir_ssa_def *alu_srcs[2] = {0};
319 nir_foreach_phi_src(src2, src_phi) {
320 nir_loop_variable *src_var2 =
321 get_loop_var(src2->src.ssa, state);
322
323 if (!src_var2->in_if_branch || !is_var_alu(src_var2))
324 break;
325
326 nir_alu_instr *alu =
327 nir_instr_as_alu(src_var2->def->parent_instr);
328 if (nir_op_infos[alu->op].num_inputs != 2)
329 break;
330
331 if (alu->src[0].src.ssa == alu_srcs[0] &&
332 alu->src[1].src.ssa == alu_srcs[1] &&
333 alu->op == alu_op) {
334 /* Both branches perform the same calculation so we can use
335 * one of them to find the induction variable.
336 */
337 src_var = src_var2;
338 } else {
339 alu_srcs[0] = alu->src[0].src.ssa;
340 alu_srcs[1] = alu->src[1].src.ssa;
341 alu_op = alu->op;
342 }
343 }
344 }
345
346 if (!src_var->in_loop) {
347 biv->def_outside_loop = src_var;
348 } else if (is_var_alu(src_var)) {
349 nir_alu_instr *alu = nir_instr_as_alu(src_var->def->parent_instr);
350
351 if (nir_op_infos[alu->op].num_inputs == 2) {
352 biv->alu_def = src_var;
353 biv->alu_op = alu->op;
354
355 for (unsigned i = 0; i < 2; i++) {
356 /* Is one of the operands const, and the other the phi */
357 if (alu->src[i].src.ssa->parent_instr->type == nir_instr_type_load_const &&
358 alu->src[1-i].src.ssa == &phi->dest.ssa)
359 biv->invariant = get_loop_var(alu->src[i].src.ssa, state);
360 }
361 }
362 }
363 }
364
365 if (biv->alu_def && biv->def_outside_loop && biv->invariant &&
366 is_var_constant(biv->def_outside_loop)) {
367 assert(is_var_constant(biv->invariant));
368 biv->alu_def->type = basic_induction;
369 biv->alu_def->ind = biv;
370 var->type = basic_induction;
371 var->ind = biv;
372
373 found_induction_var = true;
374 } else {
375 ralloc_free(biv);
376 }
377 }
378 return found_induction_var;
379 }
380
381 static bool
382 initialize_ssa_def(nir_ssa_def *def, void *void_state)
383 {
384 loop_info_state *state = void_state;
385 nir_loop_variable *var = get_loop_var(def, state);
386
387 var->in_loop = false;
388 var->def = def;
389
390 if (def->parent_instr->type == nir_instr_type_load_const) {
391 var->type = invariant;
392 } else {
393 var->type = undefined;
394 }
395
396 return true;
397 }
398
399 static bool
400 find_loop_terminators(loop_info_state *state)
401 {
402 bool success = false;
403 foreach_list_typed_safe(nir_cf_node, node, node, &state->loop->body) {
404 if (node->type == nir_cf_node_if) {
405 nir_if *nif = nir_cf_node_as_if(node);
406
407 nir_block *break_blk = NULL;
408 nir_block *continue_from_blk = NULL;
409 bool continue_from_then = true;
410
411 nir_block *last_then = nir_if_last_then_block(nif);
412 nir_block *last_else = nir_if_last_else_block(nif);
413 if (nir_block_ends_in_break(last_then)) {
414 break_blk = last_then;
415 continue_from_blk = last_else;
416 continue_from_then = false;
417 } else if (nir_block_ends_in_break(last_else)) {
418 break_blk = last_else;
419 continue_from_blk = last_then;
420 }
421
422 /* If there is a break then we should find a terminator. If we can
423 * not find a loop terminator, but there is a break-statement then
424 * we should return false so that we do not try to find trip-count
425 */
426 if (!nir_is_trivial_loop_if(nif, break_blk)) {
427 state->loop->info->complex_loop = true;
428 return false;
429 }
430
431 /* Continue if the if contained no jumps at all */
432 if (!break_blk)
433 continue;
434
435 if (nif->condition.ssa->parent_instr->type == nir_instr_type_phi) {
436 state->loop->info->complex_loop = true;
437 return false;
438 }
439
440 nir_loop_terminator *terminator =
441 rzalloc(state->loop->info, nir_loop_terminator);
442
443 list_addtail(&terminator->loop_terminator_link,
444 &state->loop->info->loop_terminator_list);
445
446 terminator->nif = nif;
447 terminator->break_block = break_blk;
448 terminator->continue_from_block = continue_from_blk;
449 terminator->continue_from_then = continue_from_then;
450 terminator->conditional_instr = nif->condition.ssa->parent_instr;
451
452 success = true;
453 }
454 }
455
456 return success;
457 }
458
459 /* This function looks for an array access within a loop that uses an
460 * induction variable for the array index. If found it returns the size of the
461 * array, otherwise 0 is returned. If we find an induction var we pass it back
462 * to the caller via array_index_out.
463 */
464 static unsigned
465 find_array_access_via_induction(loop_info_state *state,
466 nir_deref_instr *deref,
467 nir_loop_variable **array_index_out)
468 {
469 for (nir_deref_instr *d = deref; d; d = nir_deref_instr_parent(d)) {
470 if (d->deref_type != nir_deref_type_array)
471 continue;
472
473 assert(d->arr.index.is_ssa);
474 nir_loop_variable *array_index = get_loop_var(d->arr.index.ssa, state);
475
476 if (array_index->type != basic_induction)
477 continue;
478
479 if (array_index_out)
480 *array_index_out = array_index;
481
482 nir_deref_instr *parent = nir_deref_instr_parent(d);
483 if (glsl_type_is_array_or_matrix(parent->type)) {
484 return glsl_get_length(parent->type);
485 } else {
486 assert(glsl_type_is_vector(parent->type));
487 return glsl_get_vector_elements(parent->type);
488 }
489 }
490
491 return 0;
492 }
493
494 static bool
495 guess_loop_limit(loop_info_state *state, nir_const_value *limit_val,
496 nir_loop_variable *basic_ind)
497 {
498 unsigned min_array_size = 0;
499
500 nir_foreach_block_in_cf_node(block, &state->loop->cf_node) {
501 nir_foreach_instr(instr, block) {
502 if (instr->type != nir_instr_type_intrinsic)
503 continue;
504
505 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
506
507 /* Check for arrays variably-indexed by a loop induction variable. */
508 if (intrin->intrinsic == nir_intrinsic_load_deref ||
509 intrin->intrinsic == nir_intrinsic_store_deref ||
510 intrin->intrinsic == nir_intrinsic_copy_deref) {
511
512 nir_loop_variable *array_idx = NULL;
513 unsigned array_size =
514 find_array_access_via_induction(state,
515 nir_src_as_deref(intrin->src[0]),
516 &array_idx);
517 if (basic_ind == array_idx &&
518 (min_array_size == 0 || min_array_size > array_size)) {
519 min_array_size = array_size;
520 }
521
522 if (intrin->intrinsic != nir_intrinsic_copy_deref)
523 continue;
524
525 array_size =
526 find_array_access_via_induction(state,
527 nir_src_as_deref(intrin->src[1]),
528 &array_idx);
529 if (basic_ind == array_idx &&
530 (min_array_size == 0 || min_array_size > array_size)) {
531 min_array_size = array_size;
532 }
533 }
534 }
535 }
536
537 if (min_array_size) {
538 limit_val->i32 = min_array_size;
539 return true;
540 }
541
542 return false;
543 }
544
545 static bool
546 try_find_limit_of_alu(nir_loop_variable *limit, nir_const_value *limit_val,
547 nir_loop_terminator *terminator, loop_info_state *state)
548 {
549 if(!is_var_alu(limit))
550 return false;
551
552 nir_alu_instr *limit_alu = nir_instr_as_alu(limit->def->parent_instr);
553
554 if (limit_alu->op == nir_op_imin ||
555 limit_alu->op == nir_op_fmin) {
556 limit = get_loop_var(limit_alu->src[0].src.ssa, state);
557
558 if (!is_var_constant(limit))
559 limit = get_loop_var(limit_alu->src[1].src.ssa, state);
560
561 if (!is_var_constant(limit))
562 return false;
563
564 *limit_val = nir_instr_as_load_const(limit->def->parent_instr)->value[0];
565
566 terminator->exact_trip_count_unknown = true;
567
568 return true;
569 }
570
571 return false;
572 }
573
574 static int32_t
575 get_iteration(nir_op cond_op, nir_const_value *initial, nir_const_value *step,
576 nir_const_value *limit)
577 {
578 int32_t iter;
579
580 switch (cond_op) {
581 case nir_op_ige:
582 case nir_op_ilt:
583 case nir_op_ieq:
584 case nir_op_ine: {
585 int32_t initial_val = initial->i32;
586 int32_t span = limit->i32 - initial_val;
587 iter = span / step->i32;
588 break;
589 }
590 case nir_op_uge:
591 case nir_op_ult: {
592 uint32_t initial_val = initial->u32;
593 uint32_t span = limit->u32 - initial_val;
594 iter = span / step->u32;
595 break;
596 }
597 case nir_op_fge:
598 case nir_op_flt:
599 case nir_op_feq:
600 case nir_op_fne: {
601 float initial_val = initial->f32;
602 float span = limit->f32 - initial_val;
603 iter = span / step->f32;
604 break;
605 }
606 default:
607 return -1;
608 }
609
610 return iter;
611 }
612
613 static bool
614 test_iterations(int32_t iter_int, nir_const_value *step,
615 nir_const_value *limit, nir_op cond_op, unsigned bit_size,
616 nir_alu_type induction_base_type,
617 nir_const_value *initial, bool limit_rhs, bool invert_cond)
618 {
619 assert(nir_op_infos[cond_op].num_inputs == 2);
620
621 nir_const_value iter_src = {0, };
622 nir_op mul_op;
623 nir_op add_op;
624 switch (induction_base_type) {
625 case nir_type_float:
626 iter_src.f32 = (float) iter_int;
627 mul_op = nir_op_fmul;
628 add_op = nir_op_fadd;
629 break;
630 case nir_type_int:
631 case nir_type_uint:
632 iter_src.i32 = iter_int;
633 mul_op = nir_op_imul;
634 add_op = nir_op_iadd;
635 break;
636 default:
637 unreachable("Unhandled induction variable base type!");
638 }
639
640 /* Multiple the iteration count we are testing by the number of times we
641 * step the induction variable each iteration.
642 */
643 nir_const_value *mul_src[2] = { &iter_src, step };
644 nir_const_value mul_result;
645 nir_eval_const_opcode(mul_op, &mul_result, 1, bit_size, mul_src);
646
647 /* Add the initial value to the accumulated induction variable total */
648 nir_const_value *add_src[2] = { &mul_result, initial };
649 nir_const_value add_result;
650 nir_eval_const_opcode(add_op, &add_result, 1, bit_size, add_src);
651
652 nir_const_value *src[2];
653 src[limit_rhs ? 0 : 1] = &add_result;
654 src[limit_rhs ? 1 : 0] = limit;
655
656 /* Evaluate the loop exit condition */
657 nir_const_value result;
658 nir_eval_const_opcode(cond_op, &result, 1, bit_size, src);
659
660 return invert_cond ? !result.b : result.b;
661 }
662
663 static int
664 calculate_iterations(nir_const_value *initial, nir_const_value *step,
665 nir_const_value *limit, nir_loop_variable *alu_def,
666 nir_alu_instr *cond_alu, nir_op alu_op, bool limit_rhs,
667 bool invert_cond)
668 {
669 assert(initial != NULL && step != NULL && limit != NULL);
670
671 nir_alu_instr *alu = nir_instr_as_alu(alu_def->def->parent_instr);
672
673 /* nir_op_isub should have been lowered away by this point */
674 assert(alu->op != nir_op_isub);
675
676 /* Make sure the alu type for our induction variable is compatible with the
677 * conditional alus input type. If its not something has gone really wrong.
678 */
679 nir_alu_type induction_base_type =
680 nir_alu_type_get_base_type(nir_op_infos[alu->op].output_type);
681 if (induction_base_type == nir_type_int || induction_base_type == nir_type_uint) {
682 assert(nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[1]) == nir_type_int ||
683 nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[1]) == nir_type_uint);
684 } else {
685 assert(nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[0]) ==
686 induction_base_type);
687 }
688
689 /* Check for nsupported alu operations */
690 if (alu->op != nir_op_iadd && alu->op != nir_op_fadd)
691 return -1;
692
693 /* do-while loops can increment the starting value before the condition is
694 * checked. e.g.
695 *
696 * do {
697 * ndx++;
698 * } while (ndx < 3);
699 *
700 * Here we check if the induction variable is used directly by the loop
701 * condition and if so we assume we need to step the initial value.
702 */
703 unsigned trip_offset = 0;
704 if (cond_alu->src[0].src.ssa == alu_def->def ||
705 cond_alu->src[1].src.ssa == alu_def->def) {
706 trip_offset = 1;
707 }
708
709 int iter_int = get_iteration(alu_op, initial, step, limit);
710
711 /* If iter_int is negative the loop is ill-formed or is the conditional is
712 * unsigned with a huge iteration count so don't bother going any further.
713 */
714 if (iter_int < 0)
715 return -1;
716
717 /* An explanation from the GLSL unrolling pass:
718 *
719 * Make sure that the calculated number of iterations satisfies the exit
720 * condition. This is needed to catch off-by-one errors and some types of
721 * ill-formed loops. For example, we need to detect that the following
722 * loop does not have a maximum iteration count.
723 *
724 * for (float x = 0.0; x != 0.9; x += 0.2);
725 */
726 assert(nir_src_bit_size(alu->src[0].src) ==
727 nir_src_bit_size(alu->src[1].src));
728 unsigned bit_size = nir_src_bit_size(alu->src[0].src);
729 for (int bias = -1; bias <= 1; bias++) {
730 const int iter_bias = iter_int + bias;
731
732 if (test_iterations(iter_bias, step, limit, alu_op, bit_size,
733 induction_base_type, initial,
734 limit_rhs, invert_cond)) {
735 return iter_bias > 0 ? iter_bias - trip_offset : iter_bias;
736 }
737 }
738
739 return -1;
740 }
741
742 static nir_op
743 inverse_comparison(nir_alu_instr *alu)
744 {
745 switch (alu->op) {
746 case nir_op_fge:
747 return nir_op_flt;
748 case nir_op_ige:
749 return nir_op_ilt;
750 case nir_op_uge:
751 return nir_op_ult;
752 case nir_op_flt:
753 return nir_op_fge;
754 case nir_op_ilt:
755 return nir_op_ige;
756 case nir_op_ult:
757 return nir_op_uge;
758 case nir_op_feq:
759 return nir_op_fne;
760 case nir_op_ieq:
761 return nir_op_ine;
762 case nir_op_fne:
763 return nir_op_feq;
764 case nir_op_ine:
765 return nir_op_ieq;
766 default:
767 unreachable("Unsuported comparison!");
768 }
769 }
770
771 static bool
772 is_supported_terminator_condition(nir_alu_instr *alu)
773 {
774 return nir_alu_instr_is_comparison(alu) &&
775 nir_op_infos[alu->op].num_inputs == 2;
776 }
777
778 static bool
779 get_induction_and_limit_vars(nir_alu_instr *alu, nir_loop_variable **ind,
780 nir_loop_variable **limit,
781 loop_info_state *state)
782 {
783 bool limit_rhs = true;
784
785 /* We assume that the limit is the "right" operand */
786 *ind = get_loop_var(alu->src[0].src.ssa, state);
787 *limit = get_loop_var(alu->src[1].src.ssa, state);
788
789 if ((*ind)->type != basic_induction) {
790 /* We had it the wrong way, flip things around */
791 *ind = get_loop_var(alu->src[1].src.ssa, state);
792 *limit = get_loop_var(alu->src[0].src.ssa, state);
793 limit_rhs = false;
794 }
795
796 return limit_rhs;
797 }
798
799 static void
800 try_find_trip_count_vars_in_iand(nir_alu_instr **alu,
801 nir_loop_variable **ind,
802 nir_loop_variable **limit,
803 bool *limit_rhs,
804 loop_info_state *state)
805 {
806 assert((*alu)->op == nir_op_ieq || (*alu)->op == nir_op_inot);
807
808 nir_ssa_def *iand_def = (*alu)->src[0].src.ssa;
809
810 if ((*alu)->op == nir_op_ieq) {
811 nir_ssa_def *zero_def = (*alu)->src[1].src.ssa;
812
813 if (iand_def->parent_instr->type != nir_instr_type_alu ||
814 zero_def->parent_instr->type != nir_instr_type_load_const) {
815
816 /* Maybe we had it the wrong way, flip things around */
817 iand_def = (*alu)->src[1].src.ssa;
818 zero_def = (*alu)->src[0].src.ssa;
819
820 /* If we still didn't find what we need then return */
821 if (zero_def->parent_instr->type != nir_instr_type_load_const)
822 return;
823 }
824
825 /* If the loop is not breaking on (x && y) == 0 then return */
826 nir_const_value *zero =
827 nir_instr_as_load_const(zero_def->parent_instr)->value;
828 if (zero[0].i32 != 0)
829 return;
830 }
831
832 if (iand_def->parent_instr->type != nir_instr_type_alu)
833 return;
834
835 nir_alu_instr *iand = nir_instr_as_alu(iand_def->parent_instr);
836 if (iand->op != nir_op_iand)
837 return;
838
839 /* Check if iand src is a terminator condition and try get induction var
840 * and trip limit var.
841 */
842 nir_ssa_def *src = iand->src[0].src.ssa;
843 if (src->parent_instr->type == nir_instr_type_alu) {
844 *alu = nir_instr_as_alu(src->parent_instr);
845 if (is_supported_terminator_condition(*alu))
846 *limit_rhs = get_induction_and_limit_vars(*alu, ind, limit, state);
847 }
848
849 /* Try the other iand src if needed */
850 if (*ind == NULL || (*ind && (*ind)->type != basic_induction) ||
851 !is_var_constant(*limit)) {
852 src = iand->src[1].src.ssa;
853 if (src->parent_instr->type == nir_instr_type_alu) {
854 nir_alu_instr *tmp_alu = nir_instr_as_alu(src->parent_instr);
855 if (is_supported_terminator_condition(tmp_alu)) {
856 *alu = tmp_alu;
857 *limit_rhs = get_induction_and_limit_vars(*alu, ind, limit, state);
858 }
859 }
860 }
861 }
862
863 /* Run through each of the terminators of the loop and try to infer a possible
864 * trip-count. We need to check them all, and set the lowest trip-count as the
865 * trip-count of our loop. If one of the terminators has an undecidable
866 * trip-count we can not safely assume anything about the duration of the
867 * loop.
868 */
869 static void
870 find_trip_count(loop_info_state *state)
871 {
872 bool trip_count_known = true;
873 bool guessed_trip_count = false;
874 nir_loop_terminator *limiting_terminator = NULL;
875 int max_trip_count = -1;
876
877 list_for_each_entry(nir_loop_terminator, terminator,
878 &state->loop->info->loop_terminator_list,
879 loop_terminator_link) {
880
881 if (terminator->conditional_instr->type != nir_instr_type_alu) {
882 /* If we get here the loop is dead and will get cleaned up by the
883 * nir_opt_dead_cf pass.
884 */
885 trip_count_known = false;
886 continue;
887 }
888
889 nir_alu_instr *alu = nir_instr_as_alu(terminator->conditional_instr);
890 nir_op alu_op = alu->op;
891
892 bool limit_rhs;
893 nir_loop_variable *basic_ind = NULL;
894 nir_loop_variable *limit;
895 if (alu->op == nir_op_inot || alu->op == nir_op_ieq) {
896 nir_alu_instr *new_alu = alu;
897 try_find_trip_count_vars_in_iand(&new_alu, &basic_ind, &limit,
898 &limit_rhs, state);
899
900 /* The loop is exiting on (x && y) == 0 so we need to get the
901 * inverse of x or y (i.e. which ever contained the induction var) in
902 * order to compute the trip count.
903 */
904 if (basic_ind && basic_ind->type == basic_induction) {
905 alu = new_alu;
906 alu_op = inverse_comparison(alu);
907 trip_count_known = false;
908 terminator->exact_trip_count_unknown = true;
909 }
910 }
911
912 if (!basic_ind) {
913 if (!is_supported_terminator_condition(alu)) {
914 trip_count_known = false;
915 continue;
916 }
917
918 limit_rhs = get_induction_and_limit_vars(alu, &basic_ind, &limit,
919 state);
920 }
921
922 /* The comparison has to have a basic induction variable for us to be
923 * able to find trip counts.
924 */
925 if (basic_ind->type != basic_induction) {
926 trip_count_known = false;
927 continue;
928 }
929
930 terminator->induction_rhs = !limit_rhs;
931
932 /* Attempt to find a constant limit for the loop */
933 nir_const_value limit_val;
934 if (is_var_constant(limit)) {
935 limit_val =
936 nir_instr_as_load_const(limit->def->parent_instr)->value[0];
937 } else {
938 trip_count_known = false;
939
940 if (!try_find_limit_of_alu(limit, &limit_val, terminator, state)) {
941 /* Guess loop limit based on array access */
942 if (!guess_loop_limit(state, &limit_val, basic_ind)) {
943 continue;
944 }
945
946 guessed_trip_count = true;
947 }
948 }
949
950 /* We have determined that we have the following constants:
951 * (With the typical int i = 0; i < x; i++; as an example)
952 * - Upper limit.
953 * - Starting value
954 * - Step / iteration size
955 * Thats all thats needed to calculate the trip-count
956 */
957
958 nir_const_value *initial_val =
959 nir_instr_as_load_const(basic_ind->ind->def_outside_loop->
960 def->parent_instr)->value;
961
962 nir_const_value *step_val =
963 nir_instr_as_load_const(basic_ind->ind->invariant->def->
964 parent_instr)->value;
965
966 int iterations = calculate_iterations(initial_val, step_val,
967 &limit_val,
968 basic_ind->ind->alu_def, alu,
969 alu_op, limit_rhs,
970 terminator->continue_from_then);
971
972 /* Where we not able to calculate the iteration count */
973 if (iterations == -1) {
974 trip_count_known = false;
975 guessed_trip_count = false;
976 continue;
977 }
978
979 if (guessed_trip_count) {
980 guessed_trip_count = false;
981 if (state->loop->info->guessed_trip_count == 0 ||
982 state->loop->info->guessed_trip_count > iterations)
983 state->loop->info->guessed_trip_count = iterations;
984
985 continue;
986 }
987
988 /* If this is the first run or we have found a smaller amount of
989 * iterations than previously (we have identified a more limiting
990 * terminator) set the trip count and limiting terminator.
991 */
992 if (max_trip_count == -1 || iterations < max_trip_count) {
993 max_trip_count = iterations;
994 limiting_terminator = terminator;
995 }
996 }
997
998 state->loop->info->exact_trip_count_known = trip_count_known;
999 if (max_trip_count > -1)
1000 state->loop->info->max_trip_count = max_trip_count;
1001 state->loop->info->limiting_terminator = limiting_terminator;
1002 }
1003
1004 static bool
1005 force_unroll_array_access(loop_info_state *state, nir_deref_instr *deref)
1006 {
1007 unsigned array_size = find_array_access_via_induction(state, deref, NULL);
1008 if (array_size) {
1009 if (array_size == state->loop->info->max_trip_count)
1010 return true;
1011
1012 if (deref->mode & state->indirect_mask)
1013 return true;
1014 }
1015
1016 return false;
1017 }
1018
1019 static bool
1020 force_unroll_heuristics(loop_info_state *state, nir_block *block)
1021 {
1022 nir_foreach_instr(instr, block) {
1023 if (instr->type != nir_instr_type_intrinsic)
1024 continue;
1025
1026 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
1027
1028 /* Check for arrays variably-indexed by a loop induction variable.
1029 * Unrolling the loop may convert that access into constant-indexing.
1030 */
1031 if (intrin->intrinsic == nir_intrinsic_load_deref ||
1032 intrin->intrinsic == nir_intrinsic_store_deref ||
1033 intrin->intrinsic == nir_intrinsic_copy_deref) {
1034 if (force_unroll_array_access(state,
1035 nir_src_as_deref(intrin->src[0])))
1036 return true;
1037
1038 if (intrin->intrinsic == nir_intrinsic_copy_deref &&
1039 force_unroll_array_access(state,
1040 nir_src_as_deref(intrin->src[1])))
1041 return true;
1042 }
1043 }
1044
1045 return false;
1046 }
1047
1048 static void
1049 get_loop_info(loop_info_state *state, nir_function_impl *impl)
1050 {
1051 nir_shader *shader = impl->function->shader;
1052 const nir_shader_compiler_options *options = shader->options;
1053
1054 /* Initialize all variables to "outside_loop". This also marks defs
1055 * invariant and constant if they are nir_instr_type_load_consts
1056 */
1057 nir_foreach_block(block, impl) {
1058 nir_foreach_instr(instr, block)
1059 nir_foreach_ssa_def(instr, initialize_ssa_def, state);
1060 }
1061
1062 /* Add all entries in the outermost part of the loop to the processing list
1063 * Mark the entries in conditionals or in nested loops accordingly
1064 */
1065 foreach_list_typed_safe(nir_cf_node, node, node, &state->loop->body) {
1066 switch (node->type) {
1067
1068 case nir_cf_node_block:
1069 init_loop_block(nir_cf_node_as_block(node), state,
1070 false, false, options);
1071 break;
1072
1073 case nir_cf_node_if:
1074 nir_foreach_block_in_cf_node(block, node)
1075 init_loop_block(block, state, true, false, options);
1076 break;
1077
1078 case nir_cf_node_loop:
1079 nir_foreach_block_in_cf_node(block, node) {
1080 init_loop_block(block, state, false, true, options);
1081 }
1082 break;
1083
1084 case nir_cf_node_function:
1085 break;
1086 }
1087 }
1088
1089 /* Try to find all simple terminators of the loop. If we can't find any,
1090 * or we find possible terminators that have side effects then bail.
1091 */
1092 if (!find_loop_terminators(state)) {
1093 list_for_each_entry_safe(nir_loop_terminator, terminator,
1094 &state->loop->info->loop_terminator_list,
1095 loop_terminator_link) {
1096 list_del(&terminator->loop_terminator_link);
1097 ralloc_free(terminator);
1098 }
1099 return;
1100 }
1101
1102 /* Induction analysis needs invariance information so get that first */
1103 compute_invariance_information(state);
1104
1105 /* We have invariance information so try to find induction variables */
1106 if (!compute_induction_information(state))
1107 return;
1108
1109 /* Run through each of the terminators and try to compute a trip-count */
1110 find_trip_count(state);
1111
1112 nir_foreach_block_in_cf_node(block, &state->loop->cf_node) {
1113 if (force_unroll_heuristics(state, block)) {
1114 state->loop->info->force_unroll = true;
1115 break;
1116 }
1117 }
1118 }
1119
1120 static loop_info_state *
1121 initialize_loop_info_state(nir_loop *loop, void *mem_ctx,
1122 nir_function_impl *impl)
1123 {
1124 loop_info_state *state = rzalloc(mem_ctx, loop_info_state);
1125 state->loop_vars = rzalloc_array(mem_ctx, nir_loop_variable,
1126 impl->ssa_alloc);
1127 state->loop = loop;
1128
1129 list_inithead(&state->process_list);
1130
1131 if (loop->info)
1132 ralloc_free(loop->info);
1133
1134 loop->info = rzalloc(loop, nir_loop_info);
1135
1136 list_inithead(&loop->info->loop_terminator_list);
1137
1138 return state;
1139 }
1140
1141 static void
1142 process_loops(nir_cf_node *cf_node, nir_variable_mode indirect_mask)
1143 {
1144 switch (cf_node->type) {
1145 case nir_cf_node_block:
1146 return;
1147 case nir_cf_node_if: {
1148 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
1149 foreach_list_typed(nir_cf_node, nested_node, node, &if_stmt->then_list)
1150 process_loops(nested_node, indirect_mask);
1151 foreach_list_typed(nir_cf_node, nested_node, node, &if_stmt->else_list)
1152 process_loops(nested_node, indirect_mask);
1153 return;
1154 }
1155 case nir_cf_node_loop: {
1156 nir_loop *loop = nir_cf_node_as_loop(cf_node);
1157 foreach_list_typed(nir_cf_node, nested_node, node, &loop->body)
1158 process_loops(nested_node, indirect_mask);
1159 break;
1160 }
1161 default:
1162 unreachable("unknown cf node type");
1163 }
1164
1165 nir_loop *loop = nir_cf_node_as_loop(cf_node);
1166 nir_function_impl *impl = nir_cf_node_get_function(cf_node);
1167 void *mem_ctx = ralloc_context(NULL);
1168
1169 loop_info_state *state = initialize_loop_info_state(loop, mem_ctx, impl);
1170 state->indirect_mask = indirect_mask;
1171
1172 get_loop_info(state, impl);
1173
1174 ralloc_free(mem_ctx);
1175 }
1176
1177 void
1178 nir_loop_analyze_impl(nir_function_impl *impl,
1179 nir_variable_mode indirect_mask)
1180 {
1181 nir_index_ssa_defs(impl);
1182 foreach_list_typed(nir_cf_node, node, node, &impl->body)
1183 process_loops(node, indirect_mask);
1184 }