PR libstdc++/83279 handle sendfile not copying entire file
[official-gcc.git] / gcc / tree-cfgcleanup.c
bloba0e5797ec0ecb8b413b8aad19ffc4149e87676a4
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2017 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
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/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "diagnostic-core.h"
31 #include "fold-const.h"
32 #include "cfganal.h"
33 #include "cfgcleanup.h"
34 #include "tree-eh.h"
35 #include "gimplify.h"
36 #include "gimple-iterator.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-manip.h"
39 #include "tree-dfa.h"
40 #include "tree-ssa.h"
41 #include "cfgloop.h"
42 #include "tree-scalar-evolution.h"
43 #include "gimple-match.h"
44 #include "gimple-fold.h"
45 #include "tree-ssa-loop-niter.h"
48 /* The set of blocks in that at least one of the following changes happened:
49 -- the statement at the end of the block was changed
50 -- the block was newly created
51 -- the set of the predecessors of the block changed
52 -- the set of the successors of the block changed
53 ??? Maybe we could track these changes separately, since they determine
54 what cleanups it makes sense to try on the block. */
55 bitmap cfgcleanup_altered_bbs;
57 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
59 static bool
60 remove_fallthru_edge (vec<edge, va_gc> *ev)
62 edge_iterator ei;
63 edge e;
65 FOR_EACH_EDGE (e, ei, ev)
66 if ((e->flags & EDGE_FALLTHRU) != 0)
68 if (e->flags & EDGE_COMPLEX)
69 e->flags &= ~EDGE_FALLTHRU;
70 else
71 remove_edge_and_dominated_blocks (e);
72 return true;
74 return false;
77 /* Convert a SWTCH with single non-default case to gcond and replace it
78 at GSI. */
80 static bool
81 convert_single_case_switch (gswitch *swtch, gimple_stmt_iterator &gsi)
83 if (gimple_switch_num_labels (swtch) != 2)
84 return false;
86 tree index = gimple_switch_index (swtch);
87 tree default_label = CASE_LABEL (gimple_switch_default_label (swtch));
88 tree label = gimple_switch_label (swtch, 1);
89 tree low = CASE_LOW (label);
90 tree high = CASE_HIGH (label);
92 basic_block default_bb = label_to_block_fn (cfun, default_label);
93 basic_block case_bb = label_to_block_fn (cfun, CASE_LABEL (label));
95 basic_block bb = gimple_bb (swtch);
96 gcond *cond;
98 /* Replace switch statement with condition statement. */
99 if (high)
101 tree lhs, rhs;
102 generate_range_test (bb, index, low, high, &lhs, &rhs);
103 cond = gimple_build_cond (LE_EXPR, lhs, rhs, NULL_TREE, NULL_TREE);
105 else
106 cond = gimple_build_cond (EQ_EXPR, index,
107 fold_convert (TREE_TYPE (index), low),
108 NULL_TREE, NULL_TREE);
110 gsi_replace (&gsi, cond, true);
112 /* Update edges. */
113 edge case_edge = find_edge (bb, case_bb);
114 edge default_edge = find_edge (bb, default_bb);
116 case_edge->flags |= EDGE_TRUE_VALUE;
117 default_edge->flags |= EDGE_FALSE_VALUE;
118 return true;
121 /* Disconnect an unreachable block in the control expression starting
122 at block BB. */
124 static bool
125 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi)
127 edge taken_edge;
128 bool retval = false;
129 gimple *stmt = gsi_stmt (gsi);
131 if (!single_succ_p (bb))
133 edge e;
134 edge_iterator ei;
135 bool warned;
136 tree val = NULL_TREE;
138 /* Try to convert a switch with just a single non-default case to
139 GIMPLE condition. */
140 if (gimple_code (stmt) == GIMPLE_SWITCH
141 && convert_single_case_switch (as_a<gswitch *> (stmt), gsi))
142 stmt = gsi_stmt (gsi);
144 fold_defer_overflow_warnings ();
145 switch (gimple_code (stmt))
147 case GIMPLE_COND:
149 code_helper rcode;
150 tree ops[3] = {};
151 if (gimple_simplify (stmt, &rcode, ops, NULL, no_follow_ssa_edges,
152 no_follow_ssa_edges)
153 && rcode == INTEGER_CST)
154 val = ops[0];
156 break;
158 case GIMPLE_SWITCH:
159 val = gimple_switch_index (as_a <gswitch *> (stmt));
160 break;
162 default:
165 taken_edge = find_taken_edge (bb, val);
166 if (!taken_edge)
168 fold_undefer_and_ignore_overflow_warnings ();
169 return false;
172 /* Remove all the edges except the one that is always executed. */
173 warned = false;
174 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
176 if (e != taken_edge)
178 if (!warned)
180 fold_undefer_overflow_warnings
181 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
182 warned = true;
185 taken_edge->probability += e->probability;
186 remove_edge_and_dominated_blocks (e);
187 retval = true;
189 else
190 ei_next (&ei);
192 if (!warned)
193 fold_undefer_and_ignore_overflow_warnings ();
195 else
196 taken_edge = single_succ_edge (bb);
198 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
199 gsi_remove (&gsi, true);
200 taken_edge->flags = EDGE_FALLTHRU;
202 return retval;
205 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
206 to updated gimple_call_flags. */
208 static void
209 cleanup_call_ctrl_altering_flag (gimple *bb_end)
211 if (!is_gimple_call (bb_end)
212 || !gimple_call_ctrl_altering_p (bb_end))
213 return;
215 int flags = gimple_call_flags (bb_end);
216 if (((flags & (ECF_CONST | ECF_PURE))
217 && !(flags & ECF_LOOPING_CONST_OR_PURE))
218 || (flags & ECF_LEAF))
219 gimple_call_set_ctrl_altering (bb_end, false);
222 /* Try to remove superfluous control structures in basic block BB. Returns
223 true if anything changes. */
225 static bool
226 cleanup_control_flow_bb (basic_block bb)
228 gimple_stmt_iterator gsi;
229 bool retval = false;
230 gimple *stmt;
232 /* If the last statement of the block could throw and now cannot,
233 we need to prune cfg. */
234 retval |= gimple_purge_dead_eh_edges (bb);
236 gsi = gsi_last_nondebug_bb (bb);
237 if (gsi_end_p (gsi))
238 return retval;
240 stmt = gsi_stmt (gsi);
242 /* Try to cleanup ctrl altering flag for call which ends bb. */
243 cleanup_call_ctrl_altering_flag (stmt);
245 if (gimple_code (stmt) == GIMPLE_COND
246 || gimple_code (stmt) == GIMPLE_SWITCH)
248 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
249 retval |= cleanup_control_expr_graph (bb, gsi);
251 else if (gimple_code (stmt) == GIMPLE_GOTO
252 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
253 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
254 == LABEL_DECL))
256 /* If we had a computed goto which has a compile-time determinable
257 destination, then we can eliminate the goto. */
258 edge e;
259 tree label;
260 edge_iterator ei;
261 basic_block target_block;
263 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
264 /* First look at all the outgoing edges. Delete any outgoing
265 edges which do not go to the right block. For the one
266 edge which goes to the right block, fix up its flags. */
267 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
268 if (DECL_CONTEXT (label) != cfun->decl)
269 return retval;
270 target_block = label_to_block (label);
271 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
273 if (e->dest != target_block)
274 remove_edge_and_dominated_blocks (e);
275 else
277 /* Turn off the EDGE_ABNORMAL flag. */
278 e->flags &= ~EDGE_ABNORMAL;
280 /* And set EDGE_FALLTHRU. */
281 e->flags |= EDGE_FALLTHRU;
282 ei_next (&ei);
286 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
287 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
289 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
290 relevant information we need. */
291 gsi_remove (&gsi, true);
292 retval = true;
295 /* Check for indirect calls that have been turned into
296 noreturn calls. */
297 else if (is_gimple_call (stmt)
298 && gimple_call_noreturn_p (stmt))
300 /* If there are debug stmts after the noreturn call, remove them
301 now, they should be all unreachable anyway. */
302 for (gsi_next (&gsi); !gsi_end_p (gsi); )
303 gsi_remove (&gsi, true);
304 if (remove_fallthru_edge (bb->succs))
305 retval = true;
308 return retval;
311 /* Return true if basic block BB does nothing except pass control
312 flow to another block and that we can safely insert a label at
313 the start of the successor block.
315 As a precondition, we require that BB be not equal to
316 the entry block. */
318 static bool
319 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
321 gimple_stmt_iterator gsi;
322 location_t locus;
324 /* BB must have a single outgoing edge. */
325 if (single_succ_p (bb) != 1
326 /* If PHI_WANTED is false, BB must not have any PHI nodes.
327 Otherwise, BB must have PHI nodes. */
328 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
329 /* BB may not be a predecessor of the exit block. */
330 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
331 /* Nor should this be an infinite loop. */
332 || single_succ (bb) == bb
333 /* BB may not have an abnormal outgoing edge. */
334 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
335 return false;
337 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
339 locus = single_succ_edge (bb)->goto_locus;
341 /* There should not be an edge coming from entry, or an EH edge. */
343 edge_iterator ei;
344 edge e;
346 FOR_EACH_EDGE (e, ei, bb->preds)
347 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
348 return false;
349 /* If goto_locus of any of the edges differs, prevent removing
350 the forwarder block for -O0. */
351 else if (optimize == 0 && e->goto_locus != locus)
352 return false;
355 /* Now walk through the statements backward. We can ignore labels,
356 anything else means this is not a forwarder block. */
357 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
359 gimple *stmt = gsi_stmt (gsi);
361 switch (gimple_code (stmt))
363 case GIMPLE_LABEL:
364 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
365 return false;
366 if (optimize == 0 && gimple_location (stmt) != locus)
367 return false;
368 break;
370 /* ??? For now, hope there's a corresponding debug
371 assignment at the destination. */
372 case GIMPLE_DEBUG:
373 break;
375 default:
376 return false;
380 if (current_loops)
382 basic_block dest;
383 /* Protect loop headers. */
384 if (bb_loop_header_p (bb))
385 return false;
387 dest = EDGE_SUCC (bb, 0)->dest;
388 /* Protect loop preheaders and latches if requested. */
389 if (dest->loop_father->header == dest)
391 if (bb->loop_father == dest->loop_father)
393 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
394 return false;
395 /* If bb doesn't have a single predecessor we'd make this
396 loop have multiple latches. Don't do that if that
397 would in turn require disambiguating them. */
398 return (single_pred_p (bb)
399 || loops_state_satisfies_p
400 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
402 else if (bb->loop_father == loop_outer (dest->loop_father))
403 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
404 /* Always preserve other edges into loop headers that are
405 not simple latches or preheaders. */
406 return false;
410 return true;
413 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
414 those alternatives are equal in each of the PHI nodes, then return
415 true, else return false. */
417 static bool
418 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
420 int n1 = e1->dest_idx;
421 int n2 = e2->dest_idx;
422 gphi_iterator gsi;
424 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
426 gphi *phi = gsi.phi ();
427 tree val1 = gimple_phi_arg_def (phi, n1);
428 tree val2 = gimple_phi_arg_def (phi, n2);
430 gcc_assert (val1 != NULL_TREE);
431 gcc_assert (val2 != NULL_TREE);
433 if (!operand_equal_for_phi_arg_p (val1, val2))
434 return false;
437 return true;
440 /* Removes forwarder block BB. Returns false if this failed. */
442 static bool
443 remove_forwarder_block (basic_block bb)
445 edge succ = single_succ_edge (bb), e, s;
446 basic_block dest = succ->dest;
447 gimple *label;
448 edge_iterator ei;
449 gimple_stmt_iterator gsi, gsi_to;
450 bool can_move_debug_stmts;
452 /* We check for infinite loops already in tree_forwarder_block_p.
453 However it may happen that the infinite loop is created
454 afterwards due to removal of forwarders. */
455 if (dest == bb)
456 return false;
458 /* If the destination block consists of a nonlocal label or is a
459 EH landing pad, do not merge it. */
460 label = first_stmt (dest);
461 if (label)
462 if (glabel *label_stmt = dyn_cast <glabel *> (label))
463 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
464 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
465 return false;
467 /* If there is an abnormal edge to basic block BB, but not into
468 dest, problems might occur during removal of the phi node at out
469 of ssa due to overlapping live ranges of registers.
471 If there is an abnormal edge in DEST, the problems would occur
472 anyway since cleanup_dead_labels would then merge the labels for
473 two different eh regions, and rest of exception handling code
474 does not like it.
476 So if there is an abnormal edge to BB, proceed only if there is
477 no abnormal edge to DEST and there are no phi nodes in DEST. */
478 if (bb_has_abnormal_pred (bb)
479 && (bb_has_abnormal_pred (dest)
480 || !gimple_seq_empty_p (phi_nodes (dest))))
481 return false;
483 /* If there are phi nodes in DEST, and some of the blocks that are
484 predecessors of BB are also predecessors of DEST, check that the
485 phi node arguments match. */
486 if (!gimple_seq_empty_p (phi_nodes (dest)))
488 FOR_EACH_EDGE (e, ei, bb->preds)
490 s = find_edge (e->src, dest);
491 if (!s)
492 continue;
494 if (!phi_alternatives_equal (dest, succ, s))
495 return false;
499 can_move_debug_stmts = MAY_HAVE_DEBUG_STMTS && single_pred_p (dest);
501 basic_block pred = NULL;
502 if (single_pred_p (bb))
503 pred = single_pred (bb);
505 /* Redirect the edges. */
506 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
508 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
510 if (e->flags & EDGE_ABNORMAL)
512 /* If there is an abnormal edge, redirect it anyway, and
513 move the labels to the new block to make it legal. */
514 s = redirect_edge_succ_nodup (e, dest);
516 else
517 s = redirect_edge_and_branch (e, dest);
519 if (s == e)
521 /* Create arguments for the phi nodes, since the edge was not
522 here before. */
523 for (gphi_iterator psi = gsi_start_phis (dest);
524 !gsi_end_p (psi);
525 gsi_next (&psi))
527 gphi *phi = psi.phi ();
528 source_location l = gimple_phi_arg_location_from_edge (phi, succ);
529 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
530 add_phi_arg (phi, unshare_expr (def), s, l);
535 /* Move nonlocal labels and computed goto targets as well as user
536 defined labels and labels with an EH landing pad number to the
537 new block, so that the redirection of the abnormal edges works,
538 jump targets end up in a sane place and debug information for
539 labels is retained.
541 While at that, move any debug stmts that appear before or in between
542 labels, but not those that can only appear after labels. */
543 gsi_to = gsi_start_bb (dest);
544 gsi = gsi_start_bb (bb);
545 gimple_stmt_iterator gsie = gsi_after_labels (bb);
546 while (gsi_stmt (gsi) != gsi_stmt (gsie))
548 tree decl;
549 label = gsi_stmt (gsi);
550 if (is_gimple_debug (label)
551 ? can_move_debug_stmts
552 : ((decl = gimple_label_label (as_a <glabel *> (label))),
553 EH_LANDING_PAD_NR (decl) != 0
554 || DECL_NONLOCAL (decl)
555 || FORCED_LABEL (decl)
556 || !DECL_ARTIFICIAL (decl)))
558 gsi_remove (&gsi, false);
559 gsi_insert_before (&gsi_to, label, GSI_SAME_STMT);
561 else
562 gsi_next (&gsi);
565 /* Move debug statements if the destination has a single predecessor. */
566 if (can_move_debug_stmts && !gsi_end_p (gsi))
568 gcc_assert (gsi_stmt (gsi) == gsi_stmt (gsie));
569 gimple_stmt_iterator gsie_to = gsi_after_labels (dest);
572 gimple *debug = gsi_stmt (gsi);
573 gcc_assert (is_gimple_debug (debug));
574 gsi_remove (&gsi, false);
575 gsi_insert_before (&gsie_to, debug, GSI_SAME_STMT);
577 while (!gsi_end_p (gsi));
580 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
582 /* Update the dominators. */
583 if (dom_info_available_p (CDI_DOMINATORS))
585 basic_block dom, dombb, domdest;
587 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
588 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
589 if (domdest == bb)
591 /* Shortcut to avoid calling (relatively expensive)
592 nearest_common_dominator unless necessary. */
593 dom = dombb;
595 else
596 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
598 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
601 /* Adjust latch infomation of BB's parent loop as otherwise
602 the cfg hook has a hard time not to kill the loop. */
603 if (current_loops && bb->loop_father->latch == bb)
604 bb->loop_father->latch = pred;
606 /* And kill the forwarder block. */
607 delete_basic_block (bb);
609 return true;
612 /* STMT is a call that has been discovered noreturn. Split the
613 block to prepare fixing up the CFG and remove LHS.
614 Return true if cleanup-cfg needs to run. */
616 bool
617 fixup_noreturn_call (gimple *stmt)
619 basic_block bb = gimple_bb (stmt);
620 bool changed = false;
622 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
623 return false;
625 /* First split basic block if stmt is not last. */
626 if (stmt != gsi_stmt (gsi_last_bb (bb)))
628 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
630 /* Don't split if there are only debug stmts
631 after stmt, that can result in -fcompare-debug
632 failures. Remove the debug stmts instead,
633 they should be all unreachable anyway. */
634 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
635 for (gsi_next (&gsi); !gsi_end_p (gsi); )
636 gsi_remove (&gsi, true);
638 else
640 split_block (bb, stmt);
641 changed = true;
645 /* If there is an LHS, remove it, but only if its type has fixed size.
646 The LHS will need to be recreated during RTL expansion and creating
647 temporaries of variable-sized types is not supported. Also don't
648 do this with TREE_ADDRESSABLE types, as assign_temp will abort.
649 Drop LHS regardless of TREE_ADDRESSABLE, if the function call
650 has been changed into a call that does not return a value, like
651 __builtin_unreachable or __cxa_pure_virtual. */
652 tree lhs = gimple_call_lhs (stmt);
653 if (lhs
654 && (should_remove_lhs_p (lhs)
655 || VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))))
657 gimple_call_set_lhs (stmt, NULL_TREE);
659 /* We need to fix up the SSA name to avoid checking errors. */
660 if (TREE_CODE (lhs) == SSA_NAME)
662 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
663 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
664 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
665 set_ssa_default_def (cfun, new_var, lhs);
668 update_stmt (stmt);
671 /* Mark the call as altering control flow. */
672 if (!gimple_call_ctrl_altering_p (stmt))
674 gimple_call_set_ctrl_altering (stmt, true);
675 changed = true;
678 return changed;
681 /* Return true if we want to merge BB1 and BB2 into a single block. */
683 static bool
684 want_merge_blocks_p (basic_block bb1, basic_block bb2)
686 if (!can_merge_blocks_p (bb1, bb2))
687 return false;
688 gimple_stmt_iterator gsi = gsi_last_nondebug_bb (bb1);
689 if (gsi_end_p (gsi) || !stmt_can_terminate_bb_p (gsi_stmt (gsi)))
690 return true;
691 return bb1->count.ok_for_merging (bb2->count);
695 /* Tries to cleanup cfg in basic block BB. Returns true if anything
696 changes. */
698 static bool
699 cleanup_tree_cfg_bb (basic_block bb)
701 if (tree_forwarder_block_p (bb, false)
702 && remove_forwarder_block (bb))
703 return true;
705 /* If there is a merge opportunity with the predecessor
706 do nothing now but wait until we process the predecessor.
707 This happens when we visit BBs in a non-optimal order and
708 avoids quadratic behavior with adjusting stmts BB pointer. */
709 if (single_pred_p (bb)
710 && want_merge_blocks_p (single_pred (bb), bb))
711 /* But make sure we _do_ visit it. When we remove unreachable paths
712 ending in a backedge we fail to mark the destinations predecessors
713 as changed. */
714 bitmap_set_bit (cfgcleanup_altered_bbs, single_pred (bb)->index);
716 /* Merging the blocks may create new opportunities for folding
717 conditional branches (due to the elimination of single-valued PHI
718 nodes). */
719 else if (single_succ_p (bb)
720 && want_merge_blocks_p (bb, single_succ (bb)))
722 merge_blocks (bb, single_succ (bb));
723 return true;
726 return false;
729 /* Do cleanup_control_flow_bb in PRE order. */
731 static bool
732 cleanup_control_flow_pre ()
734 bool retval = false;
736 auto_vec<edge_iterator, 20> stack (n_basic_blocks_for_fn (cfun) + 1);
737 auto_sbitmap visited (last_basic_block_for_fn (cfun));
738 bitmap_clear (visited);
740 stack.quick_push (ei_start (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs));
742 while (! stack.is_empty ())
744 /* Look at the edge on the top of the stack. */
745 edge_iterator ei = stack.last ();
746 basic_block dest = ei_edge (ei)->dest;
748 if (dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
749 && ! bitmap_bit_p (visited, dest->index))
751 bitmap_set_bit (visited, dest->index);
752 retval |= cleanup_control_flow_bb (dest);
753 if (EDGE_COUNT (dest->succs) > 0)
754 stack.quick_push (ei_start (dest->succs));
756 else
758 if (!ei_one_before_end_p (ei))
759 ei_next (&stack.last ());
760 else
761 stack.pop ();
765 return retval;
768 /* Iterate the cfg cleanups, while anything changes. */
770 static bool
771 cleanup_tree_cfg_1 (void)
773 bool retval = false;
774 basic_block bb;
775 unsigned i, n;
777 /* Prepare the worklists of altered blocks. */
778 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
780 /* During forwarder block cleanup, we may redirect edges out of
781 SWITCH_EXPRs, which can get expensive. So we want to enable
782 recording of edge to CASE_LABEL_EXPR. */
783 start_recording_case_labels ();
785 /* We cannot use FOR_EACH_BB_FN for the BB iterations below
786 since the basic blocks may get removed. */
788 /* Start by iterating over all basic blocks in PRE order looking for
789 edge removal opportunities. Do this first because incoming SSA form
790 may be invalid and we want to avoid performing SSA related tasks such
791 as propgating out a PHI node during BB merging in that state. */
792 retval |= cleanup_control_flow_pre ();
794 /* After doing the above SSA form should be valid (or an update SSA
795 should be required). */
797 /* Continue by iterating over all basic blocks looking for BB merging
798 opportunities. */
799 n = last_basic_block_for_fn (cfun);
800 for (i = NUM_FIXED_BLOCKS; i < n; i++)
802 bb = BASIC_BLOCK_FOR_FN (cfun, i);
803 if (bb)
804 retval |= cleanup_tree_cfg_bb (bb);
807 /* Now process the altered blocks, as long as any are available. */
808 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
810 i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
811 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
812 if (i < NUM_FIXED_BLOCKS)
813 continue;
815 bb = BASIC_BLOCK_FOR_FN (cfun, i);
816 if (!bb)
817 continue;
819 retval |= cleanup_control_flow_bb (bb);
820 retval |= cleanup_tree_cfg_bb (bb);
823 end_recording_case_labels ();
824 BITMAP_FREE (cfgcleanup_altered_bbs);
825 return retval;
828 static bool
829 mfb_keep_latches (edge e)
831 return ! dominated_by_p (CDI_DOMINATORS, e->src, e->dest);
834 /* Remove unreachable blocks and other miscellaneous clean up work.
835 Return true if the flowgraph was modified, false otherwise. */
837 static bool
838 cleanup_tree_cfg_noloop (void)
840 bool changed;
842 timevar_push (TV_TREE_CLEANUP_CFG);
844 /* Iterate until there are no more cleanups left to do. If any
845 iteration changed the flowgraph, set CHANGED to true.
847 If dominance information is available, there cannot be any unreachable
848 blocks. */
849 if (!dom_info_available_p (CDI_DOMINATORS))
851 changed = delete_unreachable_blocks ();
852 calculate_dominance_info (CDI_DOMINATORS);
854 else
856 checking_verify_dominators (CDI_DOMINATORS);
857 changed = false;
860 /* Ensure that we have single entries into loop headers. Otherwise
861 if one of the entries is becoming a latch due to CFG cleanup
862 (from formerly being part of an irreducible region) then we mess
863 up loop fixup and associate the old loop with a different region
864 which makes niter upper bounds invalid. See for example PR80549.
865 This needs to be done before we remove trivially dead edges as
866 we need to capture the dominance state before the pending transform. */
867 if (current_loops)
869 loop_p loop;
870 unsigned i;
871 FOR_EACH_VEC_ELT (*get_loops (cfun), i, loop)
872 if (loop && loop->header)
874 basic_block bb = loop->header;
875 edge_iterator ei;
876 edge e;
877 bool found_latch = false;
878 bool any_abnormal = false;
879 unsigned n = 0;
880 /* We are only interested in preserving existing loops, but
881 we need to check whether they are still real and of course
882 if we need to add a preheader at all. */
883 FOR_EACH_EDGE (e, ei, bb->preds)
885 if (e->flags & EDGE_ABNORMAL)
887 any_abnormal = true;
888 break;
890 if (dominated_by_p (CDI_DOMINATORS, e->src, bb))
892 found_latch = true;
893 continue;
895 n++;
897 /* If we have more than one entry to the loop header
898 create a forwarder. */
899 if (found_latch && ! any_abnormal && n > 1)
901 edge fallthru = make_forwarder_block (bb, mfb_keep_latches,
902 NULL);
903 loop->header = fallthru->dest;
904 if (! loops_state_satisfies_p (LOOPS_NEED_FIXUP))
906 /* The loop updating from the CFG hook is incomplete
907 when we have multiple latches, fixup manually. */
908 remove_bb_from_loops (fallthru->src);
909 loop_p cloop = loop;
910 FOR_EACH_EDGE (e, ei, fallthru->src->preds)
911 cloop = find_common_loop (cloop, e->src->loop_father);
912 add_bb_to_loop (fallthru->src, cloop);
918 changed |= cleanup_tree_cfg_1 ();
920 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
922 /* Do not renumber blocks if the SCEV cache is active, it is indexed by
923 basic-block numbers. */
924 if (! scev_initialized_p ())
925 compact_blocks ();
927 checking_verify_flow_info ();
929 timevar_pop (TV_TREE_CLEANUP_CFG);
931 if (changed && current_loops)
933 /* Removing edges and/or blocks may make recorded bounds refer
934 to stale GIMPLE stmts now, so clear them. */
935 free_numbers_of_iterations_estimates (cfun);
936 loops_state_set (LOOPS_NEED_FIXUP);
939 return changed;
942 /* Repairs loop structures. */
944 static void
945 repair_loop_structures (void)
947 bitmap changed_bbs;
948 unsigned n_new_loops;
950 calculate_dominance_info (CDI_DOMINATORS);
952 timevar_push (TV_REPAIR_LOOPS);
953 changed_bbs = BITMAP_ALLOC (NULL);
954 n_new_loops = fix_loop_structure (changed_bbs);
956 /* This usually does nothing. But sometimes parts of cfg that originally
957 were inside a loop get out of it due to edge removal (since they
958 become unreachable by back edges from latch). Also a former
959 irreducible loop can become reducible - in this case force a full
960 rewrite into loop-closed SSA form. */
961 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
962 rewrite_into_loop_closed_ssa (n_new_loops ? NULL : changed_bbs,
963 TODO_update_ssa);
965 BITMAP_FREE (changed_bbs);
967 checking_verify_loop_structure ();
968 scev_reset ();
970 timevar_pop (TV_REPAIR_LOOPS);
973 /* Cleanup cfg and repair loop structures. */
975 bool
976 cleanup_tree_cfg (void)
978 bool changed = cleanup_tree_cfg_noloop ();
980 if (current_loops != NULL
981 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
982 repair_loop_structures ();
984 return changed;
987 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
988 Returns true if successful. */
990 static bool
991 remove_forwarder_block_with_phi (basic_block bb)
993 edge succ = single_succ_edge (bb);
994 basic_block dest = succ->dest;
995 gimple *label;
996 basic_block dombb, domdest, dom;
998 /* We check for infinite loops already in tree_forwarder_block_p.
999 However it may happen that the infinite loop is created
1000 afterwards due to removal of forwarders. */
1001 if (dest == bb)
1002 return false;
1004 /* Removal of forwarders may expose new natural loops and thus
1005 a block may turn into a loop header. */
1006 if (current_loops && bb_loop_header_p (bb))
1007 return false;
1009 /* If the destination block consists of a nonlocal label, do not
1010 merge it. */
1011 label = first_stmt (dest);
1012 if (label)
1013 if (glabel *label_stmt = dyn_cast <glabel *> (label))
1014 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
1015 return false;
1017 /* Record BB's single pred in case we need to update the father
1018 loop's latch information later. */
1019 basic_block pred = NULL;
1020 if (single_pred_p (bb))
1021 pred = single_pred (bb);
1023 /* Redirect each incoming edge to BB to DEST. */
1024 while (EDGE_COUNT (bb->preds) > 0)
1026 edge e = EDGE_PRED (bb, 0), s;
1027 gphi_iterator gsi;
1029 s = find_edge (e->src, dest);
1030 if (s)
1032 /* We already have an edge S from E->src to DEST. If S and
1033 E->dest's sole successor edge have the same PHI arguments
1034 at DEST, redirect S to DEST. */
1035 if (phi_alternatives_equal (dest, s, succ))
1037 e = redirect_edge_and_branch (e, dest);
1038 redirect_edge_var_map_clear (e);
1039 continue;
1042 /* PHI arguments are different. Create a forwarder block by
1043 splitting E so that we can merge PHI arguments on E to
1044 DEST. */
1045 e = single_succ_edge (split_edge (e));
1047 else
1049 /* If we merge the forwarder into a loop header verify if we
1050 are creating another loop latch edge. If so, reset
1051 number of iteration information of the loop. */
1052 if (dest->loop_father->header == dest
1053 && dominated_by_p (CDI_DOMINATORS, e->src, dest))
1055 dest->loop_father->any_upper_bound = false;
1056 dest->loop_father->any_likely_upper_bound = false;
1057 free_numbers_of_iterations_estimates (dest->loop_father);
1061 s = redirect_edge_and_branch (e, dest);
1063 /* redirect_edge_and_branch must not create a new edge. */
1064 gcc_assert (s == e);
1066 /* Add to the PHI nodes at DEST each PHI argument removed at the
1067 destination of E. */
1068 for (gsi = gsi_start_phis (dest);
1069 !gsi_end_p (gsi);
1070 gsi_next (&gsi))
1072 gphi *phi = gsi.phi ();
1073 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
1074 source_location locus = gimple_phi_arg_location_from_edge (phi, succ);
1076 if (TREE_CODE (def) == SSA_NAME)
1078 /* If DEF is one of the results of PHI nodes removed during
1079 redirection, replace it with the PHI argument that used
1080 to be on E. */
1081 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
1082 size_t length = head ? head->length () : 0;
1083 for (size_t i = 0; i < length; i++)
1085 edge_var_map *vm = &(*head)[i];
1086 tree old_arg = redirect_edge_var_map_result (vm);
1087 tree new_arg = redirect_edge_var_map_def (vm);
1089 if (def == old_arg)
1091 def = new_arg;
1092 locus = redirect_edge_var_map_location (vm);
1093 break;
1098 add_phi_arg (phi, def, s, locus);
1101 redirect_edge_var_map_clear (e);
1104 /* Update the dominators. */
1105 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
1106 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
1107 if (domdest == bb)
1109 /* Shortcut to avoid calling (relatively expensive)
1110 nearest_common_dominator unless necessary. */
1111 dom = dombb;
1113 else
1114 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
1116 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
1118 /* Adjust latch infomation of BB's parent loop as otherwise
1119 the cfg hook has a hard time not to kill the loop. */
1120 if (current_loops && bb->loop_father->latch == bb)
1121 bb->loop_father->latch = pred;
1123 /* Remove BB since all of BB's incoming edges have been redirected
1124 to DEST. */
1125 delete_basic_block (bb);
1127 return true;
1130 /* This pass merges PHI nodes if one feeds into another. For example,
1131 suppose we have the following:
1133 goto <bb 9> (<L9>);
1135 <L8>:;
1136 tem_17 = foo ();
1138 # tem_6 = PHI <tem_17(8), tem_23(7)>;
1139 <L9>:;
1141 # tem_3 = PHI <tem_6(9), tem_2(5)>;
1142 <L10>:;
1144 Then we merge the first PHI node into the second one like so:
1146 goto <bb 9> (<L10>);
1148 <L8>:;
1149 tem_17 = foo ();
1151 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
1152 <L10>:;
1155 namespace {
1157 const pass_data pass_data_merge_phi =
1159 GIMPLE_PASS, /* type */
1160 "mergephi", /* name */
1161 OPTGROUP_NONE, /* optinfo_flags */
1162 TV_TREE_MERGE_PHI, /* tv_id */
1163 ( PROP_cfg | PROP_ssa ), /* properties_required */
1164 0, /* properties_provided */
1165 0, /* properties_destroyed */
1166 0, /* todo_flags_start */
1167 0, /* todo_flags_finish */
1170 class pass_merge_phi : public gimple_opt_pass
1172 public:
1173 pass_merge_phi (gcc::context *ctxt)
1174 : gimple_opt_pass (pass_data_merge_phi, ctxt)
1177 /* opt_pass methods: */
1178 opt_pass * clone () { return new pass_merge_phi (m_ctxt); }
1179 virtual unsigned int execute (function *);
1181 }; // class pass_merge_phi
1183 unsigned int
1184 pass_merge_phi::execute (function *fun)
1186 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
1187 basic_block *current = worklist;
1188 basic_block bb;
1190 calculate_dominance_info (CDI_DOMINATORS);
1192 /* Find all PHI nodes that we may be able to merge. */
1193 FOR_EACH_BB_FN (bb, fun)
1195 basic_block dest;
1197 /* Look for a forwarder block with PHI nodes. */
1198 if (!tree_forwarder_block_p (bb, true))
1199 continue;
1201 dest = single_succ (bb);
1203 /* We have to feed into another basic block with PHI
1204 nodes. */
1205 if (gimple_seq_empty_p (phi_nodes (dest))
1206 /* We don't want to deal with a basic block with
1207 abnormal edges. */
1208 || bb_has_abnormal_pred (bb))
1209 continue;
1211 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1213 /* If BB does not dominate DEST, then the PHI nodes at
1214 DEST must be the only users of the results of the PHI
1215 nodes at BB. */
1216 *current++ = bb;
1218 else
1220 gphi_iterator gsi;
1221 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1223 /* BB dominates DEST. There may be many users of the PHI
1224 nodes in BB. However, there is still a trivial case we
1225 can handle. If the result of every PHI in BB is used
1226 only by a PHI in DEST, then we can trivially merge the
1227 PHI nodes from BB into DEST. */
1228 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1229 gsi_next (&gsi))
1231 gphi *phi = gsi.phi ();
1232 tree result = gimple_phi_result (phi);
1233 use_operand_p imm_use;
1234 gimple *use_stmt;
1236 /* If the PHI's result is never used, then we can just
1237 ignore it. */
1238 if (has_zero_uses (result))
1239 continue;
1241 /* Get the single use of the result of this PHI node. */
1242 if (!single_imm_use (result, &imm_use, &use_stmt)
1243 || gimple_code (use_stmt) != GIMPLE_PHI
1244 || gimple_bb (use_stmt) != dest
1245 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1246 break;
1249 /* If the loop above iterated through all the PHI nodes
1250 in BB, then we can merge the PHIs from BB into DEST. */
1251 if (gsi_end_p (gsi))
1252 *current++ = bb;
1256 /* Now let's drain WORKLIST. */
1257 bool changed = false;
1258 while (current != worklist)
1260 bb = *--current;
1261 changed |= remove_forwarder_block_with_phi (bb);
1263 free (worklist);
1265 /* Removing forwarder blocks can cause formerly irreducible loops
1266 to become reducible if we merged two entry blocks. */
1267 if (changed
1268 && current_loops)
1269 loops_state_set (LOOPS_NEED_FIXUP);
1271 return 0;
1274 } // anon namespace
1276 gimple_opt_pass *
1277 make_pass_merge_phi (gcc::context *ctxt)
1279 return new pass_merge_phi (ctxt);
1282 /* Pass: cleanup the CFG just before expanding trees to RTL.
1283 This is just a round of label cleanups and case node grouping
1284 because after the tree optimizers have run such cleanups may
1285 be necessary. */
1287 static unsigned int
1288 execute_cleanup_cfg_post_optimizing (void)
1290 unsigned int todo = execute_fixup_cfg ();
1291 if (cleanup_tree_cfg ())
1293 todo &= ~TODO_cleanup_cfg;
1294 todo |= TODO_update_ssa;
1296 maybe_remove_unreachable_handlers ();
1297 cleanup_dead_labels ();
1298 if (group_case_labels ())
1299 todo |= TODO_cleanup_cfg;
1300 if ((flag_compare_debug_opt || flag_compare_debug)
1301 && flag_dump_final_insns)
1303 FILE *final_output = fopen (flag_dump_final_insns, "a");
1305 if (!final_output)
1307 error ("could not open final insn dump file %qs: %m",
1308 flag_dump_final_insns);
1309 flag_dump_final_insns = NULL;
1311 else
1313 int save_unnumbered = flag_dump_unnumbered;
1314 int save_noaddr = flag_dump_noaddr;
1316 flag_dump_noaddr = flag_dump_unnumbered = 1;
1317 fprintf (final_output, "\n");
1318 dump_enumerated_decls (final_output,
1319 dump_flags | TDF_SLIM | TDF_NOUID);
1320 flag_dump_noaddr = save_noaddr;
1321 flag_dump_unnumbered = save_unnumbered;
1322 if (fclose (final_output))
1324 error ("could not close final insn dump file %qs: %m",
1325 flag_dump_final_insns);
1326 flag_dump_final_insns = NULL;
1330 return todo;
1333 namespace {
1335 const pass_data pass_data_cleanup_cfg_post_optimizing =
1337 GIMPLE_PASS, /* type */
1338 "optimized", /* name */
1339 OPTGROUP_NONE, /* optinfo_flags */
1340 TV_TREE_CLEANUP_CFG, /* tv_id */
1341 PROP_cfg, /* properties_required */
1342 0, /* properties_provided */
1343 0, /* properties_destroyed */
1344 0, /* todo_flags_start */
1345 TODO_remove_unused_locals, /* todo_flags_finish */
1348 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1350 public:
1351 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1352 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1355 /* opt_pass methods: */
1356 virtual unsigned int execute (function *)
1358 return execute_cleanup_cfg_post_optimizing ();
1361 }; // class pass_cleanup_cfg_post_optimizing
1363 } // anon namespace
1365 gimple_opt_pass *
1366 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1368 return new pass_cleanup_cfg_post_optimizing (ctxt);