1 /* Loop header copying on trees.
2 Copyright (C) 2004-2022 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
22 #include "coretypes.h"
27 #include "tree-pass.h"
28 #include "gimple-ssa.h"
29 #include "gimple-iterator.h"
31 #include "tree-into-ssa.h"
33 #include "tree-inline.h"
34 #include "tree-ssa-threadedge.h"
35 #include "tree-ssa-sccvn.h"
36 #include "tree-phinodes.h"
37 #include "ssa-iterators.h"
38 #include "value-range.h"
39 #include "gimple-range.h"
40 #include "gimple-range-path.h"
43 /* Duplicates headers of loops if they are small enough, so that the statements
44 in the loop body are always executed when the loop is entered. This
45 increases effectiveness of code motion optimizations, and reduces the need
46 for loop preconditioning. */
48 /* Given a path through edge E, whose last statement is COND, return
49 the range of the solved conditional in R. */
52 edge_range_query (irange
&r
, edge e
, gcond
*cond
, gimple_ranger
&ranger
)
54 auto_vec
<basic_block
> path (2);
55 path
.safe_push (e
->dest
);
56 path
.safe_push (e
->src
);
57 path_range_query
query (ranger
, path
);
58 if (!query
.range_of_stmt (r
, cond
))
59 r
.set_varying (boolean_type_node
);
62 /* Return true if the condition on the first iteration of the loop can
63 be statically determined. */
66 entry_loop_condition_is_static (class loop
*l
, gimple_ranger
*ranger
)
68 edge e
= loop_preheader_edge (l
);
69 gcond
*last
= safe_dyn_cast
<gcond
*> (last_stmt (e
->dest
));
75 extract_true_false_edges_from_block (e
->dest
, &true_e
, &false_e
);
77 /* If neither edge is the exit edge, this is not a case we'd like to
79 if (!loop_exit_edge_p (l
, true_e
) && !loop_exit_edge_p (l
, false_e
))
82 tree desired_static_value
;
83 if (loop_exit_edge_p (l
, true_e
))
84 desired_static_value
= boolean_false_node
;
86 desired_static_value
= boolean_true_node
;
89 edge_range_query (r
, e
, last
, *ranger
);
90 return r
== int_range
<2> (desired_static_value
, desired_static_value
);
93 /* Check whether we should duplicate HEADER of LOOP. At most *LIMIT
94 instructions should be duplicated, limit is decreased by the actual
98 should_duplicate_loop_header_p (basic_block header
, class loop
*loop
,
101 gimple_stmt_iterator bsi
;
103 gcc_assert (!header
->aux
);
105 gcc_assert (EDGE_COUNT (header
->succs
) > 0);
106 if (single_succ_p (header
))
108 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
110 " Not duplicating bb %i: it is single succ.\n",
115 if (flow_bb_inside_loop_p (loop
, EDGE_SUCC (header
, 0)->dest
)
116 && flow_bb_inside_loop_p (loop
, EDGE_SUCC (header
, 1)->dest
))
118 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
120 " Not duplicating bb %i: both successors are in loop.\n",
125 /* If this is not the original loop header, we want it to have just
126 one predecessor in order to match the && pattern. */
127 if (header
!= loop
->header
&& !single_pred_p (header
))
129 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
131 " Not duplicating bb %i: it has mutiple predecestors.\n",
136 gcond
*last
= safe_dyn_cast
<gcond
*> (last_stmt (header
));
139 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
141 " Not duplicating bb %i: it does not end by conditional.\n",
146 for (gphi_iterator psi
= gsi_start_phis (header
); !gsi_end_p (psi
);
149 gphi
*phi
= psi
.phi ();
150 tree res
= gimple_phi_result (phi
);
151 if (INTEGRAL_TYPE_P (TREE_TYPE (res
))
152 || POINTER_TYPE_P (TREE_TYPE (res
)))
153 gimple_set_uid (phi
, 1 /* IV */);
155 gimple_set_uid (phi
, 0);
158 /* Count number of instructions and punt on calls.
159 Populate stmts INV/IV flag to later apply heuristics to the
160 kind of conditions we want to copy. */
161 for (bsi
= gsi_start_bb (header
); !gsi_end_p (bsi
); gsi_next (&bsi
))
163 gimple
*last
= gsi_stmt (bsi
);
165 if (gimple_code (last
) == GIMPLE_LABEL
)
168 if (is_gimple_debug (last
))
171 if (gimple_code (last
) == GIMPLE_CALL
172 && (!gimple_inexpensive_call_p (as_a
<gcall
*> (last
))
173 /* IFN_LOOP_DIST_ALIAS means that inner loop is distributed
174 at current loop's header. Don't copy in this case. */
175 || gimple_call_internal_p (last
, IFN_LOOP_DIST_ALIAS
)))
177 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
179 " Not duplicating bb %i: it contains call.\n",
184 *limit
-= estimate_num_insns (last
, &eni_size_weights
);
187 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
189 " Not duplicating bb %i contains too many insns.\n",
194 /* Classify the stmt based on whether its computation is based
195 on a IV or whether it is invariant in the loop. */
196 gimple_set_uid (last
, 0);
197 if (!gimple_vuse (last
))
203 FOR_EACH_SSA_TREE_OPERAND (op
, last
, i
, SSA_OP_USE
)
204 if (!SSA_NAME_IS_DEFAULT_DEF (op
)
205 && flow_bb_inside_loop_p (loop
,
206 gimple_bb (SSA_NAME_DEF_STMT (op
))))
208 if (!(gimple_uid (SSA_NAME_DEF_STMT (op
)) & 2 /* INV */))
210 if (gimple_uid (SSA_NAME_DEF_STMT (op
)) & 1 /* IV */)
213 gimple_set_uid (last
, (iv
? 1 : 0) | (inv
? 2 : 0));
217 /* If the condition tests a non-IV loop variant we do not want to rotate
218 the loop further. Unless this is the original loop header. */
219 tree lhs
= gimple_cond_lhs (last
);
220 tree rhs
= gimple_cond_rhs (last
);
221 if (header
!= loop
->header
222 && ((TREE_CODE (lhs
) == SSA_NAME
223 && !SSA_NAME_IS_DEFAULT_DEF (lhs
)
224 && flow_bb_inside_loop_p (loop
, gimple_bb (SSA_NAME_DEF_STMT (lhs
)))
225 && gimple_uid (SSA_NAME_DEF_STMT (lhs
)) == 0)
226 || (TREE_CODE (rhs
) == SSA_NAME
227 && !SSA_NAME_IS_DEFAULT_DEF (rhs
)
228 && flow_bb_inside_loop_p (loop
,
229 gimple_bb (SSA_NAME_DEF_STMT (rhs
)))
230 && gimple_uid (SSA_NAME_DEF_STMT (rhs
)) == 0)))
232 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
234 " Not duplicating bb %i: condition based on non-IV loop"
235 " variant.\n", header
->index
);
242 /* Checks whether LOOP is a do-while style loop. */
245 do_while_loop_p (class loop
*loop
)
247 gimple
*stmt
= last_stmt (loop
->latch
);
249 /* If the latch of the loop is not empty, it is not a do-while loop. */
251 && gimple_code (stmt
) != GIMPLE_LABEL
)
253 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
255 "Loop %i is not do-while loop: latch is not empty.\n",
260 /* If the latch does not have a single predecessor, it is not a
262 if (!single_pred_p (loop
->latch
))
264 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
266 "Loop %i is not do-while loop: latch has multiple "
267 "predecessors.\n", loop
->num
);
271 /* If the latch predecessor doesn't exit the loop, it is not a
273 if (!loop_exits_from_bb_p (loop
, single_pred (loop
->latch
)))
275 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
277 "Loop %i is not do-while loop: latch predecessor "
278 "does not exit loop.\n", loop
->num
);
282 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
283 fprintf (dump_file
, "Loop %i is do-while loop\n", loop
->num
);
290 /* Common superclass for both header-copying phases. */
291 class ch_base
: public gimple_opt_pass
294 ch_base (pass_data data
, gcc::context
*ctxt
)
295 : gimple_opt_pass (data
, ctxt
)
298 /* Copies headers of all loops in FUN for which process_loop_p is true. */
299 unsigned int copy_headers (function
*fun
);
301 /* Return true to copy headers of LOOP or false to skip. */
302 virtual bool process_loop_p (class loop
*loop
) = 0;
305 const pass_data pass_data_ch
=
307 GIMPLE_PASS
, /* type */
309 OPTGROUP_LOOP
, /* optinfo_flags */
310 TV_TREE_CH
, /* tv_id */
311 ( PROP_cfg
| PROP_ssa
), /* properties_required */
312 0, /* properties_provided */
313 0, /* properties_destroyed */
314 0, /* todo_flags_start */
315 0, /* todo_flags_finish */
318 class pass_ch
: public ch_base
321 pass_ch (gcc::context
*ctxt
)
322 : ch_base (pass_data_ch
, ctxt
)
325 /* opt_pass methods: */
326 bool gate (function
*) final override
{ return flag_tree_ch
!= 0; }
328 /* Initialize and finalize loop structures, copying headers inbetween. */
329 unsigned int execute (function
*) final override
;
331 opt_pass
* clone () final override
{ return new pass_ch (m_ctxt
); }
334 /* ch_base method: */
335 bool process_loop_p (class loop
*loop
) final override
;
338 const pass_data pass_data_ch_vect
=
340 GIMPLE_PASS
, /* type */
341 "ch_vect", /* name */
342 OPTGROUP_LOOP
, /* optinfo_flags */
343 TV_TREE_CH
, /* tv_id */
344 ( PROP_cfg
| PROP_ssa
), /* properties_required */
345 0, /* properties_provided */
346 0, /* properties_destroyed */
347 0, /* todo_flags_start */
348 0, /* todo_flags_finish */
351 /* This is a more aggressive version of the same pass, designed to run just
352 before if-conversion and vectorization, to put more loops into the form
353 required for those phases. */
354 class pass_ch_vect
: public ch_base
357 pass_ch_vect (gcc::context
*ctxt
)
358 : ch_base (pass_data_ch_vect
, ctxt
)
361 /* opt_pass methods: */
362 bool gate (function
*fun
) final override
364 return flag_tree_ch
!= 0
365 && (flag_tree_loop_vectorize
!= 0 || fun
->has_force_vectorize_loops
);
368 /* Just copy headers, no initialization/finalization of loop structures. */
369 unsigned int execute (function
*) final override
;
372 /* ch_base method: */
373 bool process_loop_p (class loop
*loop
) final override
;
374 }; // class pass_ch_vect
376 /* For all loops, copy the condition at the end of the loop body in front
377 of the loop. This is beneficial since it increases efficiency of
378 code motion optimizations. It also saves one jump on entry to the loop. */
381 ch_base::copy_headers (function
*fun
)
385 basic_block
*bbs
, *copied_bbs
;
388 bool changed
= false;
390 if (number_of_loops (fun
) <= 1)
393 bbs
= XNEWVEC (basic_block
, n_basic_blocks_for_fn (fun
));
394 copied_bbs
= XNEWVEC (basic_block
, n_basic_blocks_for_fn (fun
));
395 bbs_size
= n_basic_blocks_for_fn (fun
);
397 auto_vec
<loop_p
> candidates
;
398 auto_vec
<std::pair
<edge
, loop_p
> > copied
;
400 mark_dfs_back_edges ();
401 gimple_ranger
*ranger
= new gimple_ranger
;
402 for (auto loop
: loops_list (cfun
, 0))
404 int initial_limit
= param_max_loop_header_insns
;
405 int remaining_limit
= initial_limit
;
406 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
408 "Analyzing loop %i\n", loop
->num
);
410 header
= loop
->header
;
412 /* If the loop is already a do-while style one (either because it was
413 written as such, or because jump threading transformed it into one),
414 we might be in fact peeling the first iteration of the loop. This
415 in general is not a good idea. Also avoid touching infinite loops. */
416 if (!loop_has_exit_edges (loop
)
417 || !process_loop_p (loop
))
420 /* Avoid loop header copying when optimizing for size unless we can
421 determine that the loop condition is static in the first
423 if (optimize_loop_for_size_p (loop
)
424 && !loop
->force_vectorize
425 && !entry_loop_condition_is_static (loop
, ranger
))
427 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
429 " Not duplicating bb %i: optimizing for size.\n",
434 if (should_duplicate_loop_header_p (header
, loop
, &remaining_limit
))
435 candidates
.safe_push (loop
);
437 /* Do not use ranger after we change the IL and not have updated SSA. */
440 for (auto loop
: candidates
)
442 int initial_limit
= param_max_loop_header_insns
;
443 int remaining_limit
= initial_limit
;
444 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
446 "Copying headers of loop %i\n", loop
->num
);
448 header
= loop
->header
;
450 /* Iterate the header copying up to limit; this takes care of the cases
451 like while (a && b) {...}, where we want to have both of the conditions
452 copied. TODO -- handle while (a || b) - like cases, by not requiring
453 the header to have just a single successor and copying up to
458 while (should_duplicate_loop_header_p (header
, loop
, &remaining_limit
))
460 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
461 fprintf (dump_file
, " Will duplicate bb %i\n", header
->index
);
463 /* Find a successor of header that is inside a loop; i.e. the new
464 header after the condition is copied. */
465 if (flow_bb_inside_loop_p (loop
, EDGE_SUCC (header
, 0)->dest
))
466 exit
= EDGE_SUCC (header
, 0);
468 exit
= EDGE_SUCC (header
, 1);
469 bbs
[n_bbs
++] = header
;
470 gcc_assert (bbs_size
> n_bbs
);
477 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
479 "Duplicating header of the loop %d up to edge %d->%d,"
481 loop
->num
, exit
->src
->index
, exit
->dest
->index
,
482 initial_limit
- remaining_limit
);
484 /* Ensure that the header will have just the latch as a predecessor
486 if (!single_pred_p (exit
->dest
))
487 exit
= single_pred_edge (split_edge (exit
));
489 entry
= loop_preheader_edge (loop
);
491 propagate_threaded_block_debug_into (exit
->dest
, entry
->dest
);
492 if (!gimple_duplicate_sese_region (entry
, exit
, bbs
, n_bbs
, copied_bbs
,
495 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
496 fprintf (dump_file
, "Duplication failed.\n");
499 copied
.safe_push (std::make_pair (entry
, loop
));
501 /* If the loop has the form "for (i = j; i < j + 10; i++)" then
502 this copying can introduce a case where we rely on undefined
503 signed overflow to eliminate the preheader condition, because
504 we assume that "j < j + 10" is true. We don't want to warn
505 about that case for -Wstrict-overflow, because in general we
506 don't warn about overflow involving loops. Prevent the
507 warning by setting the no_warning flag in the condition. */
508 if (warn_strict_overflow
> 0)
512 for (i
= 0; i
< n_bbs
; ++i
)
514 gimple_stmt_iterator bsi
;
516 for (bsi
= gsi_start_bb (copied_bbs
[i
]);
520 gimple
*stmt
= gsi_stmt (bsi
);
521 if (gimple_code (stmt
) == GIMPLE_COND
)
523 tree lhs
= gimple_cond_lhs (stmt
);
524 if (gimple_cond_code (stmt
) != EQ_EXPR
525 && gimple_cond_code (stmt
) != NE_EXPR
526 && INTEGRAL_TYPE_P (TREE_TYPE (lhs
))
527 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (lhs
)))
528 suppress_warning (stmt
, OPT_Wstrict_overflow_
);
530 else if (is_gimple_assign (stmt
))
532 enum tree_code rhs_code
= gimple_assign_rhs_code (stmt
);
533 tree rhs1
= gimple_assign_rhs1 (stmt
);
534 if (TREE_CODE_CLASS (rhs_code
) == tcc_comparison
535 && rhs_code
!= EQ_EXPR
536 && rhs_code
!= NE_EXPR
537 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1
))
538 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (rhs1
)))
539 suppress_warning (stmt
, OPT_Wstrict_overflow_
);
545 /* Ensure that the latch and the preheader is simple (we know that they
546 are not now, since there was the loop exit condition. */
547 split_edge (loop_preheader_edge (loop
));
548 split_edge (loop_latch_edge (loop
));
550 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
552 if (do_while_loop_p (loop
))
553 fprintf (dump_file
, "Loop %d is now do-while loop.\n", loop
->num
);
555 fprintf (dump_file
, "Loop %d is still not do-while loop.\n",
564 update_ssa (TODO_update_ssa
);
565 /* After updating SSA form perform CSE on the loop header
566 copies. This is esp. required for the pass before
567 vectorization since nothing cleans up copied exit tests
568 that can now be simplified. CSE from the entry of the
569 region we copied till all loop exit blocks but not
570 entering the loop itself. */
571 for (unsigned i
= 0; i
< copied
.length (); ++i
)
573 edge entry
= copied
[i
].first
;
574 loop_p loop
= copied
[i
].second
;
575 auto_vec
<edge
> exit_edges
= get_loop_exit_edges (loop
);
576 bitmap exit_bbs
= BITMAP_ALLOC (NULL
);
577 for (unsigned j
= 0; j
< exit_edges
.length (); ++j
)
578 bitmap_set_bit (exit_bbs
, exit_edges
[j
]->dest
->index
);
579 bitmap_set_bit (exit_bbs
, loop
->header
->index
);
580 do_rpo_vn (cfun
, entry
, exit_bbs
);
581 BITMAP_FREE (exit_bbs
);
587 return changed
? TODO_cleanup_cfg
: 0;
590 /* Initialize the loop structures we need, and finalize after. */
593 pass_ch::execute (function
*fun
)
595 loop_optimizer_init (LOOPS_HAVE_PREHEADERS
596 | LOOPS_HAVE_SIMPLE_LATCHES
597 | LOOPS_HAVE_RECORDED_EXITS
);
599 unsigned int res
= copy_headers (fun
);
601 loop_optimizer_finalize ();
605 /* Assume an earlier phase has already initialized all the loop structures that
606 we need here (and perhaps others too), and that these will be finalized by
610 pass_ch_vect::execute (function
*fun
)
612 return copy_headers (fun
);
615 /* Apply header copying according to a very simple test of do-while shape. */
618 pass_ch::process_loop_p (class loop
*loop
)
620 return !do_while_loop_p (loop
);
623 /* Apply header-copying to loops where we might enable vectorization. */
626 pass_ch_vect::process_loop_p (class loop
*loop
)
628 if (!flag_tree_loop_vectorize
&& !loop
->force_vectorize
)
631 if (loop
->dont_vectorize
)
634 /* The vectorizer won't handle anything with multiple exits, so skip. */
635 edge exit
= single_exit (loop
);
639 if (!do_while_loop_p (loop
))
648 make_pass_ch_vect (gcc::context
*ctxt
)
650 return new pass_ch_vect (ctxt
);
654 make_pass_ch (gcc::context
*ctxt
)
656 return new pass_ch (ctxt
);