2015-06-11 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / tree-cfgcleanup.c
blob47eb0991b3763a1cf2cb0acd5164297228b6029b
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2015 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 "tm.h"
24 #include "input.h"
25 #include "alias.h"
26 #include "symtab.h"
27 #include "tree.h"
28 #include "fold-const.h"
29 #include "tm_p.h"
30 #include "predict.h"
31 #include "hard-reg-set.h"
32 #include "function.h"
33 #include "dominance.h"
34 #include "cfg.h"
35 #include "cfganal.h"
36 #include "cfgcleanup.h"
37 #include "basic-block.h"
38 #include "diagnostic-core.h"
39 #include "flags.h"
40 #include "langhooks.h"
41 #include "tree-ssa-alias.h"
42 #include "internal-fn.h"
43 #include "tree-eh.h"
44 #include "gimple-expr.h"
45 #include "is-a.h"
46 #include "gimple.h"
47 #include "gimplify.h"
48 #include "gimple-iterator.h"
49 #include "gimple-ssa.h"
50 #include "tree-cfg.h"
51 #include "tree-phinodes.h"
52 #include "ssa-iterators.h"
53 #include "stringpool.h"
54 #include "tree-ssanames.h"
55 #include "tree-ssa-loop-manip.h"
56 #include "rtl.h"
57 #include "insn-config.h"
58 #include "expmed.h"
59 #include "dojump.h"
60 #include "explow.h"
61 #include "calls.h"
62 #include "emit-rtl.h"
63 #include "varasm.h"
64 #include "stmt.h"
65 #include "expr.h"
66 #include "tree-dfa.h"
67 #include "tree-ssa.h"
68 #include "tree-pass.h"
69 #include "except.h"
70 #include "cfgloop.h"
71 #include "tree-ssa-propagate.h"
72 #include "tree-scalar-evolution.h"
74 /* The set of blocks in that at least one of the following changes happened:
75 -- the statement at the end of the block was changed
76 -- the block was newly created
77 -- the set of the predecessors of the block changed
78 -- the set of the successors of the block changed
79 ??? Maybe we could track these changes separately, since they determine
80 what cleanups it makes sense to try on the block. */
81 bitmap cfgcleanup_altered_bbs;
83 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
85 static bool
86 remove_fallthru_edge (vec<edge, va_gc> *ev)
88 edge_iterator ei;
89 edge e;
91 FOR_EACH_EDGE (e, ei, ev)
92 if ((e->flags & EDGE_FALLTHRU) != 0)
94 if (e->flags & EDGE_COMPLEX)
95 e->flags &= ~EDGE_FALLTHRU;
96 else
97 remove_edge_and_dominated_blocks (e);
98 return true;
100 return false;
104 /* Disconnect an unreachable block in the control expression starting
105 at block BB. */
107 static bool
108 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi)
110 edge taken_edge;
111 bool retval = false;
112 gimple stmt = gsi_stmt (gsi);
113 tree val;
115 if (!single_succ_p (bb))
117 edge e;
118 edge_iterator ei;
119 bool warned;
120 location_t loc;
122 fold_defer_overflow_warnings ();
123 loc = gimple_location (stmt);
124 switch (gimple_code (stmt))
126 case GIMPLE_COND:
127 val = fold_binary_loc (loc, gimple_cond_code (stmt),
128 boolean_type_node,
129 gimple_cond_lhs (stmt),
130 gimple_cond_rhs (stmt));
131 break;
133 case GIMPLE_SWITCH:
134 val = gimple_switch_index (as_a <gswitch *> (stmt));
135 break;
137 default:
138 val = NULL_TREE;
140 taken_edge = find_taken_edge (bb, val);
141 if (!taken_edge)
143 fold_undefer_and_ignore_overflow_warnings ();
144 return false;
147 /* Remove all the edges except the one that is always executed. */
148 warned = false;
149 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
151 if (e != taken_edge)
153 if (!warned)
155 fold_undefer_overflow_warnings
156 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
157 warned = true;
160 taken_edge->probability += e->probability;
161 taken_edge->count += e->count;
162 remove_edge_and_dominated_blocks (e);
163 retval = true;
165 else
166 ei_next (&ei);
168 if (!warned)
169 fold_undefer_and_ignore_overflow_warnings ();
170 if (taken_edge->probability > REG_BR_PROB_BASE)
171 taken_edge->probability = REG_BR_PROB_BASE;
173 else
174 taken_edge = single_succ_edge (bb);
176 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
177 gsi_remove (&gsi, true);
178 taken_edge->flags = EDGE_FALLTHRU;
180 return retval;
183 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
184 to updated gimple_call_flags. */
186 static void
187 cleanup_call_ctrl_altering_flag (gimple bb_end)
189 if (!is_gimple_call (bb_end)
190 || !gimple_call_ctrl_altering_p (bb_end))
191 return;
193 int flags = gimple_call_flags (bb_end);
194 if (((flags & (ECF_CONST | ECF_PURE))
195 && !(flags & ECF_LOOPING_CONST_OR_PURE))
196 || (flags & ECF_LEAF))
197 gimple_call_set_ctrl_altering (bb_end, false);
200 /* Try to remove superfluous control structures in basic block BB. Returns
201 true if anything changes. */
203 static bool
204 cleanup_control_flow_bb (basic_block bb)
206 gimple_stmt_iterator gsi;
207 bool retval = false;
208 gimple stmt;
210 /* If the last statement of the block could throw and now cannot,
211 we need to prune cfg. */
212 retval |= gimple_purge_dead_eh_edges (bb);
214 gsi = gsi_last_bb (bb);
215 if (gsi_end_p (gsi))
216 return retval;
218 stmt = gsi_stmt (gsi);
220 /* Try to cleanup ctrl altering flag for call which ends bb. */
221 cleanup_call_ctrl_altering_flag (stmt);
223 if (gimple_code (stmt) == GIMPLE_COND
224 || gimple_code (stmt) == GIMPLE_SWITCH)
225 retval |= cleanup_control_expr_graph (bb, gsi);
226 else if (gimple_code (stmt) == GIMPLE_GOTO
227 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
228 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
229 == LABEL_DECL))
231 /* If we had a computed goto which has a compile-time determinable
232 destination, then we can eliminate the goto. */
233 edge e;
234 tree label;
235 edge_iterator ei;
236 basic_block target_block;
238 /* First look at all the outgoing edges. Delete any outgoing
239 edges which do not go to the right block. For the one
240 edge which goes to the right block, fix up its flags. */
241 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
242 target_block = label_to_block (label);
243 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
245 if (e->dest != target_block)
246 remove_edge_and_dominated_blocks (e);
247 else
249 /* Turn off the EDGE_ABNORMAL flag. */
250 e->flags &= ~EDGE_ABNORMAL;
252 /* And set EDGE_FALLTHRU. */
253 e->flags |= EDGE_FALLTHRU;
254 ei_next (&ei);
258 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
259 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
261 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
262 relevant information we need. */
263 gsi_remove (&gsi, true);
264 retval = true;
267 /* Check for indirect calls that have been turned into
268 noreturn calls. */
269 else if (is_gimple_call (stmt)
270 && gimple_call_noreturn_p (stmt)
271 && remove_fallthru_edge (bb->succs))
272 retval = true;
274 return retval;
277 /* Return true if basic block BB does nothing except pass control
278 flow to another block and that we can safely insert a label at
279 the start of the successor block.
281 As a precondition, we require that BB be not equal to
282 the entry block. */
284 static bool
285 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
287 gimple_stmt_iterator gsi;
288 location_t locus;
290 /* BB must have a single outgoing edge. */
291 if (single_succ_p (bb) != 1
292 /* If PHI_WANTED is false, BB must not have any PHI nodes.
293 Otherwise, BB must have PHI nodes. */
294 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
295 /* BB may not be a predecessor of the exit block. */
296 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
297 /* Nor should this be an infinite loop. */
298 || single_succ (bb) == bb
299 /* BB may not have an abnormal outgoing edge. */
300 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
301 return false;
303 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
305 locus = single_succ_edge (bb)->goto_locus;
307 /* There should not be an edge coming from entry, or an EH edge. */
309 edge_iterator ei;
310 edge e;
312 FOR_EACH_EDGE (e, ei, bb->preds)
313 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
314 return false;
315 /* If goto_locus of any of the edges differs, prevent removing
316 the forwarder block for -O0. */
317 else if (optimize == 0 && e->goto_locus != locus)
318 return false;
321 /* Now walk through the statements backward. We can ignore labels,
322 anything else means this is not a forwarder block. */
323 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
325 gimple stmt = gsi_stmt (gsi);
327 switch (gimple_code (stmt))
329 case GIMPLE_LABEL:
330 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
331 return false;
332 if (optimize == 0 && gimple_location (stmt) != locus)
333 return false;
334 break;
336 /* ??? For now, hope there's a corresponding debug
337 assignment at the destination. */
338 case GIMPLE_DEBUG:
339 break;
341 default:
342 return false;
346 if (current_loops)
348 basic_block dest;
349 /* Protect loop headers. */
350 if (bb->loop_father->header == bb)
351 return false;
353 dest = EDGE_SUCC (bb, 0)->dest;
354 /* Protect loop preheaders and latches if requested. */
355 if (dest->loop_father->header == dest)
357 if (bb->loop_father == dest->loop_father)
359 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
360 return false;
361 /* If bb doesn't have a single predecessor we'd make this
362 loop have multiple latches. Don't do that if that
363 would in turn require disambiguating them. */
364 return (single_pred_p (bb)
365 || loops_state_satisfies_p
366 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
368 else if (bb->loop_father == loop_outer (dest->loop_father))
369 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
370 /* Always preserve other edges into loop headers that are
371 not simple latches or preheaders. */
372 return false;
376 return true;
379 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
380 those alternatives are equal in each of the PHI nodes, then return
381 true, else return false. */
383 static bool
384 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
386 int n1 = e1->dest_idx;
387 int n2 = e2->dest_idx;
388 gphi_iterator gsi;
390 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
392 gphi *phi = gsi.phi ();
393 tree val1 = gimple_phi_arg_def (phi, n1);
394 tree val2 = gimple_phi_arg_def (phi, n2);
396 gcc_assert (val1 != NULL_TREE);
397 gcc_assert (val2 != NULL_TREE);
399 if (!operand_equal_for_phi_arg_p (val1, val2))
400 return false;
403 return true;
406 /* Removes forwarder block BB. Returns false if this failed. */
408 static bool
409 remove_forwarder_block (basic_block bb)
411 edge succ = single_succ_edge (bb), e, s;
412 basic_block dest = succ->dest;
413 gimple label;
414 edge_iterator ei;
415 gimple_stmt_iterator gsi, gsi_to;
416 bool can_move_debug_stmts;
418 /* We check for infinite loops already in tree_forwarder_block_p.
419 However it may happen that the infinite loop is created
420 afterwards due to removal of forwarders. */
421 if (dest == bb)
422 return false;
424 /* If the destination block consists of a nonlocal label or is a
425 EH landing pad, do not merge it. */
426 label = first_stmt (dest);
427 if (label)
428 if (glabel *label_stmt = dyn_cast <glabel *> (label))
429 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
430 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
431 return false;
433 /* If there is an abnormal edge to basic block BB, but not into
434 dest, problems might occur during removal of the phi node at out
435 of ssa due to overlapping live ranges of registers.
437 If there is an abnormal edge in DEST, the problems would occur
438 anyway since cleanup_dead_labels would then merge the labels for
439 two different eh regions, and rest of exception handling code
440 does not like it.
442 So if there is an abnormal edge to BB, proceed only if there is
443 no abnormal edge to DEST and there are no phi nodes in DEST. */
444 if (bb_has_abnormal_pred (bb)
445 && (bb_has_abnormal_pred (dest)
446 || !gimple_seq_empty_p (phi_nodes (dest))))
447 return false;
449 /* If there are phi nodes in DEST, and some of the blocks that are
450 predecessors of BB are also predecessors of DEST, check that the
451 phi node arguments match. */
452 if (!gimple_seq_empty_p (phi_nodes (dest)))
454 FOR_EACH_EDGE (e, ei, bb->preds)
456 s = find_edge (e->src, dest);
457 if (!s)
458 continue;
460 if (!phi_alternatives_equal (dest, succ, s))
461 return false;
465 can_move_debug_stmts = MAY_HAVE_DEBUG_STMTS && single_pred_p (dest);
467 basic_block pred = NULL;
468 if (single_pred_p (bb))
469 pred = single_pred (bb);
471 /* Redirect the edges. */
472 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
474 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
476 if (e->flags & EDGE_ABNORMAL)
478 /* If there is an abnormal edge, redirect it anyway, and
479 move the labels to the new block to make it legal. */
480 s = redirect_edge_succ_nodup (e, dest);
482 else
483 s = redirect_edge_and_branch (e, dest);
485 if (s == e)
487 /* Create arguments for the phi nodes, since the edge was not
488 here before. */
489 for (gphi_iterator psi = gsi_start_phis (dest);
490 !gsi_end_p (psi);
491 gsi_next (&psi))
493 gphi *phi = psi.phi ();
494 source_location l = gimple_phi_arg_location_from_edge (phi, succ);
495 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
496 add_phi_arg (phi, unshare_expr (def), s, l);
501 /* Move nonlocal labels and computed goto targets as well as user
502 defined labels and labels with an EH landing pad number to the
503 new block, so that the redirection of the abnormal edges works,
504 jump targets end up in a sane place and debug information for
505 labels is retained. */
506 gsi_to = gsi_start_bb (dest);
507 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
509 tree decl;
510 label = gsi_stmt (gsi);
511 if (is_gimple_debug (label))
512 break;
513 decl = gimple_label_label (as_a <glabel *> (label));
514 if (EH_LANDING_PAD_NR (decl) != 0
515 || DECL_NONLOCAL (decl)
516 || FORCED_LABEL (decl)
517 || !DECL_ARTIFICIAL (decl))
519 gsi_remove (&gsi, false);
520 gsi_insert_before (&gsi_to, label, GSI_SAME_STMT);
522 else
523 gsi_next (&gsi);
526 /* Move debug statements if the destination has a single predecessor. */
527 if (can_move_debug_stmts)
529 gsi_to = gsi_after_labels (dest);
530 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); )
532 gimple debug = gsi_stmt (gsi);
533 if (!is_gimple_debug (debug))
534 break;
535 gsi_remove (&gsi, false);
536 gsi_insert_before (&gsi_to, debug, GSI_SAME_STMT);
540 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
542 /* Update the dominators. */
543 if (dom_info_available_p (CDI_DOMINATORS))
545 basic_block dom, dombb, domdest;
547 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
548 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
549 if (domdest == bb)
551 /* Shortcut to avoid calling (relatively expensive)
552 nearest_common_dominator unless necessary. */
553 dom = dombb;
555 else
556 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
558 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
561 /* Adjust latch infomation of BB's parent loop as otherwise
562 the cfg hook has a hard time not to kill the loop. */
563 if (current_loops && bb->loop_father->latch == bb)
564 bb->loop_father->latch = pred;
566 /* And kill the forwarder block. */
567 delete_basic_block (bb);
569 return true;
572 /* STMT is a call that has been discovered noreturn. Split the
573 block to prepare fixing up the CFG and remove LHS.
574 Return true if cleanup-cfg needs to run. */
576 bool
577 fixup_noreturn_call (gimple stmt)
579 basic_block bb = gimple_bb (stmt);
580 bool changed = false;
582 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
583 return false;
585 /* First split basic block if stmt is not last. */
586 if (stmt != gsi_stmt (gsi_last_bb (bb)))
588 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
590 /* Don't split if there are only debug stmts
591 after stmt, that can result in -fcompare-debug
592 failures. Remove the debug stmts instead,
593 they should be all unreachable anyway. */
594 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
595 for (gsi_next (&gsi); !gsi_end_p (gsi); )
596 gsi_remove (&gsi, true);
598 else
600 split_block (bb, stmt);
601 changed = true;
605 /* If there is an LHS, remove it, but only if its type has fixed size.
606 The LHS will need to be recreated during RTL expansion and creating
607 temporaries of variable-sized types is not supported. */
608 tree lhs = gimple_call_lhs (stmt);
609 if (lhs && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
611 gimple_call_set_lhs (stmt, NULL_TREE);
613 /* We need to fix up the SSA name to avoid checking errors. */
614 if (TREE_CODE (lhs) == SSA_NAME)
616 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
617 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
618 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
619 set_ssa_default_def (cfun, new_var, lhs);
622 update_stmt (stmt);
625 /* Mark the call as altering control flow. */
626 if (!gimple_call_ctrl_altering_p (stmt))
628 gimple_call_set_ctrl_altering (stmt, true);
629 changed = true;
632 return changed;
636 /* Tries to cleanup cfg in basic block BB. Returns true if anything
637 changes. */
639 static bool
640 cleanup_tree_cfg_bb (basic_block bb)
642 bool retval = cleanup_control_flow_bb (bb);
644 if (tree_forwarder_block_p (bb, false)
645 && remove_forwarder_block (bb))
646 return true;
648 /* Merging the blocks may create new opportunities for folding
649 conditional branches (due to the elimination of single-valued PHI
650 nodes). */
651 if (single_succ_p (bb)
652 && can_merge_blocks_p (bb, single_succ (bb)))
654 /* If there is a merge opportunity with the predecessor
655 do nothing now but wait until we process the predecessor.
656 This happens when we visit BBs in a non-optimal order and
657 avoids quadratic behavior with adjusting stmts BB pointer. */
658 if (single_pred_p (bb)
659 && can_merge_blocks_p (single_pred (bb), bb))
661 else
663 merge_blocks (bb, single_succ (bb));
664 return true;
668 return retval;
671 /* Iterate the cfg cleanups, while anything changes. */
673 static bool
674 cleanup_tree_cfg_1 (void)
676 bool retval = false;
677 basic_block bb;
678 unsigned i, n;
680 /* Prepare the worklists of altered blocks. */
681 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
683 /* During forwarder block cleanup, we may redirect edges out of
684 SWITCH_EXPRs, which can get expensive. So we want to enable
685 recording of edge to CASE_LABEL_EXPR. */
686 start_recording_case_labels ();
688 /* Start by iterating over all basic blocks. We cannot use FOR_EACH_BB_FN,
689 since the basic blocks may get removed. */
690 n = last_basic_block_for_fn (cfun);
691 for (i = NUM_FIXED_BLOCKS; i < n; i++)
693 bb = BASIC_BLOCK_FOR_FN (cfun, i);
694 if (bb)
695 retval |= cleanup_tree_cfg_bb (bb);
698 /* Now process the altered blocks, as long as any are available. */
699 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
701 i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
702 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
703 if (i < NUM_FIXED_BLOCKS)
704 continue;
706 bb = BASIC_BLOCK_FOR_FN (cfun, i);
707 if (!bb)
708 continue;
710 retval |= cleanup_tree_cfg_bb (bb);
713 end_recording_case_labels ();
714 BITMAP_FREE (cfgcleanup_altered_bbs);
715 return retval;
719 /* Remove unreachable blocks and other miscellaneous clean up work.
720 Return true if the flowgraph was modified, false otherwise. */
722 static bool
723 cleanup_tree_cfg_noloop (void)
725 bool changed;
727 timevar_push (TV_TREE_CLEANUP_CFG);
729 /* Iterate until there are no more cleanups left to do. If any
730 iteration changed the flowgraph, set CHANGED to true.
732 If dominance information is available, there cannot be any unreachable
733 blocks. */
734 if (!dom_info_available_p (CDI_DOMINATORS))
736 changed = delete_unreachable_blocks ();
737 calculate_dominance_info (CDI_DOMINATORS);
739 else
741 #ifdef ENABLE_CHECKING
742 verify_dominators (CDI_DOMINATORS);
743 #endif
744 changed = false;
747 changed |= cleanup_tree_cfg_1 ();
749 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
750 compact_blocks ();
752 #ifdef ENABLE_CHECKING
753 verify_flow_info ();
754 #endif
756 timevar_pop (TV_TREE_CLEANUP_CFG);
758 if (changed && current_loops)
759 loops_state_set (LOOPS_NEED_FIXUP);
761 return changed;
764 /* Repairs loop structures. */
766 static void
767 repair_loop_structures (void)
769 bitmap changed_bbs;
770 unsigned n_new_loops;
772 calculate_dominance_info (CDI_DOMINATORS);
774 timevar_push (TV_REPAIR_LOOPS);
775 changed_bbs = BITMAP_ALLOC (NULL);
776 n_new_loops = fix_loop_structure (changed_bbs);
778 /* This usually does nothing. But sometimes parts of cfg that originally
779 were inside a loop get out of it due to edge removal (since they
780 become unreachable by back edges from latch). Also a former
781 irreducible loop can become reducible - in this case force a full
782 rewrite into loop-closed SSA form. */
783 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
784 rewrite_into_loop_closed_ssa (n_new_loops ? NULL : changed_bbs,
785 TODO_update_ssa);
787 BITMAP_FREE (changed_bbs);
789 #ifdef ENABLE_CHECKING
790 verify_loop_structure ();
791 #endif
792 scev_reset ();
794 timevar_pop (TV_REPAIR_LOOPS);
797 /* Cleanup cfg and repair loop structures. */
799 bool
800 cleanup_tree_cfg (void)
802 bool changed = cleanup_tree_cfg_noloop ();
804 if (current_loops != NULL
805 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
806 repair_loop_structures ();
808 return changed;
811 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
812 Returns true if successful. */
814 static bool
815 remove_forwarder_block_with_phi (basic_block bb)
817 edge succ = single_succ_edge (bb);
818 basic_block dest = succ->dest;
819 gimple label;
820 basic_block dombb, domdest, dom;
822 /* We check for infinite loops already in tree_forwarder_block_p.
823 However it may happen that the infinite loop is created
824 afterwards due to removal of forwarders. */
825 if (dest == bb)
826 return false;
828 /* If the destination block consists of a nonlocal label, do not
829 merge it. */
830 label = first_stmt (dest);
831 if (label)
832 if (glabel *label_stmt = dyn_cast <glabel *> (label))
833 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
834 return false;
836 /* Record BB's single pred in case we need to update the father
837 loop's latch information later. */
838 basic_block pred = NULL;
839 if (single_pred_p (bb))
840 pred = single_pred (bb);
842 /* Redirect each incoming edge to BB to DEST. */
843 while (EDGE_COUNT (bb->preds) > 0)
845 edge e = EDGE_PRED (bb, 0), s;
846 gphi_iterator gsi;
848 s = find_edge (e->src, dest);
849 if (s)
851 /* We already have an edge S from E->src to DEST. If S and
852 E->dest's sole successor edge have the same PHI arguments
853 at DEST, redirect S to DEST. */
854 if (phi_alternatives_equal (dest, s, succ))
856 e = redirect_edge_and_branch (e, dest);
857 redirect_edge_var_map_clear (e);
858 continue;
861 /* PHI arguments are different. Create a forwarder block by
862 splitting E so that we can merge PHI arguments on E to
863 DEST. */
864 e = single_succ_edge (split_edge (e));
867 s = redirect_edge_and_branch (e, dest);
869 /* redirect_edge_and_branch must not create a new edge. */
870 gcc_assert (s == e);
872 /* Add to the PHI nodes at DEST each PHI argument removed at the
873 destination of E. */
874 for (gsi = gsi_start_phis (dest);
875 !gsi_end_p (gsi);
876 gsi_next (&gsi))
878 gphi *phi = gsi.phi ();
879 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
880 source_location locus = gimple_phi_arg_location_from_edge (phi, succ);
882 if (TREE_CODE (def) == SSA_NAME)
884 /* If DEF is one of the results of PHI nodes removed during
885 redirection, replace it with the PHI argument that used
886 to be on E. */
887 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
888 size_t length = head ? head->length () : 0;
889 for (size_t i = 0; i < length; i++)
891 edge_var_map *vm = &(*head)[i];
892 tree old_arg = redirect_edge_var_map_result (vm);
893 tree new_arg = redirect_edge_var_map_def (vm);
895 if (def == old_arg)
897 def = new_arg;
898 locus = redirect_edge_var_map_location (vm);
899 break;
904 add_phi_arg (phi, def, s, locus);
907 redirect_edge_var_map_clear (e);
910 /* Update the dominators. */
911 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
912 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
913 if (domdest == bb)
915 /* Shortcut to avoid calling (relatively expensive)
916 nearest_common_dominator unless necessary. */
917 dom = dombb;
919 else
920 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
922 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
924 /* Adjust latch infomation of BB's parent loop as otherwise
925 the cfg hook has a hard time not to kill the loop. */
926 if (current_loops && bb->loop_father->latch == bb)
927 bb->loop_father->latch = pred;
929 /* Remove BB since all of BB's incoming edges have been redirected
930 to DEST. */
931 delete_basic_block (bb);
933 return true;
936 /* This pass merges PHI nodes if one feeds into another. For example,
937 suppose we have the following:
939 goto <bb 9> (<L9>);
941 <L8>:;
942 tem_17 = foo ();
944 # tem_6 = PHI <tem_17(8), tem_23(7)>;
945 <L9>:;
947 # tem_3 = PHI <tem_6(9), tem_2(5)>;
948 <L10>:;
950 Then we merge the first PHI node into the second one like so:
952 goto <bb 9> (<L10>);
954 <L8>:;
955 tem_17 = foo ();
957 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
958 <L10>:;
961 namespace {
963 const pass_data pass_data_merge_phi =
965 GIMPLE_PASS, /* type */
966 "mergephi", /* name */
967 OPTGROUP_NONE, /* optinfo_flags */
968 TV_TREE_MERGE_PHI, /* tv_id */
969 ( PROP_cfg | PROP_ssa ), /* properties_required */
970 0, /* properties_provided */
971 0, /* properties_destroyed */
972 0, /* todo_flags_start */
973 0, /* todo_flags_finish */
976 class pass_merge_phi : public gimple_opt_pass
978 public:
979 pass_merge_phi (gcc::context *ctxt)
980 : gimple_opt_pass (pass_data_merge_phi, ctxt)
983 /* opt_pass methods: */
984 opt_pass * clone () { return new pass_merge_phi (m_ctxt); }
985 virtual unsigned int execute (function *);
987 }; // class pass_merge_phi
989 unsigned int
990 pass_merge_phi::execute (function *fun)
992 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
993 basic_block *current = worklist;
994 basic_block bb;
996 calculate_dominance_info (CDI_DOMINATORS);
998 /* Find all PHI nodes that we may be able to merge. */
999 FOR_EACH_BB_FN (bb, fun)
1001 basic_block dest;
1003 /* Look for a forwarder block with PHI nodes. */
1004 if (!tree_forwarder_block_p (bb, true))
1005 continue;
1007 dest = single_succ (bb);
1009 /* We have to feed into another basic block with PHI
1010 nodes. */
1011 if (gimple_seq_empty_p (phi_nodes (dest))
1012 /* We don't want to deal with a basic block with
1013 abnormal edges. */
1014 || bb_has_abnormal_pred (bb))
1015 continue;
1017 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1019 /* If BB does not dominate DEST, then the PHI nodes at
1020 DEST must be the only users of the results of the PHI
1021 nodes at BB. */
1022 *current++ = bb;
1024 else
1026 gphi_iterator gsi;
1027 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1029 /* BB dominates DEST. There may be many users of the PHI
1030 nodes in BB. However, there is still a trivial case we
1031 can handle. If the result of every PHI in BB is used
1032 only by a PHI in DEST, then we can trivially merge the
1033 PHI nodes from BB into DEST. */
1034 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1035 gsi_next (&gsi))
1037 gphi *phi = gsi.phi ();
1038 tree result = gimple_phi_result (phi);
1039 use_operand_p imm_use;
1040 gimple use_stmt;
1042 /* If the PHI's result is never used, then we can just
1043 ignore it. */
1044 if (has_zero_uses (result))
1045 continue;
1047 /* Get the single use of the result of this PHI node. */
1048 if (!single_imm_use (result, &imm_use, &use_stmt)
1049 || gimple_code (use_stmt) != GIMPLE_PHI
1050 || gimple_bb (use_stmt) != dest
1051 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1052 break;
1055 /* If the loop above iterated through all the PHI nodes
1056 in BB, then we can merge the PHIs from BB into DEST. */
1057 if (gsi_end_p (gsi))
1058 *current++ = bb;
1062 /* Now let's drain WORKLIST. */
1063 bool changed = false;
1064 while (current != worklist)
1066 bb = *--current;
1067 changed |= remove_forwarder_block_with_phi (bb);
1069 free (worklist);
1071 /* Removing forwarder blocks can cause formerly irreducible loops
1072 to become reducible if we merged two entry blocks. */
1073 if (changed
1074 && current_loops)
1075 loops_state_set (LOOPS_NEED_FIXUP);
1077 return 0;
1080 } // anon namespace
1082 gimple_opt_pass *
1083 make_pass_merge_phi (gcc::context *ctxt)
1085 return new pass_merge_phi (ctxt);
1088 /* Pass: cleanup the CFG just before expanding trees to RTL.
1089 This is just a round of label cleanups and case node grouping
1090 because after the tree optimizers have run such cleanups may
1091 be necessary. */
1093 static unsigned int
1094 execute_cleanup_cfg_post_optimizing (void)
1096 unsigned int todo = execute_fixup_cfg ();
1097 if (cleanup_tree_cfg ())
1099 todo &= ~TODO_cleanup_cfg;
1100 todo |= TODO_update_ssa;
1102 maybe_remove_unreachable_handlers ();
1103 cleanup_dead_labels ();
1104 group_case_labels ();
1105 if ((flag_compare_debug_opt || flag_compare_debug)
1106 && flag_dump_final_insns)
1108 FILE *final_output = fopen (flag_dump_final_insns, "a");
1110 if (!final_output)
1112 error ("could not open final insn dump file %qs: %m",
1113 flag_dump_final_insns);
1114 flag_dump_final_insns = NULL;
1116 else
1118 int save_unnumbered = flag_dump_unnumbered;
1119 int save_noaddr = flag_dump_noaddr;
1121 flag_dump_noaddr = flag_dump_unnumbered = 1;
1122 fprintf (final_output, "\n");
1123 dump_enumerated_decls (final_output, dump_flags | TDF_NOUID);
1124 flag_dump_noaddr = save_noaddr;
1125 flag_dump_unnumbered = save_unnumbered;
1126 if (fclose (final_output))
1128 error ("could not close final insn dump file %qs: %m",
1129 flag_dump_final_insns);
1130 flag_dump_final_insns = NULL;
1134 return todo;
1137 namespace {
1139 const pass_data pass_data_cleanup_cfg_post_optimizing =
1141 GIMPLE_PASS, /* type */
1142 "optimized", /* name */
1143 OPTGROUP_NONE, /* optinfo_flags */
1144 TV_TREE_CLEANUP_CFG, /* tv_id */
1145 PROP_cfg, /* properties_required */
1146 0, /* properties_provided */
1147 0, /* properties_destroyed */
1148 0, /* todo_flags_start */
1149 TODO_remove_unused_locals, /* todo_flags_finish */
1152 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1154 public:
1155 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1156 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1159 /* opt_pass methods: */
1160 virtual unsigned int execute (function *)
1162 return execute_cleanup_cfg_post_optimizing ();
1165 }; // class pass_cleanup_cfg_post_optimizing
1167 } // anon namespace
1169 gimple_opt_pass *
1170 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1172 return new pass_cleanup_cfg_post_optimizing (ctxt);