gcc/
[official-gcc.git] / gcc / cfgcleanup.c
blobcd12b504e18f1bfa9fb638fc376c98942f166fdc
1 /* Control flow optimization code for GNU compiler.
2 Copyright (C) 1987-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 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 /* This file contains optimizer of the control flow. The main entry point is
21 cleanup_cfg. Following optimizations are performed:
23 - Unreachable blocks removal
24 - Edge forwarding (edge to the forwarder block is forwarded to its
25 successor. Simplification of the branch instruction is performed by
26 underlying infrastructure so branch can be converted to simplejump or
27 eliminated).
28 - Cross jumping (tail merging)
29 - Conditional jump-around-simplejump simplification
30 - Basic block merging. */
32 #include "config.h"
33 #include "system.h"
34 #include "coretypes.h"
35 #include "tm.h"
36 #include "rtl.h"
37 #include "hash-set.h"
38 #include "machmode.h"
39 #include "vec.h"
40 #include "double-int.h"
41 #include "input.h"
42 #include "alias.h"
43 #include "symtab.h"
44 #include "wide-int.h"
45 #include "inchash.h"
46 #include "tree.h"
47 #include "hard-reg-set.h"
48 #include "regs.h"
49 #include "insn-config.h"
50 #include "flags.h"
51 #include "recog.h"
52 #include "diagnostic-core.h"
53 #include "cselib.h"
54 #include "params.h"
55 #include "tm_p.h"
56 #include "target.h"
57 #include "hashtab.h"
58 #include "function.h" /* For inline functions in emit-rtl.h they need crtl. */
59 #include "emit-rtl.h"
60 #include "tree-pass.h"
61 #include "cfgloop.h"
62 #include "function.h"
63 #include "statistics.h"
64 #include "real.h"
65 #include "fixed-value.h"
66 #include "expmed.h"
67 #include "dojump.h"
68 #include "explow.h"
69 #include "calls.h"
70 #include "varasm.h"
71 #include "stmt.h"
72 #include "expr.h"
73 #include "dominance.h"
74 #include "cfg.h"
75 #include "cfgrtl.h"
76 #include "cfganal.h"
77 #include "cfgbuild.h"
78 #include "cfgcleanup.h"
79 #include "predict.h"
80 #include "basic-block.h"
81 #include "df.h"
82 #include "dce.h"
83 #include "dbgcnt.h"
84 #include "rtl-iter.h"
86 #define FORWARDER_BLOCK_P(BB) ((BB)->flags & BB_FORWARDER_BLOCK)
88 /* Set to true when we are running first pass of try_optimize_cfg loop. */
89 static bool first_pass;
91 /* Set to true if crossjumps occurred in the latest run of try_optimize_cfg. */
92 static bool crossjumps_occured;
94 /* Set to true if we couldn't run an optimization due to stale liveness
95 information; we should run df_analyze to enable more opportunities. */
96 static bool block_was_dirty;
98 static bool try_crossjump_to_edge (int, edge, edge, enum replace_direction);
99 static bool try_crossjump_bb (int, basic_block);
100 static bool outgoing_edges_match (int, basic_block, basic_block);
101 static enum replace_direction old_insns_match_p (int, rtx_insn *, rtx_insn *);
103 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
104 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
105 static bool try_optimize_cfg (int);
106 static bool try_simplify_condjump (basic_block);
107 static bool try_forward_edges (int, basic_block);
108 static edge thread_jump (edge, basic_block);
109 static bool mark_effect (rtx, bitmap);
110 static void notice_new_block (basic_block);
111 static void update_forwarder_flag (basic_block);
112 static void merge_memattrs (rtx, rtx);
114 /* Set flags for newly created block. */
116 static void
117 notice_new_block (basic_block bb)
119 if (!bb)
120 return;
122 if (forwarder_block_p (bb))
123 bb->flags |= BB_FORWARDER_BLOCK;
126 /* Recompute forwarder flag after block has been modified. */
128 static void
129 update_forwarder_flag (basic_block bb)
131 if (forwarder_block_p (bb))
132 bb->flags |= BB_FORWARDER_BLOCK;
133 else
134 bb->flags &= ~BB_FORWARDER_BLOCK;
137 /* Simplify a conditional jump around an unconditional jump.
138 Return true if something changed. */
140 static bool
141 try_simplify_condjump (basic_block cbranch_block)
143 basic_block jump_block, jump_dest_block, cbranch_dest_block;
144 edge cbranch_jump_edge, cbranch_fallthru_edge;
145 rtx_insn *cbranch_insn;
147 /* Verify that there are exactly two successors. */
148 if (EDGE_COUNT (cbranch_block->succs) != 2)
149 return false;
151 /* Verify that we've got a normal conditional branch at the end
152 of the block. */
153 cbranch_insn = BB_END (cbranch_block);
154 if (!any_condjump_p (cbranch_insn))
155 return false;
157 cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
158 cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
160 /* The next block must not have multiple predecessors, must not
161 be the last block in the function, and must contain just the
162 unconditional jump. */
163 jump_block = cbranch_fallthru_edge->dest;
164 if (!single_pred_p (jump_block)
165 || jump_block->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
166 || !FORWARDER_BLOCK_P (jump_block))
167 return false;
168 jump_dest_block = single_succ (jump_block);
170 /* If we are partitioning hot/cold basic blocks, we don't want to
171 mess up unconditional or indirect jumps that cross between hot
172 and cold sections.
174 Basic block partitioning may result in some jumps that appear to
175 be optimizable (or blocks that appear to be mergeable), but which really
176 must be left untouched (they are required to make it safely across
177 partition boundaries). See the comments at the top of
178 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
180 if (BB_PARTITION (jump_block) != BB_PARTITION (jump_dest_block)
181 || (cbranch_jump_edge->flags & EDGE_CROSSING))
182 return false;
184 /* The conditional branch must target the block after the
185 unconditional branch. */
186 cbranch_dest_block = cbranch_jump_edge->dest;
188 if (cbranch_dest_block == EXIT_BLOCK_PTR_FOR_FN (cfun)
189 || !can_fallthru (jump_block, cbranch_dest_block))
190 return false;
192 /* Invert the conditional branch. */
193 if (!invert_jump (cbranch_insn, block_label (jump_dest_block), 0))
194 return false;
196 if (dump_file)
197 fprintf (dump_file, "Simplifying condjump %i around jump %i\n",
198 INSN_UID (cbranch_insn), INSN_UID (BB_END (jump_block)));
200 /* Success. Update the CFG to match. Note that after this point
201 the edge variable names appear backwards; the redirection is done
202 this way to preserve edge profile data. */
203 cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
204 cbranch_dest_block);
205 cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
206 jump_dest_block);
207 cbranch_jump_edge->flags |= EDGE_FALLTHRU;
208 cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
209 update_br_prob_note (cbranch_block);
211 /* Delete the block with the unconditional jump, and clean up the mess. */
212 delete_basic_block (jump_block);
213 tidy_fallthru_edge (cbranch_jump_edge);
214 update_forwarder_flag (cbranch_block);
216 return true;
219 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
220 on register. Used by jump threading. */
222 static bool
223 mark_effect (rtx exp, regset nonequal)
225 rtx dest;
226 switch (GET_CODE (exp))
228 /* In case we do clobber the register, mark it as equal, as we know the
229 value is dead so it don't have to match. */
230 case CLOBBER:
231 dest = XEXP (exp, 0);
232 if (REG_P (dest))
233 bitmap_clear_range (nonequal, REGNO (dest), REG_NREGS (dest));
234 return false;
236 case SET:
237 if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
238 return false;
239 dest = SET_DEST (exp);
240 if (dest == pc_rtx)
241 return false;
242 if (!REG_P (dest))
243 return true;
244 bitmap_set_range (nonequal, REGNO (dest), REG_NREGS (dest));
245 return false;
247 default:
248 return false;
252 /* Return true if X contains a register in NONEQUAL. */
253 static bool
254 mentions_nonequal_regs (const_rtx x, regset nonequal)
256 subrtx_iterator::array_type array;
257 FOR_EACH_SUBRTX (iter, array, x, NONCONST)
259 const_rtx x = *iter;
260 if (REG_P (x))
262 unsigned int end_regno = END_REGNO (x);
263 for (unsigned int regno = REGNO (x); regno < end_regno; ++regno)
264 if (REGNO_REG_SET_P (nonequal, regno))
265 return true;
268 return false;
271 /* Attempt to prove that the basic block B will have no side effects and
272 always continues in the same edge if reached via E. Return the edge
273 if exist, NULL otherwise. */
275 static edge
276 thread_jump (edge e, basic_block b)
278 rtx set1, set2, cond1, cond2;
279 rtx_insn *insn;
280 enum rtx_code code1, code2, reversed_code2;
281 bool reverse1 = false;
282 unsigned i;
283 regset nonequal;
284 bool failed = false;
285 reg_set_iterator rsi;
287 if (b->flags & BB_NONTHREADABLE_BLOCK)
288 return NULL;
290 /* At the moment, we do handle only conditional jumps, but later we may
291 want to extend this code to tablejumps and others. */
292 if (EDGE_COUNT (e->src->succs) != 2)
293 return NULL;
294 if (EDGE_COUNT (b->succs) != 2)
296 b->flags |= BB_NONTHREADABLE_BLOCK;
297 return NULL;
300 /* Second branch must end with onlyjump, as we will eliminate the jump. */
301 if (!any_condjump_p (BB_END (e->src)))
302 return NULL;
304 if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
306 b->flags |= BB_NONTHREADABLE_BLOCK;
307 return NULL;
310 set1 = pc_set (BB_END (e->src));
311 set2 = pc_set (BB_END (b));
312 if (((e->flags & EDGE_FALLTHRU) != 0)
313 != (XEXP (SET_SRC (set1), 1) == pc_rtx))
314 reverse1 = true;
316 cond1 = XEXP (SET_SRC (set1), 0);
317 cond2 = XEXP (SET_SRC (set2), 0);
318 if (reverse1)
319 code1 = reversed_comparison_code (cond1, BB_END (e->src));
320 else
321 code1 = GET_CODE (cond1);
323 code2 = GET_CODE (cond2);
324 reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
326 if (!comparison_dominates_p (code1, code2)
327 && !comparison_dominates_p (code1, reversed_code2))
328 return NULL;
330 /* Ensure that the comparison operators are equivalent.
331 ??? This is far too pessimistic. We should allow swapped operands,
332 different CCmodes, or for example comparisons for interval, that
333 dominate even when operands are not equivalent. */
334 if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
335 || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
336 return NULL;
338 /* Short circuit cases where block B contains some side effects, as we can't
339 safely bypass it. */
340 for (insn = NEXT_INSN (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
341 insn = NEXT_INSN (insn))
342 if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
344 b->flags |= BB_NONTHREADABLE_BLOCK;
345 return NULL;
348 cselib_init (0);
350 /* First process all values computed in the source basic block. */
351 for (insn = NEXT_INSN (BB_HEAD (e->src));
352 insn != NEXT_INSN (BB_END (e->src));
353 insn = NEXT_INSN (insn))
354 if (INSN_P (insn))
355 cselib_process_insn (insn);
357 nonequal = BITMAP_ALLOC (NULL);
358 CLEAR_REG_SET (nonequal);
360 /* Now assume that we've continued by the edge E to B and continue
361 processing as if it were same basic block.
362 Our goal is to prove that whole block is an NOOP. */
364 for (insn = NEXT_INSN (BB_HEAD (b));
365 insn != NEXT_INSN (BB_END (b)) && !failed;
366 insn = NEXT_INSN (insn))
368 if (INSN_P (insn))
370 rtx pat = PATTERN (insn);
372 if (GET_CODE (pat) == PARALLEL)
374 for (i = 0; i < (unsigned)XVECLEN (pat, 0); i++)
375 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
377 else
378 failed |= mark_effect (pat, nonequal);
381 cselib_process_insn (insn);
384 /* Later we should clear nonequal of dead registers. So far we don't
385 have life information in cfg_cleanup. */
386 if (failed)
388 b->flags |= BB_NONTHREADABLE_BLOCK;
389 goto failed_exit;
392 /* cond2 must not mention any register that is not equal to the
393 former block. */
394 if (mentions_nonequal_regs (cond2, nonequal))
395 goto failed_exit;
397 EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, rsi)
398 goto failed_exit;
400 BITMAP_FREE (nonequal);
401 cselib_finish ();
402 if ((comparison_dominates_p (code1, code2) != 0)
403 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
404 return BRANCH_EDGE (b);
405 else
406 return FALLTHRU_EDGE (b);
408 failed_exit:
409 BITMAP_FREE (nonequal);
410 cselib_finish ();
411 return NULL;
414 /* Attempt to forward edges leaving basic block B.
415 Return true if successful. */
417 static bool
418 try_forward_edges (int mode, basic_block b)
420 bool changed = false;
421 edge_iterator ei;
422 edge e, *threaded_edges = NULL;
424 /* If we are partitioning hot/cold basic blocks, we don't want to
425 mess up unconditional or indirect jumps that cross between hot
426 and cold sections.
428 Basic block partitioning may result in some jumps that appear to
429 be optimizable (or blocks that appear to be mergeable), but which really
430 must be left untouched (they are required to make it safely across
431 partition boundaries). See the comments at the top of
432 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
434 if (JUMP_P (BB_END (b)) && CROSSING_JUMP_P (BB_END (b)))
435 return false;
437 for (ei = ei_start (b->succs); (e = ei_safe_edge (ei)); )
439 basic_block target, first;
440 location_t goto_locus;
441 int counter;
442 bool threaded = false;
443 int nthreaded_edges = 0;
444 bool may_thread = first_pass || (b->flags & BB_MODIFIED) != 0;
446 /* Skip complex edges because we don't know how to update them.
448 Still handle fallthru edges, as we can succeed to forward fallthru
449 edge to the same place as the branch edge of conditional branch
450 and turn conditional branch to an unconditional branch. */
451 if (e->flags & EDGE_COMPLEX)
453 ei_next (&ei);
454 continue;
457 target = first = e->dest;
458 counter = NUM_FIXED_BLOCKS;
459 goto_locus = e->goto_locus;
461 /* If we are partitioning hot/cold basic_blocks, we don't want to mess
462 up jumps that cross between hot/cold sections.
464 Basic block partitioning may result in some jumps that appear
465 to be optimizable (or blocks that appear to be mergeable), but which
466 really must be left untouched (they are required to make it safely
467 across partition boundaries). See the comments at the top of
468 bb-reorder.c:partition_hot_cold_basic_blocks for complete
469 details. */
471 if (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
472 && JUMP_P (BB_END (first))
473 && CROSSING_JUMP_P (BB_END (first)))
474 return changed;
476 while (counter < n_basic_blocks_for_fn (cfun))
478 basic_block new_target = NULL;
479 bool new_target_threaded = false;
480 may_thread |= (target->flags & BB_MODIFIED) != 0;
482 if (FORWARDER_BLOCK_P (target)
483 && !(single_succ_edge (target)->flags & EDGE_CROSSING)
484 && single_succ (target) != EXIT_BLOCK_PTR_FOR_FN (cfun))
486 /* Bypass trivial infinite loops. */
487 new_target = single_succ (target);
488 if (target == new_target)
489 counter = n_basic_blocks_for_fn (cfun);
490 else if (!optimize)
492 /* When not optimizing, ensure that edges or forwarder
493 blocks with different locus are not optimized out. */
494 location_t new_locus = single_succ_edge (target)->goto_locus;
495 location_t locus = goto_locus;
497 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
498 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
499 && new_locus != locus)
500 new_target = NULL;
501 else
503 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
504 locus = new_locus;
506 rtx_insn *last = BB_END (target);
507 if (DEBUG_INSN_P (last))
508 last = prev_nondebug_insn (last);
509 if (last && INSN_P (last))
510 new_locus = INSN_LOCATION (last);
511 else
512 new_locus = UNKNOWN_LOCATION;
514 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
515 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
516 && new_locus != locus)
517 new_target = NULL;
518 else
520 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
521 locus = new_locus;
523 goto_locus = locus;
529 /* Allow to thread only over one edge at time to simplify updating
530 of probabilities. */
531 else if ((mode & CLEANUP_THREADING) && may_thread)
533 edge t = thread_jump (e, target);
534 if (t)
536 if (!threaded_edges)
537 threaded_edges = XNEWVEC (edge,
538 n_basic_blocks_for_fn (cfun));
539 else
541 int i;
543 /* Detect an infinite loop across blocks not
544 including the start block. */
545 for (i = 0; i < nthreaded_edges; ++i)
546 if (threaded_edges[i] == t)
547 break;
548 if (i < nthreaded_edges)
550 counter = n_basic_blocks_for_fn (cfun);
551 break;
555 /* Detect an infinite loop across the start block. */
556 if (t->dest == b)
557 break;
559 gcc_assert (nthreaded_edges
560 < (n_basic_blocks_for_fn (cfun)
561 - NUM_FIXED_BLOCKS));
562 threaded_edges[nthreaded_edges++] = t;
564 new_target = t->dest;
565 new_target_threaded = true;
569 if (!new_target)
570 break;
572 counter++;
573 target = new_target;
574 threaded |= new_target_threaded;
577 if (counter >= n_basic_blocks_for_fn (cfun))
579 if (dump_file)
580 fprintf (dump_file, "Infinite loop in BB %i.\n",
581 target->index);
583 else if (target == first)
584 ; /* We didn't do anything. */
585 else
587 /* Save the values now, as the edge may get removed. */
588 gcov_type edge_count = e->count;
589 int edge_probability = e->probability;
590 int edge_frequency;
591 int n = 0;
593 e->goto_locus = goto_locus;
595 /* Don't force if target is exit block. */
596 if (threaded && target != EXIT_BLOCK_PTR_FOR_FN (cfun))
598 notice_new_block (redirect_edge_and_branch_force (e, target));
599 if (dump_file)
600 fprintf (dump_file, "Conditionals threaded.\n");
602 else if (!redirect_edge_and_branch (e, target))
604 if (dump_file)
605 fprintf (dump_file,
606 "Forwarding edge %i->%i to %i failed.\n",
607 b->index, e->dest->index, target->index);
608 ei_next (&ei);
609 continue;
612 /* We successfully forwarded the edge. Now update profile
613 data: for each edge we traversed in the chain, remove
614 the original edge's execution count. */
615 edge_frequency = apply_probability (b->frequency, edge_probability);
619 edge t;
621 if (!single_succ_p (first))
623 gcc_assert (n < nthreaded_edges);
624 t = threaded_edges [n++];
625 gcc_assert (t->src == first);
626 update_bb_profile_for_threading (first, edge_frequency,
627 edge_count, t);
628 update_br_prob_note (first);
630 else
632 first->count -= edge_count;
633 if (first->count < 0)
634 first->count = 0;
635 first->frequency -= edge_frequency;
636 if (first->frequency < 0)
637 first->frequency = 0;
638 /* It is possible that as the result of
639 threading we've removed edge as it is
640 threaded to the fallthru edge. Avoid
641 getting out of sync. */
642 if (n < nthreaded_edges
643 && first == threaded_edges [n]->src)
644 n++;
645 t = single_succ_edge (first);
648 t->count -= edge_count;
649 if (t->count < 0)
650 t->count = 0;
651 first = t->dest;
653 while (first != target);
655 changed = true;
656 continue;
658 ei_next (&ei);
661 free (threaded_edges);
662 return changed;
666 /* Blocks A and B are to be merged into a single block. A has no incoming
667 fallthru edge, so it can be moved before B without adding or modifying
668 any jumps (aside from the jump from A to B). */
670 static void
671 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
673 rtx_insn *barrier;
675 /* If we are partitioning hot/cold basic blocks, we don't want to
676 mess up unconditional or indirect jumps that cross between hot
677 and cold sections.
679 Basic block partitioning may result in some jumps that appear to
680 be optimizable (or blocks that appear to be mergeable), but which really
681 must be left untouched (they are required to make it safely across
682 partition boundaries). See the comments at the top of
683 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
685 if (BB_PARTITION (a) != BB_PARTITION (b))
686 return;
688 barrier = next_nonnote_insn (BB_END (a));
689 gcc_assert (BARRIER_P (barrier));
690 delete_insn (barrier);
692 /* Scramble the insn chain. */
693 if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
694 reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
695 df_set_bb_dirty (a);
697 if (dump_file)
698 fprintf (dump_file, "Moved block %d before %d and merged.\n",
699 a->index, b->index);
701 /* Swap the records for the two blocks around. */
703 unlink_block (a);
704 link_block (a, b->prev_bb);
706 /* Now blocks A and B are contiguous. Merge them. */
707 merge_blocks (a, b);
710 /* Blocks A and B are to be merged into a single block. B has no outgoing
711 fallthru edge, so it can be moved after A without adding or modifying
712 any jumps (aside from the jump from A to B). */
714 static void
715 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
717 rtx_insn *barrier, *real_b_end;
718 rtx label;
719 rtx_jump_table_data *table;
721 /* If we are partitioning hot/cold basic blocks, we don't want to
722 mess up unconditional or indirect jumps that cross between hot
723 and cold sections.
725 Basic block partitioning may result in some jumps that appear to
726 be optimizable (or blocks that appear to be mergeable), but which really
727 must be left untouched (they are required to make it safely across
728 partition boundaries). See the comments at the top of
729 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
731 if (BB_PARTITION (a) != BB_PARTITION (b))
732 return;
734 real_b_end = BB_END (b);
736 /* If there is a jump table following block B temporarily add the jump table
737 to block B so that it will also be moved to the correct location. */
738 if (tablejump_p (BB_END (b), &label, &table)
739 && prev_active_insn (label) == BB_END (b))
741 BB_END (b) = table;
744 /* There had better have been a barrier there. Delete it. */
745 barrier = NEXT_INSN (BB_END (b));
746 if (barrier && BARRIER_P (barrier))
747 delete_insn (barrier);
750 /* Scramble the insn chain. */
751 reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
753 /* Restore the real end of b. */
754 BB_END (b) = real_b_end;
756 if (dump_file)
757 fprintf (dump_file, "Moved block %d after %d and merged.\n",
758 b->index, a->index);
760 /* Now blocks A and B are contiguous. Merge them. */
761 merge_blocks (a, b);
764 /* Attempt to merge basic blocks that are potentially non-adjacent.
765 Return NULL iff the attempt failed, otherwise return basic block
766 where cleanup_cfg should continue. Because the merging commonly
767 moves basic block away or introduces another optimization
768 possibility, return basic block just before B so cleanup_cfg don't
769 need to iterate.
771 It may be good idea to return basic block before C in the case
772 C has been moved after B and originally appeared earlier in the
773 insn sequence, but we have no information available about the
774 relative ordering of these two. Hopefully it is not too common. */
776 static basic_block
777 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
779 basic_block next;
781 /* If we are partitioning hot/cold basic blocks, we don't want to
782 mess up unconditional or indirect jumps that cross between hot
783 and cold sections.
785 Basic block partitioning may result in some jumps that appear to
786 be optimizable (or blocks that appear to be mergeable), but which really
787 must be left untouched (they are required to make it safely across
788 partition boundaries). See the comments at the top of
789 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
791 if (BB_PARTITION (b) != BB_PARTITION (c))
792 return NULL;
794 /* If B has a fallthru edge to C, no need to move anything. */
795 if (e->flags & EDGE_FALLTHRU)
797 int b_index = b->index, c_index = c->index;
799 /* Protect the loop latches. */
800 if (current_loops && c->loop_father->latch == c)
801 return NULL;
803 merge_blocks (b, c);
804 update_forwarder_flag (b);
806 if (dump_file)
807 fprintf (dump_file, "Merged %d and %d without moving.\n",
808 b_index, c_index);
810 return b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? b : b->prev_bb;
813 /* Otherwise we will need to move code around. Do that only if expensive
814 transformations are allowed. */
815 else if (mode & CLEANUP_EXPENSIVE)
817 edge tmp_edge, b_fallthru_edge;
818 bool c_has_outgoing_fallthru;
819 bool b_has_incoming_fallthru;
821 /* Avoid overactive code motion, as the forwarder blocks should be
822 eliminated by edge redirection instead. One exception might have
823 been if B is a forwarder block and C has no fallthru edge, but
824 that should be cleaned up by bb-reorder instead. */
825 if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
826 return NULL;
828 /* We must make sure to not munge nesting of lexical blocks,
829 and loop notes. This is done by squeezing out all the notes
830 and leaving them there to lie. Not ideal, but functional. */
832 tmp_edge = find_fallthru_edge (c->succs);
833 c_has_outgoing_fallthru = (tmp_edge != NULL);
835 tmp_edge = find_fallthru_edge (b->preds);
836 b_has_incoming_fallthru = (tmp_edge != NULL);
837 b_fallthru_edge = tmp_edge;
838 next = b->prev_bb;
839 if (next == c)
840 next = next->prev_bb;
842 /* Otherwise, we're going to try to move C after B. If C does
843 not have an outgoing fallthru, then it can be moved
844 immediately after B without introducing or modifying jumps. */
845 if (! c_has_outgoing_fallthru)
847 merge_blocks_move_successor_nojumps (b, c);
848 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
851 /* If B does not have an incoming fallthru, then it can be moved
852 immediately before C without introducing or modifying jumps.
853 C cannot be the first block, so we do not have to worry about
854 accessing a non-existent block. */
856 if (b_has_incoming_fallthru)
858 basic_block bb;
860 if (b_fallthru_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
861 return NULL;
862 bb = force_nonfallthru (b_fallthru_edge);
863 if (bb)
864 notice_new_block (bb);
867 merge_blocks_move_predecessor_nojumps (b, c);
868 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
871 return NULL;
875 /* Removes the memory attributes of MEM expression
876 if they are not equal. */
878 static void
879 merge_memattrs (rtx x, rtx y)
881 int i;
882 int j;
883 enum rtx_code code;
884 const char *fmt;
886 if (x == y)
887 return;
888 if (x == 0 || y == 0)
889 return;
891 code = GET_CODE (x);
893 if (code != GET_CODE (y))
894 return;
896 if (GET_MODE (x) != GET_MODE (y))
897 return;
899 if (code == MEM && !mem_attrs_eq_p (MEM_ATTRS (x), MEM_ATTRS (y)))
901 if (! MEM_ATTRS (x))
902 MEM_ATTRS (y) = 0;
903 else if (! MEM_ATTRS (y))
904 MEM_ATTRS (x) = 0;
905 else
907 HOST_WIDE_INT mem_size;
909 if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
911 set_mem_alias_set (x, 0);
912 set_mem_alias_set (y, 0);
915 if (! mem_expr_equal_p (MEM_EXPR (x), MEM_EXPR (y)))
917 set_mem_expr (x, 0);
918 set_mem_expr (y, 0);
919 clear_mem_offset (x);
920 clear_mem_offset (y);
922 else if (MEM_OFFSET_KNOWN_P (x) != MEM_OFFSET_KNOWN_P (y)
923 || (MEM_OFFSET_KNOWN_P (x)
924 && MEM_OFFSET (x) != MEM_OFFSET (y)))
926 clear_mem_offset (x);
927 clear_mem_offset (y);
930 if (MEM_SIZE_KNOWN_P (x) && MEM_SIZE_KNOWN_P (y))
932 mem_size = MAX (MEM_SIZE (x), MEM_SIZE (y));
933 set_mem_size (x, mem_size);
934 set_mem_size (y, mem_size);
936 else
938 clear_mem_size (x);
939 clear_mem_size (y);
942 set_mem_align (x, MIN (MEM_ALIGN (x), MEM_ALIGN (y)));
943 set_mem_align (y, MEM_ALIGN (x));
946 if (code == MEM)
948 if (MEM_READONLY_P (x) != MEM_READONLY_P (y))
950 MEM_READONLY_P (x) = 0;
951 MEM_READONLY_P (y) = 0;
953 if (MEM_NOTRAP_P (x) != MEM_NOTRAP_P (y))
955 MEM_NOTRAP_P (x) = 0;
956 MEM_NOTRAP_P (y) = 0;
958 if (MEM_VOLATILE_P (x) != MEM_VOLATILE_P (y))
960 MEM_VOLATILE_P (x) = 1;
961 MEM_VOLATILE_P (y) = 1;
965 fmt = GET_RTX_FORMAT (code);
966 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
968 switch (fmt[i])
970 case 'E':
971 /* Two vectors must have the same length. */
972 if (XVECLEN (x, i) != XVECLEN (y, i))
973 return;
975 for (j = 0; j < XVECLEN (x, i); j++)
976 merge_memattrs (XVECEXP (x, i, j), XVECEXP (y, i, j));
978 break;
980 case 'e':
981 merge_memattrs (XEXP (x, i), XEXP (y, i));
984 return;
988 /* Checks if patterns P1 and P2 are equivalent, apart from the possibly
989 different single sets S1 and S2. */
991 static bool
992 equal_different_set_p (rtx p1, rtx s1, rtx p2, rtx s2)
994 int i;
995 rtx e1, e2;
997 if (p1 == s1 && p2 == s2)
998 return true;
1000 if (GET_CODE (p1) != PARALLEL || GET_CODE (p2) != PARALLEL)
1001 return false;
1003 if (XVECLEN (p1, 0) != XVECLEN (p2, 0))
1004 return false;
1006 for (i = 0; i < XVECLEN (p1, 0); i++)
1008 e1 = XVECEXP (p1, 0, i);
1009 e2 = XVECEXP (p2, 0, i);
1010 if (e1 == s1 && e2 == s2)
1011 continue;
1012 if (reload_completed
1013 ? rtx_renumbered_equal_p (e1, e2) : rtx_equal_p (e1, e2))
1014 continue;
1016 return false;
1019 return true;
1023 /* NOTE1 is the REG_EQUAL note, if any, attached to an insn
1024 that is a single_set with a SET_SRC of SRC1. Similarly
1025 for NOTE2/SRC2.
1027 So effectively NOTE1/NOTE2 are an alternate form of
1028 SRC1/SRC2 respectively.
1030 Return nonzero if SRC1 or NOTE1 has the same constant
1031 integer value as SRC2 or NOTE2. Else return zero. */
1032 static int
1033 values_equal_p (rtx note1, rtx note2, rtx src1, rtx src2)
1035 if (note1
1036 && note2
1037 && CONST_INT_P (XEXP (note1, 0))
1038 && rtx_equal_p (XEXP (note1, 0), XEXP (note2, 0)))
1039 return 1;
1041 if (!note1
1042 && !note2
1043 && CONST_INT_P (src1)
1044 && CONST_INT_P (src2)
1045 && rtx_equal_p (src1, src2))
1046 return 1;
1048 if (note1
1049 && CONST_INT_P (src2)
1050 && rtx_equal_p (XEXP (note1, 0), src2))
1051 return 1;
1053 if (note2
1054 && CONST_INT_P (src1)
1055 && rtx_equal_p (XEXP (note2, 0), src1))
1056 return 1;
1058 return 0;
1061 /* Examine register notes on I1 and I2 and return:
1062 - dir_forward if I1 can be replaced by I2, or
1063 - dir_backward if I2 can be replaced by I1, or
1064 - dir_both if both are the case. */
1066 static enum replace_direction
1067 can_replace_by (rtx_insn *i1, rtx_insn *i2)
1069 rtx s1, s2, d1, d2, src1, src2, note1, note2;
1070 bool c1, c2;
1072 /* Check for 2 sets. */
1073 s1 = single_set (i1);
1074 s2 = single_set (i2);
1075 if (s1 == NULL_RTX || s2 == NULL_RTX)
1076 return dir_none;
1078 /* Check that the 2 sets set the same dest. */
1079 d1 = SET_DEST (s1);
1080 d2 = SET_DEST (s2);
1081 if (!(reload_completed
1082 ? rtx_renumbered_equal_p (d1, d2) : rtx_equal_p (d1, d2)))
1083 return dir_none;
1085 /* Find identical req_equiv or reg_equal note, which implies that the 2 sets
1086 set dest to the same value. */
1087 note1 = find_reg_equal_equiv_note (i1);
1088 note2 = find_reg_equal_equiv_note (i2);
1090 src1 = SET_SRC (s1);
1091 src2 = SET_SRC (s2);
1093 if (!values_equal_p (note1, note2, src1, src2))
1094 return dir_none;
1096 if (!equal_different_set_p (PATTERN (i1), s1, PATTERN (i2), s2))
1097 return dir_none;
1099 /* Although the 2 sets set dest to the same value, we cannot replace
1100 (set (dest) (const_int))
1102 (set (dest) (reg))
1103 because we don't know if the reg is live and has the same value at the
1104 location of replacement. */
1105 c1 = CONST_INT_P (src1);
1106 c2 = CONST_INT_P (src2);
1107 if (c1 && c2)
1108 return dir_both;
1109 else if (c2)
1110 return dir_forward;
1111 else if (c1)
1112 return dir_backward;
1114 return dir_none;
1117 /* Merges directions A and B. */
1119 static enum replace_direction
1120 merge_dir (enum replace_direction a, enum replace_direction b)
1122 /* Implements the following table:
1123 |bo fw bw no
1124 ---+-----------
1125 bo |bo fw bw no
1126 fw |-- fw no no
1127 bw |-- -- bw no
1128 no |-- -- -- no. */
1130 if (a == b)
1131 return a;
1133 if (a == dir_both)
1134 return b;
1135 if (b == dir_both)
1136 return a;
1138 return dir_none;
1141 /* Examine I1 and I2 and return:
1142 - dir_forward if I1 can be replaced by I2, or
1143 - dir_backward if I2 can be replaced by I1, or
1144 - dir_both if both are the case. */
1146 static enum replace_direction
1147 old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
1149 rtx p1, p2;
1151 /* Verify that I1 and I2 are equivalent. */
1152 if (GET_CODE (i1) != GET_CODE (i2))
1153 return dir_none;
1155 /* __builtin_unreachable() may lead to empty blocks (ending with
1156 NOTE_INSN_BASIC_BLOCK). They may be crossjumped. */
1157 if (NOTE_INSN_BASIC_BLOCK_P (i1) && NOTE_INSN_BASIC_BLOCK_P (i2))
1158 return dir_both;
1160 /* ??? Do not allow cross-jumping between different stack levels. */
1161 p1 = find_reg_note (i1, REG_ARGS_SIZE, NULL);
1162 p2 = find_reg_note (i2, REG_ARGS_SIZE, NULL);
1163 if (p1 && p2)
1165 p1 = XEXP (p1, 0);
1166 p2 = XEXP (p2, 0);
1167 if (!rtx_equal_p (p1, p2))
1168 return dir_none;
1170 /* ??? Worse, this adjustment had better be constant lest we
1171 have differing incoming stack levels. */
1172 if (!frame_pointer_needed
1173 && find_args_size_adjust (i1) == HOST_WIDE_INT_MIN)
1174 return dir_none;
1176 else if (p1 || p2)
1177 return dir_none;
1179 p1 = PATTERN (i1);
1180 p2 = PATTERN (i2);
1182 if (GET_CODE (p1) != GET_CODE (p2))
1183 return dir_none;
1185 /* If this is a CALL_INSN, compare register usage information.
1186 If we don't check this on stack register machines, the two
1187 CALL_INSNs might be merged leaving reg-stack.c with mismatching
1188 numbers of stack registers in the same basic block.
1189 If we don't check this on machines with delay slots, a delay slot may
1190 be filled that clobbers a parameter expected by the subroutine.
1192 ??? We take the simple route for now and assume that if they're
1193 equal, they were constructed identically.
1195 Also check for identical exception regions. */
1197 if (CALL_P (i1))
1199 /* Ensure the same EH region. */
1200 rtx n1 = find_reg_note (i1, REG_EH_REGION, 0);
1201 rtx n2 = find_reg_note (i2, REG_EH_REGION, 0);
1203 if (!n1 && n2)
1204 return dir_none;
1206 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1207 return dir_none;
1209 if (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
1210 CALL_INSN_FUNCTION_USAGE (i2))
1211 || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2))
1212 return dir_none;
1214 /* For address sanitizer, never crossjump __asan_report_* builtins,
1215 otherwise errors might be reported on incorrect lines. */
1216 if (flag_sanitize & SANITIZE_ADDRESS)
1218 rtx call = get_call_rtx_from (i1);
1219 if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
1221 rtx symbol = XEXP (XEXP (call, 0), 0);
1222 if (SYMBOL_REF_DECL (symbol)
1223 && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
1225 if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
1226 == BUILT_IN_NORMAL)
1227 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1228 >= BUILT_IN_ASAN_REPORT_LOAD1
1229 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1230 <= BUILT_IN_ASAN_STOREN)
1231 return dir_none;
1237 #ifdef STACK_REGS
1238 /* If cross_jump_death_matters is not 0, the insn's mode
1239 indicates whether or not the insn contains any stack-like
1240 regs. */
1242 if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
1244 /* If register stack conversion has already been done, then
1245 death notes must also be compared before it is certain that
1246 the two instruction streams match. */
1248 rtx note;
1249 HARD_REG_SET i1_regset, i2_regset;
1251 CLEAR_HARD_REG_SET (i1_regset);
1252 CLEAR_HARD_REG_SET (i2_regset);
1254 for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
1255 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1256 SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
1258 for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
1259 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1260 SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
1262 if (!hard_reg_set_equal_p (i1_regset, i2_regset))
1263 return dir_none;
1265 #endif
1267 if (reload_completed
1268 ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
1269 return dir_both;
1271 return can_replace_by (i1, i2);
1274 /* When comparing insns I1 and I2 in flow_find_cross_jump or
1275 flow_find_head_matching_sequence, ensure the notes match. */
1277 static void
1278 merge_notes (rtx_insn *i1, rtx_insn *i2)
1280 /* If the merged insns have different REG_EQUAL notes, then
1281 remove them. */
1282 rtx equiv1 = find_reg_equal_equiv_note (i1);
1283 rtx equiv2 = find_reg_equal_equiv_note (i2);
1285 if (equiv1 && !equiv2)
1286 remove_note (i1, equiv1);
1287 else if (!equiv1 && equiv2)
1288 remove_note (i2, equiv2);
1289 else if (equiv1 && equiv2
1290 && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1292 remove_note (i1, equiv1);
1293 remove_note (i2, equiv2);
1297 /* Walks from I1 in BB1 backward till the next non-debug insn, and returns the
1298 resulting insn in I1, and the corresponding bb in BB1. At the head of a
1299 bb, if there is a predecessor bb that reaches this bb via fallthru, and
1300 FOLLOW_FALLTHRU, walks further in the predecessor bb and registers this in
1301 DID_FALLTHRU. Otherwise, stops at the head of the bb. */
1303 static void
1304 walk_to_nondebug_insn (rtx_insn **i1, basic_block *bb1, bool follow_fallthru,
1305 bool *did_fallthru)
1307 edge fallthru;
1309 *did_fallthru = false;
1311 /* Ignore notes. */
1312 while (!NONDEBUG_INSN_P (*i1))
1314 if (*i1 != BB_HEAD (*bb1))
1316 *i1 = PREV_INSN (*i1);
1317 continue;
1320 if (!follow_fallthru)
1321 return;
1323 fallthru = find_fallthru_edge ((*bb1)->preds);
1324 if (!fallthru || fallthru->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
1325 || !single_succ_p (fallthru->src))
1326 return;
1328 *bb1 = fallthru->src;
1329 *i1 = BB_END (*bb1);
1330 *did_fallthru = true;
1334 /* Look through the insns at the end of BB1 and BB2 and find the longest
1335 sequence that are either equivalent, or allow forward or backward
1336 replacement. Store the first insns for that sequence in *F1 and *F2 and
1337 return the sequence length.
1339 DIR_P indicates the allowed replacement direction on function entry, and
1340 the actual replacement direction on function exit. If NULL, only equivalent
1341 sequences are allowed.
1343 To simplify callers of this function, if the blocks match exactly,
1344 store the head of the blocks in *F1 and *F2. */
1347 flow_find_cross_jump (basic_block bb1, basic_block bb2, rtx_insn **f1,
1348 rtx_insn **f2, enum replace_direction *dir_p)
1350 rtx_insn *i1, *i2, *last1, *last2, *afterlast1, *afterlast2;
1351 int ninsns = 0;
1352 enum replace_direction dir, last_dir, afterlast_dir;
1353 bool follow_fallthru, did_fallthru;
1355 if (dir_p)
1356 dir = *dir_p;
1357 else
1358 dir = dir_both;
1359 afterlast_dir = dir;
1360 last_dir = afterlast_dir;
1362 /* Skip simple jumps at the end of the blocks. Complex jumps still
1363 need to be compared for equivalence, which we'll do below. */
1365 i1 = BB_END (bb1);
1366 last1 = afterlast1 = last2 = afterlast2 = NULL;
1367 if (onlyjump_p (i1)
1368 || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1370 last1 = i1;
1371 i1 = PREV_INSN (i1);
1374 i2 = BB_END (bb2);
1375 if (onlyjump_p (i2)
1376 || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1378 last2 = i2;
1379 /* Count everything except for unconditional jump as insn.
1380 Don't count any jumps if dir_p is NULL. */
1381 if (!simplejump_p (i2) && !returnjump_p (i2) && last1 && dir_p)
1382 ninsns++;
1383 i2 = PREV_INSN (i2);
1386 while (true)
1388 /* In the following example, we can replace all jumps to C by jumps to A.
1390 This removes 4 duplicate insns.
1391 [bb A] insn1 [bb C] insn1
1392 insn2 insn2
1393 [bb B] insn3 insn3
1394 insn4 insn4
1395 jump_insn jump_insn
1397 We could also replace all jumps to A by jumps to C, but that leaves B
1398 alive, and removes only 2 duplicate insns. In a subsequent crossjump
1399 step, all jumps to B would be replaced with jumps to the middle of C,
1400 achieving the same result with more effort.
1401 So we allow only the first possibility, which means that we don't allow
1402 fallthru in the block that's being replaced. */
1404 follow_fallthru = dir_p && dir != dir_forward;
1405 walk_to_nondebug_insn (&i1, &bb1, follow_fallthru, &did_fallthru);
1406 if (did_fallthru)
1407 dir = dir_backward;
1409 follow_fallthru = dir_p && dir != dir_backward;
1410 walk_to_nondebug_insn (&i2, &bb2, follow_fallthru, &did_fallthru);
1411 if (did_fallthru)
1412 dir = dir_forward;
1414 if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1415 break;
1417 dir = merge_dir (dir, old_insns_match_p (0, i1, i2));
1418 if (dir == dir_none || (!dir_p && dir != dir_both))
1419 break;
1421 merge_memattrs (i1, i2);
1423 /* Don't begin a cross-jump with a NOTE insn. */
1424 if (INSN_P (i1))
1426 merge_notes (i1, i2);
1428 afterlast1 = last1, afterlast2 = last2;
1429 last1 = i1, last2 = i2;
1430 afterlast_dir = last_dir;
1431 last_dir = dir;
1432 if (active_insn_p (i1))
1433 ninsns++;
1436 i1 = PREV_INSN (i1);
1437 i2 = PREV_INSN (i2);
1440 /* Don't allow the insn after a compare to be shared by
1441 cross-jumping unless the compare is also shared. */
1442 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1443 && ! sets_cc0_p (last1))
1444 last1 = afterlast1, last2 = afterlast2, last_dir = afterlast_dir, ninsns--;
1446 /* Include preceding notes and labels in the cross-jump. One,
1447 this may bring us to the head of the blocks as requested above.
1448 Two, it keeps line number notes as matched as may be. */
1449 if (ninsns)
1451 bb1 = BLOCK_FOR_INSN (last1);
1452 while (last1 != BB_HEAD (bb1) && !NONDEBUG_INSN_P (PREV_INSN (last1)))
1453 last1 = PREV_INSN (last1);
1455 if (last1 != BB_HEAD (bb1) && LABEL_P (PREV_INSN (last1)))
1456 last1 = PREV_INSN (last1);
1458 bb2 = BLOCK_FOR_INSN (last2);
1459 while (last2 != BB_HEAD (bb2) && !NONDEBUG_INSN_P (PREV_INSN (last2)))
1460 last2 = PREV_INSN (last2);
1462 if (last2 != BB_HEAD (bb2) && LABEL_P (PREV_INSN (last2)))
1463 last2 = PREV_INSN (last2);
1465 *f1 = last1;
1466 *f2 = last2;
1469 if (dir_p)
1470 *dir_p = last_dir;
1471 return ninsns;
1474 /* Like flow_find_cross_jump, except start looking for a matching sequence from
1475 the head of the two blocks. Do not include jumps at the end.
1476 If STOP_AFTER is nonzero, stop after finding that many matching
1477 instructions. If STOP_AFTER is zero, count all INSN_P insns, if it is
1478 non-zero, only count active insns. */
1481 flow_find_head_matching_sequence (basic_block bb1, basic_block bb2, rtx_insn **f1,
1482 rtx_insn **f2, int stop_after)
1484 rtx_insn *i1, *i2, *last1, *last2, *beforelast1, *beforelast2;
1485 int ninsns = 0;
1486 edge e;
1487 edge_iterator ei;
1488 int nehedges1 = 0, nehedges2 = 0;
1490 FOR_EACH_EDGE (e, ei, bb1->succs)
1491 if (e->flags & EDGE_EH)
1492 nehedges1++;
1493 FOR_EACH_EDGE (e, ei, bb2->succs)
1494 if (e->flags & EDGE_EH)
1495 nehedges2++;
1497 i1 = BB_HEAD (bb1);
1498 i2 = BB_HEAD (bb2);
1499 last1 = beforelast1 = last2 = beforelast2 = NULL;
1501 while (true)
1503 /* Ignore notes, except NOTE_INSN_EPILOGUE_BEG. */
1504 while (!NONDEBUG_INSN_P (i1) && i1 != BB_END (bb1))
1506 if (NOTE_P (i1) && NOTE_KIND (i1) == NOTE_INSN_EPILOGUE_BEG)
1507 break;
1508 i1 = NEXT_INSN (i1);
1511 while (!NONDEBUG_INSN_P (i2) && i2 != BB_END (bb2))
1513 if (NOTE_P (i2) && NOTE_KIND (i2) == NOTE_INSN_EPILOGUE_BEG)
1514 break;
1515 i2 = NEXT_INSN (i2);
1518 if ((i1 == BB_END (bb1) && !NONDEBUG_INSN_P (i1))
1519 || (i2 == BB_END (bb2) && !NONDEBUG_INSN_P (i2)))
1520 break;
1522 if (NOTE_P (i1) || NOTE_P (i2)
1523 || JUMP_P (i1) || JUMP_P (i2))
1524 break;
1526 /* A sanity check to make sure we're not merging insns with different
1527 effects on EH. If only one of them ends a basic block, it shouldn't
1528 have an EH edge; if both end a basic block, there should be the same
1529 number of EH edges. */
1530 if ((i1 == BB_END (bb1) && i2 != BB_END (bb2)
1531 && nehedges1 > 0)
1532 || (i2 == BB_END (bb2) && i1 != BB_END (bb1)
1533 && nehedges2 > 0)
1534 || (i1 == BB_END (bb1) && i2 == BB_END (bb2)
1535 && nehedges1 != nehedges2))
1536 break;
1538 if (old_insns_match_p (0, i1, i2) != dir_both)
1539 break;
1541 merge_memattrs (i1, i2);
1543 /* Don't begin a cross-jump with a NOTE insn. */
1544 if (INSN_P (i1))
1546 merge_notes (i1, i2);
1548 beforelast1 = last1, beforelast2 = last2;
1549 last1 = i1, last2 = i2;
1550 if (!stop_after || active_insn_p (i1))
1551 ninsns++;
1554 if (i1 == BB_END (bb1) || i2 == BB_END (bb2)
1555 || (stop_after > 0 && ninsns == stop_after))
1556 break;
1558 i1 = NEXT_INSN (i1);
1559 i2 = NEXT_INSN (i2);
1562 /* Don't allow a compare to be shared by cross-jumping unless the insn
1563 after the compare is also shared. */
1564 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1565 && sets_cc0_p (last1))
1566 last1 = beforelast1, last2 = beforelast2, ninsns--;
1568 if (ninsns)
1570 *f1 = last1;
1571 *f2 = last2;
1574 return ninsns;
1577 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1578 the branch instruction. This means that if we commonize the control
1579 flow before end of the basic block, the semantic remains unchanged.
1581 We may assume that there exists one edge with a common destination. */
1583 static bool
1584 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1586 int nehedges1 = 0, nehedges2 = 0;
1587 edge fallthru1 = 0, fallthru2 = 0;
1588 edge e1, e2;
1589 edge_iterator ei;
1591 /* If we performed shrink-wrapping, edges to the exit block can
1592 only be distinguished for JUMP_INSNs. The two paths may differ in
1593 whether they went through the prologue. Sibcalls are fine, we know
1594 that we either didn't need or inserted an epilogue before them. */
1595 if (crtl->shrink_wrapped
1596 && single_succ_p (bb1)
1597 && single_succ (bb1) == EXIT_BLOCK_PTR_FOR_FN (cfun)
1598 && !JUMP_P (BB_END (bb1))
1599 && !(CALL_P (BB_END (bb1)) && SIBLING_CALL_P (BB_END (bb1))))
1600 return false;
1602 /* If BB1 has only one successor, we may be looking at either an
1603 unconditional jump, or a fake edge to exit. */
1604 if (single_succ_p (bb1)
1605 && (single_succ_edge (bb1)->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1606 && (!JUMP_P (BB_END (bb1)) || simplejump_p (BB_END (bb1))))
1607 return (single_succ_p (bb2)
1608 && (single_succ_edge (bb2)->flags
1609 & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1610 && (!JUMP_P (BB_END (bb2)) || simplejump_p (BB_END (bb2))));
1612 /* Match conditional jumps - this may get tricky when fallthru and branch
1613 edges are crossed. */
1614 if (EDGE_COUNT (bb1->succs) == 2
1615 && any_condjump_p (BB_END (bb1))
1616 && onlyjump_p (BB_END (bb1)))
1618 edge b1, f1, b2, f2;
1619 bool reverse, match;
1620 rtx set1, set2, cond1, cond2;
1621 enum rtx_code code1, code2;
1623 if (EDGE_COUNT (bb2->succs) != 2
1624 || !any_condjump_p (BB_END (bb2))
1625 || !onlyjump_p (BB_END (bb2)))
1626 return false;
1628 b1 = BRANCH_EDGE (bb1);
1629 b2 = BRANCH_EDGE (bb2);
1630 f1 = FALLTHRU_EDGE (bb1);
1631 f2 = FALLTHRU_EDGE (bb2);
1633 /* Get around possible forwarders on fallthru edges. Other cases
1634 should be optimized out already. */
1635 if (FORWARDER_BLOCK_P (f1->dest))
1636 f1 = single_succ_edge (f1->dest);
1638 if (FORWARDER_BLOCK_P (f2->dest))
1639 f2 = single_succ_edge (f2->dest);
1641 /* To simplify use of this function, return false if there are
1642 unneeded forwarder blocks. These will get eliminated later
1643 during cleanup_cfg. */
1644 if (FORWARDER_BLOCK_P (f1->dest)
1645 || FORWARDER_BLOCK_P (f2->dest)
1646 || FORWARDER_BLOCK_P (b1->dest)
1647 || FORWARDER_BLOCK_P (b2->dest))
1648 return false;
1650 if (f1->dest == f2->dest && b1->dest == b2->dest)
1651 reverse = false;
1652 else if (f1->dest == b2->dest && b1->dest == f2->dest)
1653 reverse = true;
1654 else
1655 return false;
1657 set1 = pc_set (BB_END (bb1));
1658 set2 = pc_set (BB_END (bb2));
1659 if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1660 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1661 reverse = !reverse;
1663 cond1 = XEXP (SET_SRC (set1), 0);
1664 cond2 = XEXP (SET_SRC (set2), 0);
1665 code1 = GET_CODE (cond1);
1666 if (reverse)
1667 code2 = reversed_comparison_code (cond2, BB_END (bb2));
1668 else
1669 code2 = GET_CODE (cond2);
1671 if (code2 == UNKNOWN)
1672 return false;
1674 /* Verify codes and operands match. */
1675 match = ((code1 == code2
1676 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1677 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1678 || (code1 == swap_condition (code2)
1679 && rtx_renumbered_equal_p (XEXP (cond1, 1),
1680 XEXP (cond2, 0))
1681 && rtx_renumbered_equal_p (XEXP (cond1, 0),
1682 XEXP (cond2, 1))));
1684 /* If we return true, we will join the blocks. Which means that
1685 we will only have one branch prediction bit to work with. Thus
1686 we require the existing branches to have probabilities that are
1687 roughly similar. */
1688 if (match
1689 && optimize_bb_for_speed_p (bb1)
1690 && optimize_bb_for_speed_p (bb2))
1692 int prob2;
1694 if (b1->dest == b2->dest)
1695 prob2 = b2->probability;
1696 else
1697 /* Do not use f2 probability as f2 may be forwarded. */
1698 prob2 = REG_BR_PROB_BASE - b2->probability;
1700 /* Fail if the difference in probabilities is greater than 50%.
1701 This rules out two well-predicted branches with opposite
1702 outcomes. */
1703 if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1705 if (dump_file)
1706 fprintf (dump_file,
1707 "Outcomes of branch in bb %i and %i differ too much (%i %i)\n",
1708 bb1->index, bb2->index, b1->probability, prob2);
1710 return false;
1714 if (dump_file && match)
1715 fprintf (dump_file, "Conditionals in bb %i and %i match.\n",
1716 bb1->index, bb2->index);
1718 return match;
1721 /* Generic case - we are seeing a computed jump, table jump or trapping
1722 instruction. */
1724 /* Check whether there are tablejumps in the end of BB1 and BB2.
1725 Return true if they are identical. */
1727 rtx label1, label2;
1728 rtx_jump_table_data *table1, *table2;
1730 if (tablejump_p (BB_END (bb1), &label1, &table1)
1731 && tablejump_p (BB_END (bb2), &label2, &table2)
1732 && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1734 /* The labels should never be the same rtx. If they really are same
1735 the jump tables are same too. So disable crossjumping of blocks BB1
1736 and BB2 because when deleting the common insns in the end of BB1
1737 by delete_basic_block () the jump table would be deleted too. */
1738 /* If LABEL2 is referenced in BB1->END do not do anything
1739 because we would loose information when replacing
1740 LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END. */
1741 if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1743 /* Set IDENTICAL to true when the tables are identical. */
1744 bool identical = false;
1745 rtx p1, p2;
1747 p1 = PATTERN (table1);
1748 p2 = PATTERN (table2);
1749 if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1751 identical = true;
1753 else if (GET_CODE (p1) == ADDR_DIFF_VEC
1754 && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1755 && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1756 && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1758 int i;
1760 identical = true;
1761 for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1762 if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1763 identical = false;
1766 if (identical)
1768 bool match;
1770 /* Temporarily replace references to LABEL1 with LABEL2
1771 in BB1->END so that we could compare the instructions. */
1772 replace_label_in_insn (BB_END (bb1), label1, label2, false);
1774 match = (old_insns_match_p (mode, BB_END (bb1), BB_END (bb2))
1775 == dir_both);
1776 if (dump_file && match)
1777 fprintf (dump_file,
1778 "Tablejumps in bb %i and %i match.\n",
1779 bb1->index, bb2->index);
1781 /* Set the original label in BB1->END because when deleting
1782 a block whose end is a tablejump, the tablejump referenced
1783 from the instruction is deleted too. */
1784 replace_label_in_insn (BB_END (bb1), label2, label1, false);
1786 return match;
1789 return false;
1793 /* Find the last non-debug non-note instruction in each bb, except
1794 stop when we see the NOTE_INSN_BASIC_BLOCK, as old_insns_match_p
1795 handles that case specially. old_insns_match_p does not handle
1796 other types of instruction notes. */
1797 rtx_insn *last1 = BB_END (bb1);
1798 rtx_insn *last2 = BB_END (bb2);
1799 while (!NOTE_INSN_BASIC_BLOCK_P (last1) &&
1800 (DEBUG_INSN_P (last1) || NOTE_P (last1)))
1801 last1 = PREV_INSN (last1);
1802 while (!NOTE_INSN_BASIC_BLOCK_P (last2) &&
1803 (DEBUG_INSN_P (last2) || NOTE_P (last2)))
1804 last2 = PREV_INSN (last2);
1805 gcc_assert (last1 && last2);
1807 /* First ensure that the instructions match. There may be many outgoing
1808 edges so this test is generally cheaper. */
1809 if (old_insns_match_p (mode, last1, last2) != dir_both)
1810 return false;
1812 /* Search the outgoing edges, ensure that the counts do match, find possible
1813 fallthru and exception handling edges since these needs more
1814 validation. */
1815 if (EDGE_COUNT (bb1->succs) != EDGE_COUNT (bb2->succs))
1816 return false;
1818 bool nonfakeedges = false;
1819 FOR_EACH_EDGE (e1, ei, bb1->succs)
1821 e2 = EDGE_SUCC (bb2, ei.index);
1823 if ((e1->flags & EDGE_FAKE) == 0)
1824 nonfakeedges = true;
1826 if (e1->flags & EDGE_EH)
1827 nehedges1++;
1829 if (e2->flags & EDGE_EH)
1830 nehedges2++;
1832 if (e1->flags & EDGE_FALLTHRU)
1833 fallthru1 = e1;
1834 if (e2->flags & EDGE_FALLTHRU)
1835 fallthru2 = e2;
1838 /* If number of edges of various types does not match, fail. */
1839 if (nehedges1 != nehedges2
1840 || (fallthru1 != 0) != (fallthru2 != 0))
1841 return false;
1843 /* If !ACCUMULATE_OUTGOING_ARGS, bb1 (and bb2) have no successors
1844 and the last real insn doesn't have REG_ARGS_SIZE note, don't
1845 attempt to optimize, as the two basic blocks might have different
1846 REG_ARGS_SIZE depths. For noreturn calls and unconditional
1847 traps there should be REG_ARG_SIZE notes, they could be missing
1848 for __builtin_unreachable () uses though. */
1849 if (!nonfakeedges
1850 && !ACCUMULATE_OUTGOING_ARGS
1851 && (!INSN_P (last1)
1852 || !find_reg_note (last1, REG_ARGS_SIZE, NULL)))
1853 return false;
1855 /* fallthru edges must be forwarded to the same destination. */
1856 if (fallthru1)
1858 basic_block d1 = (forwarder_block_p (fallthru1->dest)
1859 ? single_succ (fallthru1->dest): fallthru1->dest);
1860 basic_block d2 = (forwarder_block_p (fallthru2->dest)
1861 ? single_succ (fallthru2->dest): fallthru2->dest);
1863 if (d1 != d2)
1864 return false;
1867 /* Ensure the same EH region. */
1869 rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1870 rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1872 if (!n1 && n2)
1873 return false;
1875 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1876 return false;
1879 /* The same checks as in try_crossjump_to_edge. It is required for RTL
1880 version of sequence abstraction. */
1881 FOR_EACH_EDGE (e1, ei, bb2->succs)
1883 edge e2;
1884 edge_iterator ei;
1885 basic_block d1 = e1->dest;
1887 if (FORWARDER_BLOCK_P (d1))
1888 d1 = EDGE_SUCC (d1, 0)->dest;
1890 FOR_EACH_EDGE (e2, ei, bb1->succs)
1892 basic_block d2 = e2->dest;
1893 if (FORWARDER_BLOCK_P (d2))
1894 d2 = EDGE_SUCC (d2, 0)->dest;
1895 if (d1 == d2)
1896 break;
1899 if (!e2)
1900 return false;
1903 return true;
1906 /* Returns true if BB basic block has a preserve label. */
1908 static bool
1909 block_has_preserve_label (basic_block bb)
1911 return (bb
1912 && block_label (bb)
1913 && LABEL_PRESERVE_P (block_label (bb)));
1916 /* E1 and E2 are edges with the same destination block. Search their
1917 predecessors for common code. If found, redirect control flow from
1918 (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC (dir_forward),
1919 or the other way around (dir_backward). DIR specifies the allowed
1920 replacement direction. */
1922 static bool
1923 try_crossjump_to_edge (int mode, edge e1, edge e2,
1924 enum replace_direction dir)
1926 int nmatch;
1927 basic_block src1 = e1->src, src2 = e2->src;
1928 basic_block redirect_to, redirect_from, to_remove;
1929 basic_block osrc1, osrc2, redirect_edges_to, tmp;
1930 rtx_insn *newpos1, *newpos2;
1931 edge s;
1932 edge_iterator ei;
1934 newpos1 = newpos2 = NULL;
1936 /* If we have partitioned hot/cold basic blocks, it is a bad idea
1937 to try this optimization.
1939 Basic block partitioning may result in some jumps that appear to
1940 be optimizable (or blocks that appear to be mergeable), but which really
1941 must be left untouched (they are required to make it safely across
1942 partition boundaries). See the comments at the top of
1943 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
1945 if (crtl->has_bb_partition && reload_completed)
1946 return false;
1948 /* Search backward through forwarder blocks. We don't need to worry
1949 about multiple entry or chained forwarders, as they will be optimized
1950 away. We do this to look past the unconditional jump following a
1951 conditional jump that is required due to the current CFG shape. */
1952 if (single_pred_p (src1)
1953 && FORWARDER_BLOCK_P (src1))
1954 e1 = single_pred_edge (src1), src1 = e1->src;
1956 if (single_pred_p (src2)
1957 && FORWARDER_BLOCK_P (src2))
1958 e2 = single_pred_edge (src2), src2 = e2->src;
1960 /* Nothing to do if we reach ENTRY, or a common source block. */
1961 if (src1 == ENTRY_BLOCK_PTR_FOR_FN (cfun) || src2
1962 == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1963 return false;
1964 if (src1 == src2)
1965 return false;
1967 /* Seeing more than 1 forwarder blocks would confuse us later... */
1968 if (FORWARDER_BLOCK_P (e1->dest)
1969 && FORWARDER_BLOCK_P (single_succ (e1->dest)))
1970 return false;
1972 if (FORWARDER_BLOCK_P (e2->dest)
1973 && FORWARDER_BLOCK_P (single_succ (e2->dest)))
1974 return false;
1976 /* Likewise with dead code (possibly newly created by the other optimizations
1977 of cfg_cleanup). */
1978 if (EDGE_COUNT (src1->preds) == 0 || EDGE_COUNT (src2->preds) == 0)
1979 return false;
1981 /* Look for the common insn sequence, part the first ... */
1982 if (!outgoing_edges_match (mode, src1, src2))
1983 return false;
1985 /* ... and part the second. */
1986 nmatch = flow_find_cross_jump (src1, src2, &newpos1, &newpos2, &dir);
1988 osrc1 = src1;
1989 osrc2 = src2;
1990 if (newpos1 != NULL_RTX)
1991 src1 = BLOCK_FOR_INSN (newpos1);
1992 if (newpos2 != NULL_RTX)
1993 src2 = BLOCK_FOR_INSN (newpos2);
1995 if (dir == dir_backward)
1997 #define SWAP(T, X, Y) do { T tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
1998 SWAP (basic_block, osrc1, osrc2);
1999 SWAP (basic_block, src1, src2);
2000 SWAP (edge, e1, e2);
2001 SWAP (rtx_insn *, newpos1, newpos2);
2002 #undef SWAP
2005 /* Don't proceed with the crossjump unless we found a sufficient number
2006 of matching instructions or the 'from' block was totally matched
2007 (such that its predecessors will hopefully be redirected and the
2008 block removed). */
2009 if ((nmatch < PARAM_VALUE (PARAM_MIN_CROSSJUMP_INSNS))
2010 && (newpos1 != BB_HEAD (src1)))
2011 return false;
2013 /* Avoid deleting preserve label when redirecting ABNORMAL edges. */
2014 if (block_has_preserve_label (e1->dest)
2015 && (e1->flags & EDGE_ABNORMAL))
2016 return false;
2018 /* Here we know that the insns in the end of SRC1 which are common with SRC2
2019 will be deleted.
2020 If we have tablejumps in the end of SRC1 and SRC2
2021 they have been already compared for equivalence in outgoing_edges_match ()
2022 so replace the references to TABLE1 by references to TABLE2. */
2024 rtx label1, label2;
2025 rtx_jump_table_data *table1, *table2;
2027 if (tablejump_p (BB_END (osrc1), &label1, &table1)
2028 && tablejump_p (BB_END (osrc2), &label2, &table2)
2029 && label1 != label2)
2031 rtx_insn *insn;
2033 /* Replace references to LABEL1 with LABEL2. */
2034 for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2036 /* Do not replace the label in SRC1->END because when deleting
2037 a block whose end is a tablejump, the tablejump referenced
2038 from the instruction is deleted too. */
2039 if (insn != BB_END (osrc1))
2040 replace_label_in_insn (insn, label1, label2, true);
2045 /* Avoid splitting if possible. We must always split when SRC2 has
2046 EH predecessor edges, or we may end up with basic blocks with both
2047 normal and EH predecessor edges. */
2048 if (newpos2 == BB_HEAD (src2)
2049 && !(EDGE_PRED (src2, 0)->flags & EDGE_EH))
2050 redirect_to = src2;
2051 else
2053 if (newpos2 == BB_HEAD (src2))
2055 /* Skip possible basic block header. */
2056 if (LABEL_P (newpos2))
2057 newpos2 = NEXT_INSN (newpos2);
2058 while (DEBUG_INSN_P (newpos2))
2059 newpos2 = NEXT_INSN (newpos2);
2060 if (NOTE_P (newpos2))
2061 newpos2 = NEXT_INSN (newpos2);
2062 while (DEBUG_INSN_P (newpos2))
2063 newpos2 = NEXT_INSN (newpos2);
2066 if (dump_file)
2067 fprintf (dump_file, "Splitting bb %i before %i insns\n",
2068 src2->index, nmatch);
2069 redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
2072 if (dump_file)
2073 fprintf (dump_file,
2074 "Cross jumping from bb %i to bb %i; %i common insns\n",
2075 src1->index, src2->index, nmatch);
2077 /* We may have some registers visible through the block. */
2078 df_set_bb_dirty (redirect_to);
2080 if (osrc2 == src2)
2081 redirect_edges_to = redirect_to;
2082 else
2083 redirect_edges_to = osrc2;
2085 /* Recompute the frequencies and counts of outgoing edges. */
2086 FOR_EACH_EDGE (s, ei, redirect_edges_to->succs)
2088 edge s2;
2089 edge_iterator ei;
2090 basic_block d = s->dest;
2092 if (FORWARDER_BLOCK_P (d))
2093 d = single_succ (d);
2095 FOR_EACH_EDGE (s2, ei, src1->succs)
2097 basic_block d2 = s2->dest;
2098 if (FORWARDER_BLOCK_P (d2))
2099 d2 = single_succ (d2);
2100 if (d == d2)
2101 break;
2104 s->count += s2->count;
2106 /* Take care to update possible forwarder blocks. We verified
2107 that there is no more than one in the chain, so we can't run
2108 into infinite loop. */
2109 if (FORWARDER_BLOCK_P (s->dest))
2111 single_succ_edge (s->dest)->count += s2->count;
2112 s->dest->count += s2->count;
2113 s->dest->frequency += EDGE_FREQUENCY (s);
2116 if (FORWARDER_BLOCK_P (s2->dest))
2118 single_succ_edge (s2->dest)->count -= s2->count;
2119 if (single_succ_edge (s2->dest)->count < 0)
2120 single_succ_edge (s2->dest)->count = 0;
2121 s2->dest->count -= s2->count;
2122 s2->dest->frequency -= EDGE_FREQUENCY (s);
2123 if (s2->dest->frequency < 0)
2124 s2->dest->frequency = 0;
2125 if (s2->dest->count < 0)
2126 s2->dest->count = 0;
2129 if (!redirect_edges_to->frequency && !src1->frequency)
2130 s->probability = (s->probability + s2->probability) / 2;
2131 else
2132 s->probability
2133 = ((s->probability * redirect_edges_to->frequency +
2134 s2->probability * src1->frequency)
2135 / (redirect_edges_to->frequency + src1->frequency));
2138 /* Adjust count and frequency for the block. An earlier jump
2139 threading pass may have left the profile in an inconsistent
2140 state (see update_bb_profile_for_threading) so we must be
2141 prepared for overflows. */
2142 tmp = redirect_to;
2145 tmp->count += src1->count;
2146 tmp->frequency += src1->frequency;
2147 if (tmp->frequency > BB_FREQ_MAX)
2148 tmp->frequency = BB_FREQ_MAX;
2149 if (tmp == redirect_edges_to)
2150 break;
2151 tmp = find_fallthru_edge (tmp->succs)->dest;
2153 while (true);
2154 update_br_prob_note (redirect_edges_to);
2156 /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1. */
2158 /* Skip possible basic block header. */
2159 if (LABEL_P (newpos1))
2160 newpos1 = NEXT_INSN (newpos1);
2162 while (DEBUG_INSN_P (newpos1))
2163 newpos1 = NEXT_INSN (newpos1);
2165 if (NOTE_INSN_BASIC_BLOCK_P (newpos1))
2166 newpos1 = NEXT_INSN (newpos1);
2168 while (DEBUG_INSN_P (newpos1))
2169 newpos1 = NEXT_INSN (newpos1);
2171 redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
2172 to_remove = single_succ (redirect_from);
2174 redirect_edge_and_branch_force (single_succ_edge (redirect_from), redirect_to);
2175 delete_basic_block (to_remove);
2177 update_forwarder_flag (redirect_from);
2178 if (redirect_to != src2)
2179 update_forwarder_flag (src2);
2181 return true;
2184 /* Search the predecessors of BB for common insn sequences. When found,
2185 share code between them by redirecting control flow. Return true if
2186 any changes made. */
2188 static bool
2189 try_crossjump_bb (int mode, basic_block bb)
2191 edge e, e2, fallthru;
2192 bool changed;
2193 unsigned max, ix, ix2;
2195 /* Nothing to do if there is not at least two incoming edges. */
2196 if (EDGE_COUNT (bb->preds) < 2)
2197 return false;
2199 /* Don't crossjump if this block ends in a computed jump,
2200 unless we are optimizing for size. */
2201 if (optimize_bb_for_size_p (bb)
2202 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2203 && computed_jump_p (BB_END (bb)))
2204 return false;
2206 /* If we are partitioning hot/cold basic blocks, we don't want to
2207 mess up unconditional or indirect jumps that cross between hot
2208 and cold sections.
2210 Basic block partitioning may result in some jumps that appear to
2211 be optimizable (or blocks that appear to be mergeable), but which really
2212 must be left untouched (they are required to make it safely across
2213 partition boundaries). See the comments at the top of
2214 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
2216 if (BB_PARTITION (EDGE_PRED (bb, 0)->src) !=
2217 BB_PARTITION (EDGE_PRED (bb, 1)->src)
2218 || (EDGE_PRED (bb, 0)->flags & EDGE_CROSSING))
2219 return false;
2221 /* It is always cheapest to redirect a block that ends in a branch to
2222 a block that falls through into BB, as that adds no branches to the
2223 program. We'll try that combination first. */
2224 fallthru = NULL;
2225 max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
2227 if (EDGE_COUNT (bb->preds) > max)
2228 return false;
2230 fallthru = find_fallthru_edge (bb->preds);
2232 changed = false;
2233 for (ix = 0; ix < EDGE_COUNT (bb->preds);)
2235 e = EDGE_PRED (bb, ix);
2236 ix++;
2238 /* As noted above, first try with the fallthru predecessor (or, a
2239 fallthru predecessor if we are in cfglayout mode). */
2240 if (fallthru)
2242 /* Don't combine the fallthru edge into anything else.
2243 If there is a match, we'll do it the other way around. */
2244 if (e == fallthru)
2245 continue;
2246 /* If nothing changed since the last attempt, there is nothing
2247 we can do. */
2248 if (!first_pass
2249 && !((e->src->flags & BB_MODIFIED)
2250 || (fallthru->src->flags & BB_MODIFIED)))
2251 continue;
2253 if (try_crossjump_to_edge (mode, e, fallthru, dir_forward))
2255 changed = true;
2256 ix = 0;
2257 continue;
2261 /* Non-obvious work limiting check: Recognize that we're going
2262 to call try_crossjump_bb on every basic block. So if we have
2263 two blocks with lots of outgoing edges (a switch) and they
2264 share lots of common destinations, then we would do the
2265 cross-jump check once for each common destination.
2267 Now, if the blocks actually are cross-jump candidates, then
2268 all of their destinations will be shared. Which means that
2269 we only need check them for cross-jump candidacy once. We
2270 can eliminate redundant checks of crossjump(A,B) by arbitrarily
2271 choosing to do the check from the block for which the edge
2272 in question is the first successor of A. */
2273 if (EDGE_SUCC (e->src, 0) != e)
2274 continue;
2276 for (ix2 = 0; ix2 < EDGE_COUNT (bb->preds); ix2++)
2278 e2 = EDGE_PRED (bb, ix2);
2280 if (e2 == e)
2281 continue;
2283 /* We've already checked the fallthru edge above. */
2284 if (e2 == fallthru)
2285 continue;
2287 /* The "first successor" check above only prevents multiple
2288 checks of crossjump(A,B). In order to prevent redundant
2289 checks of crossjump(B,A), require that A be the block
2290 with the lowest index. */
2291 if (e->src->index > e2->src->index)
2292 continue;
2294 /* If nothing changed since the last attempt, there is nothing
2295 we can do. */
2296 if (!first_pass
2297 && !((e->src->flags & BB_MODIFIED)
2298 || (e2->src->flags & BB_MODIFIED)))
2299 continue;
2301 /* Both e and e2 are not fallthru edges, so we can crossjump in either
2302 direction. */
2303 if (try_crossjump_to_edge (mode, e, e2, dir_both))
2305 changed = true;
2306 ix = 0;
2307 break;
2312 if (changed)
2313 crossjumps_occured = true;
2315 return changed;
2318 /* Search the successors of BB for common insn sequences. When found,
2319 share code between them by moving it across the basic block
2320 boundary. Return true if any changes made. */
2322 static bool
2323 try_head_merge_bb (basic_block bb)
2325 basic_block final_dest_bb = NULL;
2326 int max_match = INT_MAX;
2327 edge e0;
2328 rtx_insn **headptr, **currptr, **nextptr;
2329 bool changed, moveall;
2330 unsigned ix;
2331 rtx_insn *e0_last_head;
2332 rtx cond;
2333 rtx_insn *move_before;
2334 unsigned nedges = EDGE_COUNT (bb->succs);
2335 rtx_insn *jump = BB_END (bb);
2336 regset live, live_union;
2338 /* Nothing to do if there is not at least two outgoing edges. */
2339 if (nedges < 2)
2340 return false;
2342 /* Don't crossjump if this block ends in a computed jump,
2343 unless we are optimizing for size. */
2344 if (optimize_bb_for_size_p (bb)
2345 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2346 && computed_jump_p (BB_END (bb)))
2347 return false;
2349 cond = get_condition (jump, &move_before, true, false);
2350 if (cond == NULL_RTX)
2352 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2353 move_before = prev_nonnote_nondebug_insn (jump);
2354 else
2355 move_before = jump;
2358 for (ix = 0; ix < nedges; ix++)
2359 if (EDGE_SUCC (bb, ix)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
2360 return false;
2362 for (ix = 0; ix < nedges; ix++)
2364 edge e = EDGE_SUCC (bb, ix);
2365 basic_block other_bb = e->dest;
2367 if (df_get_bb_dirty (other_bb))
2369 block_was_dirty = true;
2370 return false;
2373 if (e->flags & EDGE_ABNORMAL)
2374 return false;
2376 /* Normally, all destination blocks must only be reachable from this
2377 block, i.e. they must have one incoming edge.
2379 There is one special case we can handle, that of multiple consecutive
2380 jumps where the first jumps to one of the targets of the second jump.
2381 This happens frequently in switch statements for default labels.
2382 The structure is as follows:
2383 FINAL_DEST_BB
2384 ....
2385 if (cond) jump A;
2386 fall through
2388 jump with targets A, B, C, D...
2390 has two incoming edges, from FINAL_DEST_BB and BB
2392 In this case, we can try to move the insns through BB and into
2393 FINAL_DEST_BB. */
2394 if (EDGE_COUNT (other_bb->preds) != 1)
2396 edge incoming_edge, incoming_bb_other_edge;
2397 edge_iterator ei;
2399 if (final_dest_bb != NULL
2400 || EDGE_COUNT (other_bb->preds) != 2)
2401 return false;
2403 /* We must be able to move the insns across the whole block. */
2404 move_before = BB_HEAD (bb);
2405 while (!NONDEBUG_INSN_P (move_before))
2406 move_before = NEXT_INSN (move_before);
2408 if (EDGE_COUNT (bb->preds) != 1)
2409 return false;
2410 incoming_edge = EDGE_PRED (bb, 0);
2411 final_dest_bb = incoming_edge->src;
2412 if (EDGE_COUNT (final_dest_bb->succs) != 2)
2413 return false;
2414 FOR_EACH_EDGE (incoming_bb_other_edge, ei, final_dest_bb->succs)
2415 if (incoming_bb_other_edge != incoming_edge)
2416 break;
2417 if (incoming_bb_other_edge->dest != other_bb)
2418 return false;
2422 e0 = EDGE_SUCC (bb, 0);
2423 e0_last_head = NULL;
2424 changed = false;
2426 for (ix = 1; ix < nedges; ix++)
2428 edge e = EDGE_SUCC (bb, ix);
2429 rtx_insn *e0_last, *e_last;
2430 int nmatch;
2432 nmatch = flow_find_head_matching_sequence (e0->dest, e->dest,
2433 &e0_last, &e_last, 0);
2434 if (nmatch == 0)
2435 return false;
2437 if (nmatch < max_match)
2439 max_match = nmatch;
2440 e0_last_head = e0_last;
2444 /* If we matched an entire block, we probably have to avoid moving the
2445 last insn. */
2446 if (max_match > 0
2447 && e0_last_head == BB_END (e0->dest)
2448 && (find_reg_note (e0_last_head, REG_EH_REGION, 0)
2449 || control_flow_insn_p (e0_last_head)))
2451 max_match--;
2452 if (max_match == 0)
2453 return false;
2455 e0_last_head = prev_real_insn (e0_last_head);
2456 while (DEBUG_INSN_P (e0_last_head));
2459 if (max_match == 0)
2460 return false;
2462 /* We must find a union of the live registers at each of the end points. */
2463 live = BITMAP_ALLOC (NULL);
2464 live_union = BITMAP_ALLOC (NULL);
2466 currptr = XNEWVEC (rtx_insn *, nedges);
2467 headptr = XNEWVEC (rtx_insn *, nedges);
2468 nextptr = XNEWVEC (rtx_insn *, nedges);
2470 for (ix = 0; ix < nedges; ix++)
2472 int j;
2473 basic_block merge_bb = EDGE_SUCC (bb, ix)->dest;
2474 rtx_insn *head = BB_HEAD (merge_bb);
2476 while (!NONDEBUG_INSN_P (head))
2477 head = NEXT_INSN (head);
2478 headptr[ix] = head;
2479 currptr[ix] = head;
2481 /* Compute the end point and live information */
2482 for (j = 1; j < max_match; j++)
2484 head = NEXT_INSN (head);
2485 while (!NONDEBUG_INSN_P (head));
2486 simulate_backwards_to_point (merge_bb, live, head);
2487 IOR_REG_SET (live_union, live);
2490 /* If we're moving across two blocks, verify the validity of the
2491 first move, then adjust the target and let the loop below deal
2492 with the final move. */
2493 if (final_dest_bb != NULL)
2495 rtx_insn *move_upto;
2497 moveall = can_move_insns_across (currptr[0], e0_last_head, move_before,
2498 jump, e0->dest, live_union,
2499 NULL, &move_upto);
2500 if (!moveall)
2502 if (move_upto == NULL_RTX)
2503 goto out;
2505 while (e0_last_head != move_upto)
2507 df_simulate_one_insn_backwards (e0->dest, e0_last_head,
2508 live_union);
2509 e0_last_head = PREV_INSN (e0_last_head);
2512 if (e0_last_head == NULL_RTX)
2513 goto out;
2515 jump = BB_END (final_dest_bb);
2516 cond = get_condition (jump, &move_before, true, false);
2517 if (cond == NULL_RTX)
2519 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2520 move_before = prev_nonnote_nondebug_insn (jump);
2521 else
2522 move_before = jump;
2528 rtx_insn *move_upto;
2529 moveall = can_move_insns_across (currptr[0], e0_last_head,
2530 move_before, jump, e0->dest, live_union,
2531 NULL, &move_upto);
2532 if (!moveall && move_upto == NULL_RTX)
2534 if (jump == move_before)
2535 break;
2537 /* Try again, using a different insertion point. */
2538 move_before = jump;
2540 /* Don't try moving before a cc0 user, as that may invalidate
2541 the cc0. */
2542 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2543 break;
2545 continue;
2548 if (final_dest_bb && !moveall)
2549 /* We haven't checked whether a partial move would be OK for the first
2550 move, so we have to fail this case. */
2551 break;
2553 changed = true;
2554 for (;;)
2556 if (currptr[0] == move_upto)
2557 break;
2558 for (ix = 0; ix < nedges; ix++)
2560 rtx_insn *curr = currptr[ix];
2562 curr = NEXT_INSN (curr);
2563 while (!NONDEBUG_INSN_P (curr));
2564 currptr[ix] = curr;
2568 /* If we can't currently move all of the identical insns, remember
2569 each insn after the range that we'll merge. */
2570 if (!moveall)
2571 for (ix = 0; ix < nedges; ix++)
2573 rtx_insn *curr = currptr[ix];
2575 curr = NEXT_INSN (curr);
2576 while (!NONDEBUG_INSN_P (curr));
2577 nextptr[ix] = curr;
2580 reorder_insns (headptr[0], currptr[0], PREV_INSN (move_before));
2581 df_set_bb_dirty (EDGE_SUCC (bb, 0)->dest);
2582 if (final_dest_bb != NULL)
2583 df_set_bb_dirty (final_dest_bb);
2584 df_set_bb_dirty (bb);
2585 for (ix = 1; ix < nedges; ix++)
2587 df_set_bb_dirty (EDGE_SUCC (bb, ix)->dest);
2588 delete_insn_chain (headptr[ix], currptr[ix], false);
2590 if (!moveall)
2592 if (jump == move_before)
2593 break;
2595 /* For the unmerged insns, try a different insertion point. */
2596 move_before = jump;
2598 /* Don't try moving before a cc0 user, as that may invalidate
2599 the cc0. */
2600 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2601 break;
2603 for (ix = 0; ix < nedges; ix++)
2604 currptr[ix] = headptr[ix] = nextptr[ix];
2607 while (!moveall);
2609 out:
2610 free (currptr);
2611 free (headptr);
2612 free (nextptr);
2614 crossjumps_occured |= changed;
2616 return changed;
2619 /* Return true if BB contains just bb note, or bb note followed
2620 by only DEBUG_INSNs. */
2622 static bool
2623 trivially_empty_bb_p (basic_block bb)
2625 rtx_insn *insn = BB_END (bb);
2627 while (1)
2629 if (insn == BB_HEAD (bb))
2630 return true;
2631 if (!DEBUG_INSN_P (insn))
2632 return false;
2633 insn = PREV_INSN (insn);
2637 /* Do simple CFG optimizations - basic block merging, simplifying of jump
2638 instructions etc. Return nonzero if changes were made. */
2640 static bool
2641 try_optimize_cfg (int mode)
2643 bool changed_overall = false;
2644 bool changed;
2645 int iterations = 0;
2646 basic_block bb, b, next;
2648 if (mode & (CLEANUP_CROSSJUMP | CLEANUP_THREADING))
2649 clear_bb_flags ();
2651 crossjumps_occured = false;
2653 FOR_EACH_BB_FN (bb, cfun)
2654 update_forwarder_flag (bb);
2656 if (! targetm.cannot_modify_jumps_p ())
2658 first_pass = true;
2659 /* Attempt to merge blocks as made possible by edge removal. If
2660 a block has only one successor, and the successor has only
2661 one predecessor, they may be combined. */
2664 block_was_dirty = false;
2665 changed = false;
2666 iterations++;
2668 if (dump_file)
2669 fprintf (dump_file,
2670 "\n\ntry_optimize_cfg iteration %i\n\n",
2671 iterations);
2673 for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
2674 != EXIT_BLOCK_PTR_FOR_FN (cfun);)
2676 basic_block c;
2677 edge s;
2678 bool changed_here = false;
2680 /* Delete trivially dead basic blocks. This is either
2681 blocks with no predecessors, or empty blocks with no
2682 successors. However if the empty block with no
2683 successors is the successor of the ENTRY_BLOCK, it is
2684 kept. This ensures that the ENTRY_BLOCK will have a
2685 successor which is a precondition for many RTL
2686 passes. Empty blocks may result from expanding
2687 __builtin_unreachable (). */
2688 if (EDGE_COUNT (b->preds) == 0
2689 || (EDGE_COUNT (b->succs) == 0
2690 && trivially_empty_bb_p (b)
2691 && single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->dest
2692 != b))
2694 c = b->prev_bb;
2695 if (EDGE_COUNT (b->preds) > 0)
2697 edge e;
2698 edge_iterator ei;
2700 if (current_ir_type () == IR_RTL_CFGLAYOUT)
2702 if (BB_FOOTER (b)
2703 && BARRIER_P (BB_FOOTER (b)))
2704 FOR_EACH_EDGE (e, ei, b->preds)
2705 if ((e->flags & EDGE_FALLTHRU)
2706 && BB_FOOTER (e->src) == NULL)
2708 if (BB_FOOTER (b))
2710 BB_FOOTER (e->src) = BB_FOOTER (b);
2711 BB_FOOTER (b) = NULL;
2713 else
2715 start_sequence ();
2716 BB_FOOTER (e->src) = emit_barrier ();
2717 end_sequence ();
2721 else
2723 rtx_insn *last = get_last_bb_insn (b);
2724 if (last && BARRIER_P (last))
2725 FOR_EACH_EDGE (e, ei, b->preds)
2726 if ((e->flags & EDGE_FALLTHRU))
2727 emit_barrier_after (BB_END (e->src));
2730 delete_basic_block (b);
2731 changed = true;
2732 /* Avoid trying to remove the exit block. */
2733 b = (c == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? c->next_bb : c);
2734 continue;
2737 /* Remove code labels no longer used. */
2738 if (single_pred_p (b)
2739 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2740 && !(single_pred_edge (b)->flags & EDGE_COMPLEX)
2741 && LABEL_P (BB_HEAD (b))
2742 && !LABEL_PRESERVE_P (BB_HEAD (b))
2743 /* If the previous block ends with a branch to this
2744 block, we can't delete the label. Normally this
2745 is a condjump that is yet to be simplified, but
2746 if CASE_DROPS_THRU, this can be a tablejump with
2747 some element going to the same place as the
2748 default (fallthru). */
2749 && (single_pred (b) == ENTRY_BLOCK_PTR_FOR_FN (cfun)
2750 || !JUMP_P (BB_END (single_pred (b)))
2751 || ! label_is_jump_target_p (BB_HEAD (b),
2752 BB_END (single_pred (b)))))
2754 delete_insn (BB_HEAD (b));
2755 if (dump_file)
2756 fprintf (dump_file, "Deleted label in block %i.\n",
2757 b->index);
2760 /* If we fall through an empty block, we can remove it. */
2761 if (!(mode & (CLEANUP_CFGLAYOUT | CLEANUP_NO_INSN_DEL))
2762 && single_pred_p (b)
2763 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2764 && !LABEL_P (BB_HEAD (b))
2765 && FORWARDER_BLOCK_P (b)
2766 /* Note that forwarder_block_p true ensures that
2767 there is a successor for this block. */
2768 && (single_succ_edge (b)->flags & EDGE_FALLTHRU)
2769 && n_basic_blocks_for_fn (cfun) > NUM_FIXED_BLOCKS + 1)
2771 if (dump_file)
2772 fprintf (dump_file,
2773 "Deleting fallthru block %i.\n",
2774 b->index);
2776 c = ((b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
2777 ? b->next_bb : b->prev_bb);
2778 redirect_edge_succ_nodup (single_pred_edge (b),
2779 single_succ (b));
2780 delete_basic_block (b);
2781 changed = true;
2782 b = c;
2783 continue;
2786 /* Merge B with its single successor, if any. */
2787 if (single_succ_p (b)
2788 && (s = single_succ_edge (b))
2789 && !(s->flags & EDGE_COMPLEX)
2790 && (c = s->dest) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2791 && single_pred_p (c)
2792 && b != c)
2794 /* When not in cfg_layout mode use code aware of reordering
2795 INSN. This code possibly creates new basic blocks so it
2796 does not fit merge_blocks interface and is kept here in
2797 hope that it will become useless once more of compiler
2798 is transformed to use cfg_layout mode. */
2800 if ((mode & CLEANUP_CFGLAYOUT)
2801 && can_merge_blocks_p (b, c))
2803 merge_blocks (b, c);
2804 update_forwarder_flag (b);
2805 changed_here = true;
2807 else if (!(mode & CLEANUP_CFGLAYOUT)
2808 /* If the jump insn has side effects,
2809 we can't kill the edge. */
2810 && (!JUMP_P (BB_END (b))
2811 || (reload_completed
2812 ? simplejump_p (BB_END (b))
2813 : (onlyjump_p (BB_END (b))
2814 && !tablejump_p (BB_END (b),
2815 NULL, NULL))))
2816 && (next = merge_blocks_move (s, b, c, mode)))
2818 b = next;
2819 changed_here = true;
2823 /* Simplify branch over branch. */
2824 if ((mode & CLEANUP_EXPENSIVE)
2825 && !(mode & CLEANUP_CFGLAYOUT)
2826 && try_simplify_condjump (b))
2827 changed_here = true;
2829 /* If B has a single outgoing edge, but uses a
2830 non-trivial jump instruction without side-effects, we
2831 can either delete the jump entirely, or replace it
2832 with a simple unconditional jump. */
2833 if (single_succ_p (b)
2834 && single_succ (b) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2835 && onlyjump_p (BB_END (b))
2836 && !CROSSING_JUMP_P (BB_END (b))
2837 && try_redirect_by_replacing_jump (single_succ_edge (b),
2838 single_succ (b),
2839 (mode & CLEANUP_CFGLAYOUT) != 0))
2841 update_forwarder_flag (b);
2842 changed_here = true;
2845 /* Simplify branch to branch. */
2846 if (try_forward_edges (mode, b))
2848 update_forwarder_flag (b);
2849 changed_here = true;
2852 /* Look for shared code between blocks. */
2853 if ((mode & CLEANUP_CROSSJUMP)
2854 && try_crossjump_bb (mode, b))
2855 changed_here = true;
2857 if ((mode & CLEANUP_CROSSJUMP)
2858 /* This can lengthen register lifetimes. Do it only after
2859 reload. */
2860 && reload_completed
2861 && try_head_merge_bb (b))
2862 changed_here = true;
2864 /* Don't get confused by the index shift caused by
2865 deleting blocks. */
2866 if (!changed_here)
2867 b = b->next_bb;
2868 else
2869 changed = true;
2872 if ((mode & CLEANUP_CROSSJUMP)
2873 && try_crossjump_bb (mode, EXIT_BLOCK_PTR_FOR_FN (cfun)))
2874 changed = true;
2876 if (block_was_dirty)
2878 /* This should only be set by head-merging. */
2879 gcc_assert (mode & CLEANUP_CROSSJUMP);
2880 df_analyze ();
2883 if (changed)
2885 /* Edge forwarding in particular can cause hot blocks previously
2886 reached by both hot and cold blocks to become dominated only
2887 by cold blocks. This will cause the verification below to fail,
2888 and lead to now cold code in the hot section. This is not easy
2889 to detect and fix during edge forwarding, and in some cases
2890 is only visible after newly unreachable blocks are deleted,
2891 which will be done in fixup_partitions. */
2892 fixup_partitions ();
2894 #ifdef ENABLE_CHECKING
2895 verify_flow_info ();
2896 #endif
2899 changed_overall |= changed;
2900 first_pass = false;
2902 while (changed);
2905 FOR_ALL_BB_FN (b, cfun)
2906 b->flags &= ~(BB_FORWARDER_BLOCK | BB_NONTHREADABLE_BLOCK);
2908 return changed_overall;
2911 /* Delete all unreachable basic blocks. */
2913 bool
2914 delete_unreachable_blocks (void)
2916 bool changed = false;
2917 basic_block b, prev_bb;
2919 find_unreachable_blocks ();
2921 /* When we're in GIMPLE mode and there may be debug insns, we should
2922 delete blocks in reverse dominator order, so as to get a chance
2923 to substitute all released DEFs into debug stmts. If we don't
2924 have dominators information, walking blocks backward gets us a
2925 better chance of retaining most debug information than
2926 otherwise. */
2927 if (MAY_HAVE_DEBUG_INSNS && current_ir_type () == IR_GIMPLE
2928 && dom_info_available_p (CDI_DOMINATORS))
2930 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2931 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2933 prev_bb = b->prev_bb;
2935 if (!(b->flags & BB_REACHABLE))
2937 /* Speed up the removal of blocks that don't dominate
2938 others. Walking backwards, this should be the common
2939 case. */
2940 if (!first_dom_son (CDI_DOMINATORS, b))
2941 delete_basic_block (b);
2942 else
2944 vec<basic_block> h
2945 = get_all_dominated_blocks (CDI_DOMINATORS, b);
2947 while (h.length ())
2949 b = h.pop ();
2951 prev_bb = b->prev_bb;
2953 gcc_assert (!(b->flags & BB_REACHABLE));
2955 delete_basic_block (b);
2958 h.release ();
2961 changed = true;
2965 else
2967 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2968 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2970 prev_bb = b->prev_bb;
2972 if (!(b->flags & BB_REACHABLE))
2974 delete_basic_block (b);
2975 changed = true;
2980 if (changed)
2981 tidy_fallthru_edges ();
2982 return changed;
2985 /* Delete any jump tables never referenced. We can't delete them at the
2986 time of removing tablejump insn as they are referenced by the preceding
2987 insns computing the destination, so we delay deleting and garbagecollect
2988 them once life information is computed. */
2989 void
2990 delete_dead_jumptables (void)
2992 basic_block bb;
2994 /* A dead jump table does not belong to any basic block. Scan insns
2995 between two adjacent basic blocks. */
2996 FOR_EACH_BB_FN (bb, cfun)
2998 rtx_insn *insn, *next;
3000 for (insn = NEXT_INSN (BB_END (bb));
3001 insn && !NOTE_INSN_BASIC_BLOCK_P (insn);
3002 insn = next)
3004 next = NEXT_INSN (insn);
3005 if (LABEL_P (insn)
3006 && LABEL_NUSES (insn) == LABEL_PRESERVE_P (insn)
3007 && JUMP_TABLE_DATA_P (next))
3009 rtx_insn *label = insn, *jump = next;
3011 if (dump_file)
3012 fprintf (dump_file, "Dead jumptable %i removed\n",
3013 INSN_UID (insn));
3015 next = NEXT_INSN (next);
3016 delete_insn (jump);
3017 delete_insn (label);
3024 /* Tidy the CFG by deleting unreachable code and whatnot. */
3026 bool
3027 cleanup_cfg (int mode)
3029 bool changed = false;
3031 /* Set the cfglayout mode flag here. We could update all the callers
3032 but that is just inconvenient, especially given that we eventually
3033 want to have cfglayout mode as the default. */
3034 if (current_ir_type () == IR_RTL_CFGLAYOUT)
3035 mode |= CLEANUP_CFGLAYOUT;
3037 timevar_push (TV_CLEANUP_CFG);
3038 if (delete_unreachable_blocks ())
3040 changed = true;
3041 /* We've possibly created trivially dead code. Cleanup it right
3042 now to introduce more opportunities for try_optimize_cfg. */
3043 if (!(mode & (CLEANUP_NO_INSN_DEL))
3044 && !reload_completed)
3045 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3048 compact_blocks ();
3050 /* To tail-merge blocks ending in the same noreturn function (e.g.
3051 a call to abort) we have to insert fake edges to exit. Do this
3052 here once. The fake edges do not interfere with any other CFG
3053 cleanups. */
3054 if (mode & CLEANUP_CROSSJUMP)
3055 add_noreturn_fake_exit_edges ();
3057 if (!dbg_cnt (cfg_cleanup))
3058 return changed;
3060 while (try_optimize_cfg (mode))
3062 delete_unreachable_blocks (), changed = true;
3063 if (!(mode & CLEANUP_NO_INSN_DEL))
3065 /* Try to remove some trivially dead insns when doing an expensive
3066 cleanup. But delete_trivially_dead_insns doesn't work after
3067 reload (it only handles pseudos) and run_fast_dce is too costly
3068 to run in every iteration.
3070 For effective cross jumping, we really want to run a fast DCE to
3071 clean up any dead conditions, or they get in the way of performing
3072 useful tail merges.
3074 Other transformations in cleanup_cfg are not so sensitive to dead
3075 code, so delete_trivially_dead_insns or even doing nothing at all
3076 is good enough. */
3077 if ((mode & CLEANUP_EXPENSIVE) && !reload_completed
3078 && !delete_trivially_dead_insns (get_insns (), max_reg_num ()))
3079 break;
3080 if ((mode & CLEANUP_CROSSJUMP) && crossjumps_occured)
3081 run_fast_dce ();
3083 else
3084 break;
3087 if (mode & CLEANUP_CROSSJUMP)
3088 remove_fake_exit_edges ();
3090 /* Don't call delete_dead_jumptables in cfglayout mode, because
3091 that function assumes that jump tables are in the insns stream.
3092 But we also don't _have_ to delete dead jumptables in cfglayout
3093 mode because we shouldn't even be looking at things that are
3094 not in a basic block. Dead jumptables are cleaned up when
3095 going out of cfglayout mode. */
3096 if (!(mode & CLEANUP_CFGLAYOUT))
3097 delete_dead_jumptables ();
3099 /* ??? We probably do this way too often. */
3100 if (current_loops
3101 && (changed
3102 || (mode & CLEANUP_CFG_CHANGED)))
3104 timevar_push (TV_REPAIR_LOOPS);
3105 /* The above doesn't preserve dominance info if available. */
3106 gcc_assert (!dom_info_available_p (CDI_DOMINATORS));
3107 calculate_dominance_info (CDI_DOMINATORS);
3108 fix_loop_structure (NULL);
3109 free_dominance_info (CDI_DOMINATORS);
3110 timevar_pop (TV_REPAIR_LOOPS);
3113 timevar_pop (TV_CLEANUP_CFG);
3115 return changed;
3118 namespace {
3120 const pass_data pass_data_jump =
3122 RTL_PASS, /* type */
3123 "jump", /* name */
3124 OPTGROUP_NONE, /* optinfo_flags */
3125 TV_JUMP, /* tv_id */
3126 0, /* properties_required */
3127 0, /* properties_provided */
3128 0, /* properties_destroyed */
3129 0, /* todo_flags_start */
3130 0, /* todo_flags_finish */
3133 class pass_jump : public rtl_opt_pass
3135 public:
3136 pass_jump (gcc::context *ctxt)
3137 : rtl_opt_pass (pass_data_jump, ctxt)
3140 /* opt_pass methods: */
3141 virtual unsigned int execute (function *);
3143 }; // class pass_jump
3145 unsigned int
3146 pass_jump::execute (function *)
3148 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3149 if (dump_file)
3150 dump_flow_info (dump_file, dump_flags);
3151 cleanup_cfg ((optimize ? CLEANUP_EXPENSIVE : 0)
3152 | (flag_thread_jumps ? CLEANUP_THREADING : 0));
3153 return 0;
3156 } // anon namespace
3158 rtl_opt_pass *
3159 make_pass_jump (gcc::context *ctxt)
3161 return new pass_jump (ctxt);
3164 namespace {
3166 const pass_data pass_data_jump2 =
3168 RTL_PASS, /* type */
3169 "jump2", /* name */
3170 OPTGROUP_NONE, /* optinfo_flags */
3171 TV_JUMP, /* tv_id */
3172 0, /* properties_required */
3173 0, /* properties_provided */
3174 0, /* properties_destroyed */
3175 0, /* todo_flags_start */
3176 0, /* todo_flags_finish */
3179 class pass_jump2 : public rtl_opt_pass
3181 public:
3182 pass_jump2 (gcc::context *ctxt)
3183 : rtl_opt_pass (pass_data_jump2, ctxt)
3186 /* opt_pass methods: */
3187 virtual unsigned int execute (function *)
3189 cleanup_cfg (flag_crossjumping ? CLEANUP_CROSSJUMP : 0);
3190 return 0;
3193 }; // class pass_jump2
3195 } // anon namespace
3197 rtl_opt_pass *
3198 make_pass_jump2 (gcc::context *ctxt)
3200 return new pass_jump2 (ctxt);