2 * Copyright © 2016 Intel Corporation
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:
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
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
25 #include "nir_builder.h"
26 #include "nir_control_flow.h"
27 #include "nir_loop_analyze.h"
30 /* This limit is chosen fairly arbitrarily. GLSL IR max iteration is 32
31 * instructions. (Multiply counting nodes and magic number 5.) But there is
32 * no 1:1 mapping between GLSL IR and NIR so 25 was picked because it seemed
33 * to give about the same results. Around 5 instructions per node. But some
34 * loops that would unroll with GLSL IR fail to unroll if we set this to 25 so
37 #define LOOP_UNROLL_LIMIT 26
39 /* Prepare this loop for unrolling by first converting to lcssa and then
40 * converting the phis from the top level of the loop body to regs.
41 * Partially converting out of SSA allows us to unroll the loop without having
42 * to keep track of and update phis along the way which gets tricky and
43 * doesn't add much value over converting to regs.
45 * The loop may have a continue instruction at the end of the loop which does
46 * nothing. Once we're out of SSA, we can safely delete it so we don't have
47 * to deal with it later.
50 loop_prepare_for_unroll(nir_loop
*loop
)
52 nir_rematerialize_derefs_in_use_blocks_impl(
53 nir_cf_node_get_function(&loop
->cf_node
));
55 nir_convert_loop_to_lcssa(loop
);
57 /* Lower phis at the top level of the loop body */
58 foreach_list_typed_safe(nir_cf_node
, node
, node
, &loop
->body
) {
59 if (nir_cf_node_block
== node
->type
) {
60 nir_lower_phis_to_regs_block(nir_cf_node_as_block(node
));
64 /* Lower phis after the loop */
65 nir_block
*block_after_loop
=
66 nir_cf_node_as_block(nir_cf_node_next(&loop
->cf_node
));
68 nir_lower_phis_to_regs_block(block_after_loop
);
70 /* Remove continue if its the last instruction in the loop */
71 nir_instr
*last_instr
= nir_block_last_instr(nir_loop_last_block(loop
));
72 if (last_instr
&& last_instr
->type
== nir_instr_type_jump
) {
73 nir_instr_remove(last_instr
);
78 get_first_blocks_in_terminator(nir_loop_terminator
*term
,
79 nir_block
**first_break_block
,
80 nir_block
**first_continue_block
)
82 if (term
->continue_from_then
) {
83 *first_continue_block
= nir_if_first_then_block(term
->nif
);
84 *first_break_block
= nir_if_first_else_block(term
->nif
);
86 *first_continue_block
= nir_if_first_else_block(term
->nif
);
87 *first_break_block
= nir_if_first_then_block(term
->nif
);
92 * Unroll a loop where we know exactly how many iterations there are and there
93 * is only a single exit point. Note here we can unroll loops with multiple
94 * theoretical exits that only have a single terminating exit that we always
95 * know is the "real" exit.
101 * And the iteration count is 3, the output will be:
103 * ...instrs... ...instrs... ...instrs...
106 simple_unroll(nir_loop
*loop
)
108 nir_loop_terminator
*limiting_term
= loop
->info
->limiting_terminator
;
109 assert(nir_is_trivial_loop_if(limiting_term
->nif
,
110 limiting_term
->break_block
));
112 loop_prepare_for_unroll(loop
);
114 /* Skip over loop terminator and get the loop body. */
115 list_for_each_entry(nir_loop_terminator
, terminator
,
116 &loop
->info
->loop_terminator_list
,
117 loop_terminator_link
) {
119 /* Remove all but the limiting terminator as we know the other exit
120 * conditions can never be met. Note we need to extract any instructions
121 * in the continue from branch and insert then into the loop body before
124 if (terminator
->nif
!= limiting_term
->nif
) {
125 nir_block
*first_break_block
;
126 nir_block
*first_continue_block
;
127 get_first_blocks_in_terminator(terminator
, &first_break_block
,
128 &first_continue_block
);
130 assert(nir_is_trivial_loop_if(terminator
->nif
,
131 terminator
->break_block
));
133 nir_cf_list continue_from_lst
;
134 nir_cf_extract(&continue_from_lst
,
135 nir_before_block(first_continue_block
),
136 nir_after_block(terminator
->continue_from_block
));
137 nir_cf_reinsert(&continue_from_lst
,
138 nir_after_cf_node(&terminator
->nif
->cf_node
));
140 nir_cf_node_remove(&terminator
->nif
->cf_node
);
144 nir_block
*first_break_block
;
145 nir_block
*first_continue_block
;
146 get_first_blocks_in_terminator(limiting_term
, &first_break_block
,
147 &first_continue_block
);
149 /* Pluck out the loop header */
150 nir_block
*header_blk
= nir_loop_first_block(loop
);
151 nir_cf_list lp_header
;
152 nir_cf_extract(&lp_header
, nir_before_block(header_blk
),
153 nir_before_cf_node(&limiting_term
->nif
->cf_node
));
155 /* Add the continue from block of the limiting terminator to the loop body
157 nir_cf_list continue_from_lst
;
158 nir_cf_extract(&continue_from_lst
, nir_before_block(first_continue_block
),
159 nir_after_block(limiting_term
->continue_from_block
));
160 nir_cf_reinsert(&continue_from_lst
,
161 nir_after_cf_node(&limiting_term
->nif
->cf_node
));
163 /* Pluck out the loop body */
164 nir_cf_list loop_body
;
165 nir_cf_extract(&loop_body
, nir_after_cf_node(&limiting_term
->nif
->cf_node
),
166 nir_after_block(nir_loop_last_block(loop
)));
168 struct hash_table
*remap_table
=
169 _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
170 _mesa_key_pointer_equal
);
172 /* Clone the loop header and insert before the loop */
173 nir_cf_list_clone_and_reinsert(&lp_header
, loop
->cf_node
.parent
,
174 nir_before_cf_node(&loop
->cf_node
),
177 for (unsigned i
= 0; i
< loop
->info
->max_trip_count
; i
++) {
178 /* Clone loop body and insert before the loop */
179 nir_cf_list_clone_and_reinsert(&loop_body
, loop
->cf_node
.parent
,
180 nir_before_cf_node(&loop
->cf_node
),
183 /* Clone loop header and insert after loop body */
184 nir_cf_list_clone_and_reinsert(&lp_header
, loop
->cf_node
.parent
,
185 nir_before_cf_node(&loop
->cf_node
),
189 /* Remove the break from the loop terminator and add instructions from
190 * the break block after the unrolled loop.
192 nir_instr
*break_instr
= nir_block_last_instr(limiting_term
->break_block
);
193 nir_instr_remove(break_instr
);
194 nir_cf_list break_list
;
195 nir_cf_extract(&break_list
, nir_before_block(first_break_block
),
196 nir_after_block(limiting_term
->break_block
));
198 /* Clone so things get properly remapped */
199 nir_cf_list_clone_and_reinsert(&break_list
, loop
->cf_node
.parent
,
200 nir_before_cf_node(&loop
->cf_node
),
203 /* Remove the loop */
204 nir_cf_node_remove(&loop
->cf_node
);
206 /* Delete the original loop body, break block & header */
207 nir_cf_delete(&lp_header
);
208 nir_cf_delete(&loop_body
);
209 nir_cf_delete(&break_list
);
211 _mesa_hash_table_destroy(remap_table
, NULL
);
215 move_cf_list_into_loop_term(nir_cf_list
*lst
, nir_loop_terminator
*term
)
217 /* Move the rest of the loop inside the continue-from-block */
218 nir_cf_reinsert(lst
, nir_after_block(term
->continue_from_block
));
220 /* Remove the break */
221 nir_instr_remove(nir_block_last_instr(term
->break_block
));
225 get_complex_unroll_insert_location(nir_cf_node
*node
, bool continue_from_then
)
227 if (node
->type
== nir_cf_node_loop
) {
228 return nir_before_cf_node(node
);
230 nir_if
*if_stmt
= nir_cf_node_as_if(node
);
231 if (continue_from_then
) {
232 return nir_after_block(nir_if_last_then_block(if_stmt
));
234 return nir_after_block(nir_if_last_else_block(if_stmt
));
240 * Unroll a loop with two exists when the trip count of one of the exits is
241 * unknown. If continue_from_then is true, the loop is repeated only when the
242 * "then" branch of the if is taken; otherwise it is repeated only
243 * when the "else" branch of the if is taken.
245 * For example, if the input is:
248 * ...phis/condition...
250 * ...then instructions...
252 * ...continue instructions...
258 * And the iteration count is 3, and unlimit_term->continue_from_then is true,
259 * then the output will be:
263 * ...then instructions...
266 * ...then instructions...
269 * ...then instructions...
272 * ...continue instructions...
275 * ...continue instructions...
278 * ...continue instructions...
282 complex_unroll(nir_loop
*loop
, nir_loop_terminator
*unlimit_term
,
283 bool limiting_term_second
)
285 assert(nir_is_trivial_loop_if(unlimit_term
->nif
,
286 unlimit_term
->break_block
));
288 nir_loop_terminator
*limiting_term
= loop
->info
->limiting_terminator
;
289 assert(nir_is_trivial_loop_if(limiting_term
->nif
,
290 limiting_term
->break_block
));
292 loop_prepare_for_unroll(loop
);
294 nir_block
*header_blk
= nir_loop_first_block(loop
);
296 nir_cf_list lp_header
;
297 nir_cf_list limit_break_list
;
298 unsigned num_times_to_clone
;
299 if (limiting_term_second
) {
300 /* Pluck out the loop header */
301 nir_cf_extract(&lp_header
, nir_before_block(header_blk
),
302 nir_before_cf_node(&unlimit_term
->nif
->cf_node
));
304 /* We need some special handling when its the second terminator causing
305 * us to exit the loop for example:
307 * for (int i = 0; i < uniform_lp_count; i++) {
308 * colour = vec4(0.0, 1.0, 0.0, 1.0);
313 * ... any further code is unreachable after i == 1 ...
316 nir_cf_list after_lt
;
317 nir_if
*limit_if
= limiting_term
->nif
;
318 nir_cf_extract(&after_lt
, nir_after_cf_node(&limit_if
->cf_node
),
319 nir_after_block(nir_loop_last_block(loop
)));
320 move_cf_list_into_loop_term(&after_lt
, limiting_term
);
322 /* Because the trip count is the number of times we pass over the entire
323 * loop before hitting a break when the second terminator is the
324 * limiting terminator we can actually execute code inside the loop when
325 * trip count == 0 e.g. the code above the break. So we need to bump
326 * the trip_count in order for the code below to clone anything. When
327 * trip count == 1 we execute the code above the break twice and the
328 * code below it once so we need clone things twice and so on.
330 num_times_to_clone
= loop
->info
->max_trip_count
+ 1;
332 /* Pluck out the loop header */
333 nir_cf_extract(&lp_header
, nir_before_block(header_blk
),
334 nir_before_cf_node(&limiting_term
->nif
->cf_node
));
336 nir_block
*first_break_block
;
337 nir_block
*first_continue_block
;
338 get_first_blocks_in_terminator(limiting_term
, &first_break_block
,
339 &first_continue_block
);
341 /* Remove the break then extract instructions from the break block so we
342 * can insert them in the innermost else of the unrolled loop.
344 nir_instr
*break_instr
= nir_block_last_instr(limiting_term
->break_block
);
345 nir_instr_remove(break_instr
);
346 nir_cf_extract(&limit_break_list
, nir_before_block(first_break_block
),
347 nir_after_block(limiting_term
->break_block
));
349 nir_cf_list continue_list
;
350 nir_cf_extract(&continue_list
, nir_before_block(first_continue_block
),
351 nir_after_block(limiting_term
->continue_from_block
));
353 nir_cf_reinsert(&continue_list
,
354 nir_after_cf_node(&limiting_term
->nif
->cf_node
));
356 nir_cf_node_remove(&limiting_term
->nif
->cf_node
);
358 num_times_to_clone
= loop
->info
->max_trip_count
;
361 /* In the terminator that we have no trip count for move everything after
362 * the terminator into the continue from branch.
364 nir_cf_list loop_end
;
365 nir_cf_extract(&loop_end
, nir_after_cf_node(&unlimit_term
->nif
->cf_node
),
366 nir_after_block(nir_loop_last_block(loop
)));
367 move_cf_list_into_loop_term(&loop_end
, unlimit_term
);
369 /* Pluck out the loop body. */
370 nir_cf_list loop_body
;
371 nir_cf_extract(&loop_body
, nir_before_block(nir_loop_first_block(loop
)),
372 nir_after_block(nir_loop_last_block(loop
)));
374 struct hash_table
*remap_table
=
375 _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
376 _mesa_key_pointer_equal
);
378 /* Set unroll_loc to the loop as we will insert the unrolled loop before it
380 nir_cf_node
*unroll_loc
= &loop
->cf_node
;
382 /* Temp lists to store the cloned loop as we unroll */
383 nir_cf_list unrolled_lp_body
;
385 for (unsigned i
= 0; i
< num_times_to_clone
; i
++) {
388 get_complex_unroll_insert_location(unroll_loc
,
389 unlimit_term
->continue_from_then
);
391 /* Clone loop header and insert in if branch */
392 nir_cf_list_clone_and_reinsert(&lp_header
, loop
->cf_node
.parent
,
393 cursor
, remap_table
);
396 get_complex_unroll_insert_location(unroll_loc
,
397 unlimit_term
->continue_from_then
);
399 /* Clone loop body */
400 nir_cf_list_clone(&unrolled_lp_body
, &loop_body
, loop
->cf_node
.parent
,
403 unroll_loc
= exec_node_data(nir_cf_node
,
404 exec_list_get_tail(&unrolled_lp_body
.list
),
406 assert(unroll_loc
->type
== nir_cf_node_block
&&
407 exec_list_is_empty(&nir_cf_node_as_block(unroll_loc
)->instr_list
));
409 /* Get the unrolled if node */
410 unroll_loc
= nir_cf_node_prev(unroll_loc
);
412 /* Insert unrolled loop body */
413 nir_cf_reinsert(&unrolled_lp_body
, cursor
);
416 if (!limiting_term_second
) {
417 assert(unroll_loc
->type
== nir_cf_node_if
);
420 get_complex_unroll_insert_location(unroll_loc
,
421 unlimit_term
->continue_from_then
);
423 /* Clone loop header and insert in if branch */
424 nir_cf_list_clone_and_reinsert(&lp_header
, loop
->cf_node
.parent
,
425 cursor
, remap_table
);
428 get_complex_unroll_insert_location(unroll_loc
,
429 unlimit_term
->continue_from_then
);
431 /* Clone so things get properly remapped, and insert break block from
432 * the limiting terminator.
434 nir_cf_list_clone_and_reinsert(&limit_break_list
, loop
->cf_node
.parent
,
435 cursor
, remap_table
);
437 nir_cf_delete(&limit_break_list
);
440 /* The loop has been unrolled so remove it. */
441 nir_cf_node_remove(&loop
->cf_node
);
443 /* Delete the original loop header and body */
444 nir_cf_delete(&lp_header
);
445 nir_cf_delete(&loop_body
);
447 _mesa_hash_table_destroy(remap_table
, NULL
);
450 /* Unrolls the classic wrapper loops e.g
457 wrapper_unroll(nir_loop
*loop
)
459 if (!list_empty(&loop
->info
->loop_terminator_list
)) {
461 /* Unrolling a loop with a large number of exits can result in a
462 * large inrease in register pressure. For now we just skip
463 * unrolling if we have more than 3 exits (not including the break
464 * at the end of the loop).
466 * TODO: Most loops that fit this pattern are simply switch
467 * statements that are converted to a loop to take advantage of
468 * exiting jump instruction handling. In this case we could make
469 * use of a binary seach pattern like we do in
470 * nir_lower_indirect_derefs(), this should allow us to unroll the
471 * loops in an optimal way and should also avoid some of the
472 * register pressure that comes from simply nesting the
473 * terminators one after the other.
475 if (list_length(&loop
->info
->loop_terminator_list
) > 3)
478 loop_prepare_for_unroll(loop
);
480 nir_cursor loop_end
= nir_after_block(nir_loop_last_block(loop
));
481 list_for_each_entry(nir_loop_terminator
, terminator
,
482 &loop
->info
->loop_terminator_list
,
483 loop_terminator_link
) {
485 /* Remove break from the terminator */
486 nir_instr
*break_instr
=
487 nir_block_last_instr(terminator
->break_block
);
488 nir_instr_remove(break_instr
);
490 /* Pluck out the loop body. */
491 nir_cf_list loop_body
;
492 nir_cf_extract(&loop_body
,
493 nir_after_cf_node(&terminator
->nif
->cf_node
),
496 /* Reinsert loop body into continue from block */
497 nir_cf_reinsert(&loop_body
,
498 nir_after_block(terminator
->continue_from_block
));
500 loop_end
= terminator
->continue_from_then
?
501 nir_after_block(nir_if_last_then_block(terminator
->nif
)) :
502 nir_after_block(nir_if_last_else_block(terminator
->nif
));
505 nir_block
*blk_after_loop
=
506 nir_cursor_current_block(nir_after_cf_node(&loop
->cf_node
));
508 /* There may still be some single src phis following the loop that
509 * have not yet been cleaned up by another pass. Tidy those up
510 * before unrolling the loop.
512 nir_foreach_instr_safe(instr
, blk_after_loop
) {
513 if (instr
->type
!= nir_instr_type_phi
)
516 nir_phi_instr
*phi
= nir_instr_as_phi(instr
);
517 assert(exec_list_length(&phi
->srcs
) == 1);
519 nir_phi_src
*phi_src
=
520 exec_node_data(nir_phi_src
, exec_list_get_head(&phi
->srcs
), node
);
522 nir_ssa_def_rewrite_uses(&phi
->dest
.ssa
, phi_src
->src
);
523 nir_instr_remove(instr
);
526 /* Remove break at end of the loop */
527 nir_block
*last_loop_blk
= nir_loop_last_block(loop
);
528 nir_instr
*break_instr
= nir_block_last_instr(last_loop_blk
);
529 nir_instr_remove(break_instr
);
532 /* Pluck out the loop body. */
533 nir_cf_list loop_body
;
534 nir_cf_extract(&loop_body
, nir_before_block(nir_loop_first_block(loop
)),
535 nir_after_block(nir_loop_last_block(loop
)));
537 /* Reinsert loop body after the loop */
538 nir_cf_reinsert(&loop_body
, nir_after_cf_node(&loop
->cf_node
));
540 /* The loop has been unrolled so remove it. */
541 nir_cf_node_remove(&loop
->cf_node
);
547 is_loop_small_enough_to_unroll(nir_shader
*shader
, nir_loop_info
*li
)
549 unsigned max_iter
= shader
->options
->max_unroll_iterations
;
551 if (li
->max_trip_count
> max_iter
)
554 if (li
->force_unroll
)
557 bool loop_not_too_large
=
558 li
->num_instructions
* li
->max_trip_count
<= max_iter
* LOOP_UNROLL_LIMIT
;
560 return loop_not_too_large
;
564 process_loops(nir_shader
*sh
, nir_cf_node
*cf_node
, bool *has_nested_loop_out
)
566 bool progress
= false;
567 bool has_nested_loop
= false;
570 switch (cf_node
->type
) {
571 case nir_cf_node_block
:
573 case nir_cf_node_if
: {
574 nir_if
*if_stmt
= nir_cf_node_as_if(cf_node
);
575 foreach_list_typed_safe(nir_cf_node
, nested_node
, node
, &if_stmt
->then_list
)
576 progress
|= process_loops(sh
, nested_node
, has_nested_loop_out
);
577 foreach_list_typed_safe(nir_cf_node
, nested_node
, node
, &if_stmt
->else_list
)
578 progress
|= process_loops(sh
, nested_node
, has_nested_loop_out
);
581 case nir_cf_node_loop
: {
582 loop
= nir_cf_node_as_loop(cf_node
);
583 foreach_list_typed_safe(nir_cf_node
, nested_node
, node
, &loop
->body
)
584 progress
|= process_loops(sh
, nested_node
, &has_nested_loop
);
589 unreachable("unknown cf node type");
592 /* Don't attempt to unroll a second inner loop in this pass, wait until the
593 * next pass as we have altered the cf.
597 /* Check for the classic
603 * that is used to wrap multi-line macros. GLSL IR also wraps switch
604 * statements in a loop like this.
606 if (loop
->info
->limiting_terminator
== NULL
&&
607 !loop
->info
->complex_loop
) {
609 nir_block
*last_loop_blk
= nir_loop_last_block(loop
);
610 if (!nir_block_ends_in_break(last_loop_blk
))
613 progress
= wrapper_unroll(loop
);
618 if (has_nested_loop
|| loop
->info
->limiting_terminator
== NULL
)
621 if (!is_loop_small_enough_to_unroll(sh
, loop
->info
))
624 if (loop
->info
->exact_trip_count_known
) {
628 /* Attempt to unroll loops with two terminators. */
629 unsigned num_lt
= list_length(&loop
->info
->loop_terminator_list
);
631 bool limiting_term_second
= true;
632 nir_loop_terminator
*terminator
=
633 list_first_entry(&loop
->info
->loop_terminator_list
,
634 nir_loop_terminator
, loop_terminator_link
);
637 if (terminator
->nif
== loop
->info
->limiting_terminator
->nif
) {
638 limiting_term_second
= false;
640 list_last_entry(&loop
->info
->loop_terminator_list
,
641 nir_loop_terminator
, loop_terminator_link
);
644 /* If the first terminator has a trip count of zero and is the
645 * limiting terminator just do a simple unroll as the second
646 * terminator can never be reached.
648 if (loop
->info
->max_trip_count
== 0 && !limiting_term_second
) {
651 complex_unroll(loop
, terminator
, limiting_term_second
);
659 *has_nested_loop_out
= true;
664 nir_opt_loop_unroll_impl(nir_function_impl
*impl
,
665 nir_variable_mode indirect_mask
)
667 bool progress
= false;
668 nir_metadata_require(impl
, nir_metadata_loop_analysis
, indirect_mask
);
669 nir_metadata_require(impl
, nir_metadata_block_index
);
671 foreach_list_typed_safe(nir_cf_node
, node
, node
, &impl
->body
) {
672 bool has_nested_loop
= false;
673 progress
|= process_loops(impl
->function
->shader
, node
,
678 nir_lower_regs_to_ssa_impl(impl
);
684 * indirect_mask specifies which type of indirectly accessed variables
685 * should force loop unrolling.
688 nir_opt_loop_unroll(nir_shader
*shader
, nir_variable_mode indirect_mask
)
690 bool progress
= false;
692 nir_foreach_function(function
, shader
) {
693 if (function
->impl
) {
694 progress
|= nir_opt_loop_unroll_impl(function
->impl
, indirect_mask
);