c9b132d8ec25535b431980f9e2587308166754e5
[platform/upstream/gcc.git] / gcc / cfgcleanup.c
1 /* Control flow optimization code for GNU compiler.
2    Copyright (C) 1987-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>.  */
19
20 /* This file contains optimizer of the control flow.  The main entry point is
21    cleanup_cfg.  Following optimizations are performed:
22
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.  */
31
32 #include "config.h"
33 #include "system.h"
34 #include "coretypes.h"
35 #include "backend.h"
36 #include "cfghooks.h"
37 #include "tree.h"
38 #include "rtl.h"
39 #include "df.h"
40 #include "alias.h"
41 #include "regs.h"
42 #include "insn-config.h"
43 #include "flags.h"
44 #include "recog.h"
45 #include "diagnostic-core.h"
46 #include "alloc-pool.h"
47 #include "cselib.h"
48 #include "params.h"
49 #include "tm_p.h"
50 #include "target.h"
51 #include "emit-rtl.h"
52 #include "tree-pass.h"
53 #include "cfgloop.h"
54 #include "expmed.h"
55 #include "dojump.h"
56 #include "explow.h"
57 #include "calls.h"
58 #include "varasm.h"
59 #include "stmt.h"
60 #include "expr.h"
61 #include "cfgrtl.h"
62 #include "cfganal.h"
63 #include "cfgbuild.h"
64 #include "cfgcleanup.h"
65 #include "dce.h"
66 #include "dbgcnt.h"
67 #include "rtl-iter.h"
68
69 #define FORWARDER_BLOCK_P(BB) ((BB)->flags & BB_FORWARDER_BLOCK)
70
71 /* Set to true when we are running first pass of try_optimize_cfg loop.  */
72 static bool first_pass;
73
74 /* Set to true if crossjumps occurred in the latest run of try_optimize_cfg.  */
75 static bool crossjumps_occured;
76
77 /* Set to true if we couldn't run an optimization due to stale liveness
78    information; we should run df_analyze to enable more opportunities.  */
79 static bool block_was_dirty;
80
81 static bool try_crossjump_to_edge (int, edge, edge, enum replace_direction);
82 static bool try_crossjump_bb (int, basic_block);
83 static bool outgoing_edges_match (int, basic_block, basic_block);
84 static enum replace_direction old_insns_match_p (int, rtx_insn *, rtx_insn *);
85
86 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
87 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
88 static bool try_optimize_cfg (int);
89 static bool try_simplify_condjump (basic_block);
90 static bool try_forward_edges (int, basic_block);
91 static edge thread_jump (edge, basic_block);
92 static bool mark_effect (rtx, bitmap);
93 static void notice_new_block (basic_block);
94 static void update_forwarder_flag (basic_block);
95 static void merge_memattrs (rtx, rtx);
96 \f
97 /* Set flags for newly created block.  */
98
99 static void
100 notice_new_block (basic_block bb)
101 {
102   if (!bb)
103     return;
104
105   if (forwarder_block_p (bb))
106     bb->flags |= BB_FORWARDER_BLOCK;
107 }
108
109 /* Recompute forwarder flag after block has been modified.  */
110
111 static void
112 update_forwarder_flag (basic_block bb)
113 {
114   if (forwarder_block_p (bb))
115     bb->flags |= BB_FORWARDER_BLOCK;
116   else
117     bb->flags &= ~BB_FORWARDER_BLOCK;
118 }
119 \f
120 /* Simplify a conditional jump around an unconditional jump.
121    Return true if something changed.  */
122
123 static bool
124 try_simplify_condjump (basic_block cbranch_block)
125 {
126   basic_block jump_block, jump_dest_block, cbranch_dest_block;
127   edge cbranch_jump_edge, cbranch_fallthru_edge;
128   rtx_insn *cbranch_insn;
129
130   /* Verify that there are exactly two successors.  */
131   if (EDGE_COUNT (cbranch_block->succs) != 2)
132     return false;
133
134   /* Verify that we've got a normal conditional branch at the end
135      of the block.  */
136   cbranch_insn = BB_END (cbranch_block);
137   if (!any_condjump_p (cbranch_insn))
138     return false;
139
140   cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
141   cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
142
143   /* The next block must not have multiple predecessors, must not
144      be the last block in the function, and must contain just the
145      unconditional jump.  */
146   jump_block = cbranch_fallthru_edge->dest;
147   if (!single_pred_p (jump_block)
148       || jump_block->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
149       || !FORWARDER_BLOCK_P (jump_block))
150     return false;
151   jump_dest_block = single_succ (jump_block);
152
153   /* If we are partitioning hot/cold basic blocks, we don't want to
154      mess up unconditional or indirect jumps that cross between hot
155      and cold sections.
156
157      Basic block partitioning may result in some jumps that appear to
158      be optimizable (or blocks that appear to be mergeable), but which really
159      must be left untouched (they are required to make it safely across
160      partition boundaries).  See the comments at the top of
161      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
162
163   if (BB_PARTITION (jump_block) != BB_PARTITION (jump_dest_block)
164       || (cbranch_jump_edge->flags & EDGE_CROSSING))
165     return false;
166
167   /* The conditional branch must target the block after the
168      unconditional branch.  */
169   cbranch_dest_block = cbranch_jump_edge->dest;
170
171   if (cbranch_dest_block == EXIT_BLOCK_PTR_FOR_FN (cfun)
172       || !can_fallthru (jump_block, cbranch_dest_block))
173     return false;
174
175   /* Invert the conditional branch.  */
176   if (!invert_jump (as_a <rtx_jump_insn *> (cbranch_insn),
177                     block_label (jump_dest_block), 0))
178     return false;
179
180   if (dump_file)
181     fprintf (dump_file, "Simplifying condjump %i around jump %i\n",
182              INSN_UID (cbranch_insn), INSN_UID (BB_END (jump_block)));
183
184   /* Success.  Update the CFG to match.  Note that after this point
185      the edge variable names appear backwards; the redirection is done
186      this way to preserve edge profile data.  */
187   cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
188                                                 cbranch_dest_block);
189   cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
190                                                     jump_dest_block);
191   cbranch_jump_edge->flags |= EDGE_FALLTHRU;
192   cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
193   update_br_prob_note (cbranch_block);
194
195   /* Delete the block with the unconditional jump, and clean up the mess.  */
196   delete_basic_block (jump_block);
197   tidy_fallthru_edge (cbranch_jump_edge);
198   update_forwarder_flag (cbranch_block);
199
200   return true;
201 }
202 \f
203 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
204    on register.  Used by jump threading.  */
205
206 static bool
207 mark_effect (rtx exp, regset nonequal)
208 {
209   rtx dest;
210   switch (GET_CODE (exp))
211     {
212       /* In case we do clobber the register, mark it as equal, as we know the
213          value is dead so it don't have to match.  */
214     case CLOBBER:
215       dest = XEXP (exp, 0);
216       if (REG_P (dest))
217         bitmap_clear_range (nonequal, REGNO (dest), REG_NREGS (dest));
218       return false;
219
220     case SET:
221       if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
222         return false;
223       dest = SET_DEST (exp);
224       if (dest == pc_rtx)
225         return false;
226       if (!REG_P (dest))
227         return true;
228       bitmap_set_range (nonequal, REGNO (dest), REG_NREGS (dest));
229       return false;
230
231     default:
232       return false;
233     }
234 }
235
236 /* Return true if X contains a register in NONEQUAL.  */
237 static bool
238 mentions_nonequal_regs (const_rtx x, regset nonequal)
239 {
240   subrtx_iterator::array_type array;
241   FOR_EACH_SUBRTX (iter, array, x, NONCONST)
242     {
243       const_rtx x = *iter;
244       if (REG_P (x))
245         {
246           unsigned int end_regno = END_REGNO (x);
247           for (unsigned int regno = REGNO (x); regno < end_regno; ++regno)
248             if (REGNO_REG_SET_P (nonequal, regno))
249               return true;
250         }
251     }
252   return false;
253 }
254
255 /* Attempt to prove that the basic block B will have no side effects and
256    always continues in the same edge if reached via E.  Return the edge
257    if exist, NULL otherwise.  */
258
259 static edge
260 thread_jump (edge e, basic_block b)
261 {
262   rtx set1, set2, cond1, cond2;
263   rtx_insn *insn;
264   enum rtx_code code1, code2, reversed_code2;
265   bool reverse1 = false;
266   unsigned i;
267   regset nonequal;
268   bool failed = false;
269   reg_set_iterator rsi;
270
271   if (b->flags & BB_NONTHREADABLE_BLOCK)
272     return NULL;
273
274   /* At the moment, we do handle only conditional jumps, but later we may
275      want to extend this code to tablejumps and others.  */
276   if (EDGE_COUNT (e->src->succs) != 2)
277     return NULL;
278   if (EDGE_COUNT (b->succs) != 2)
279     {
280       b->flags |= BB_NONTHREADABLE_BLOCK;
281       return NULL;
282     }
283
284   /* Second branch must end with onlyjump, as we will eliminate the jump.  */
285   if (!any_condjump_p (BB_END (e->src)))
286     return NULL;
287
288   if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
289     {
290       b->flags |= BB_NONTHREADABLE_BLOCK;
291       return NULL;
292     }
293
294   set1 = pc_set (BB_END (e->src));
295   set2 = pc_set (BB_END (b));
296   if (((e->flags & EDGE_FALLTHRU) != 0)
297       != (XEXP (SET_SRC (set1), 1) == pc_rtx))
298     reverse1 = true;
299
300   cond1 = XEXP (SET_SRC (set1), 0);
301   cond2 = XEXP (SET_SRC (set2), 0);
302   if (reverse1)
303     code1 = reversed_comparison_code (cond1, BB_END (e->src));
304   else
305     code1 = GET_CODE (cond1);
306
307   code2 = GET_CODE (cond2);
308   reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
309
310   if (!comparison_dominates_p (code1, code2)
311       && !comparison_dominates_p (code1, reversed_code2))
312     return NULL;
313
314   /* Ensure that the comparison operators are equivalent.
315      ??? This is far too pessimistic.  We should allow swapped operands,
316      different CCmodes, or for example comparisons for interval, that
317      dominate even when operands are not equivalent.  */
318   if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
319       || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
320     return NULL;
321
322   /* Short circuit cases where block B contains some side effects, as we can't
323      safely bypass it.  */
324   for (insn = NEXT_INSN (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
325        insn = NEXT_INSN (insn))
326     if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
327       {
328         b->flags |= BB_NONTHREADABLE_BLOCK;
329         return NULL;
330       }
331
332   cselib_init (0);
333
334   /* First process all values computed in the source basic block.  */
335   for (insn = NEXT_INSN (BB_HEAD (e->src));
336        insn != NEXT_INSN (BB_END (e->src));
337        insn = NEXT_INSN (insn))
338     if (INSN_P (insn))
339       cselib_process_insn (insn);
340
341   nonequal = BITMAP_ALLOC (NULL);
342   CLEAR_REG_SET (nonequal);
343
344   /* Now assume that we've continued by the edge E to B and continue
345      processing as if it were same basic block.
346      Our goal is to prove that whole block is an NOOP.  */
347
348   for (insn = NEXT_INSN (BB_HEAD (b));
349        insn != NEXT_INSN (BB_END (b)) && !failed;
350        insn = NEXT_INSN (insn))
351     {
352       if (INSN_P (insn))
353         {
354           rtx pat = PATTERN (insn);
355
356           if (GET_CODE (pat) == PARALLEL)
357             {
358               for (i = 0; i < (unsigned)XVECLEN (pat, 0); i++)
359                 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
360             }
361           else
362             failed |= mark_effect (pat, nonequal);
363         }
364
365       cselib_process_insn (insn);
366     }
367
368   /* Later we should clear nonequal of dead registers.  So far we don't
369      have life information in cfg_cleanup.  */
370   if (failed)
371     {
372       b->flags |= BB_NONTHREADABLE_BLOCK;
373       goto failed_exit;
374     }
375
376   /* cond2 must not mention any register that is not equal to the
377      former block.  */
378   if (mentions_nonequal_regs (cond2, nonequal))
379     goto failed_exit;
380
381   EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, rsi)
382     goto failed_exit;
383
384   BITMAP_FREE (nonequal);
385   cselib_finish ();
386   if ((comparison_dominates_p (code1, code2) != 0)
387       != (XEXP (SET_SRC (set2), 1) == pc_rtx))
388     return BRANCH_EDGE (b);
389   else
390     return FALLTHRU_EDGE (b);
391
392 failed_exit:
393   BITMAP_FREE (nonequal);
394   cselib_finish ();
395   return NULL;
396 }
397 \f
398 /* Attempt to forward edges leaving basic block B.
399    Return true if successful.  */
400
401 static bool
402 try_forward_edges (int mode, basic_block b)
403 {
404   bool changed = false;
405   edge_iterator ei;
406   edge e, *threaded_edges = NULL;
407
408   /* If we are partitioning hot/cold basic blocks, we don't want to
409      mess up unconditional or indirect jumps that cross between hot
410      and cold sections.
411
412      Basic block partitioning may result in some jumps that appear to
413      be optimizable (or blocks that appear to be mergeable), but which really
414      must be left untouched (they are required to make it safely across
415      partition boundaries).  See the comments at the top of
416      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
417
418   if (JUMP_P (BB_END (b)) && CROSSING_JUMP_P (BB_END (b)))
419     return false;
420
421   for (ei = ei_start (b->succs); (e = ei_safe_edge (ei)); )
422     {
423       basic_block target, first;
424       location_t goto_locus;
425       int counter;
426       bool threaded = false;
427       int nthreaded_edges = 0;
428       bool may_thread = first_pass || (b->flags & BB_MODIFIED) != 0;
429
430       /* Skip complex edges because we don't know how to update them.
431
432          Still handle fallthru edges, as we can succeed to forward fallthru
433          edge to the same place as the branch edge of conditional branch
434          and turn conditional branch to an unconditional branch.  */
435       if (e->flags & EDGE_COMPLEX)
436         {
437           ei_next (&ei);
438           continue;
439         }
440
441       target = first = e->dest;
442       counter = NUM_FIXED_BLOCKS;
443       goto_locus = e->goto_locus;
444
445       /* If we are partitioning hot/cold basic_blocks, we don't want to mess
446          up jumps that cross between hot/cold sections.
447
448          Basic block partitioning may result in some jumps that appear
449          to be optimizable (or blocks that appear to be mergeable), but which
450          really must be left untouched (they are required to make it safely
451          across partition boundaries).  See the comments at the top of
452          bb-reorder.c:partition_hot_cold_basic_blocks for complete
453          details.  */
454
455       if (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
456           && JUMP_P (BB_END (first))
457           && CROSSING_JUMP_P (BB_END (first)))
458         return changed;
459
460       while (counter < n_basic_blocks_for_fn (cfun))
461         {
462           basic_block new_target = NULL;
463           bool new_target_threaded = false;
464           may_thread |= (target->flags & BB_MODIFIED) != 0;
465
466           if (FORWARDER_BLOCK_P (target)
467               && !(single_succ_edge (target)->flags & EDGE_CROSSING)
468               && single_succ (target) != EXIT_BLOCK_PTR_FOR_FN (cfun))
469             {
470               /* Bypass trivial infinite loops.  */
471               new_target = single_succ (target);
472               if (target == new_target)
473                 counter = n_basic_blocks_for_fn (cfun);
474               else if (!optimize)
475                 {
476                   /* When not optimizing, ensure that edges or forwarder
477                      blocks with different locus are not optimized out.  */
478                   location_t new_locus = single_succ_edge (target)->goto_locus;
479                   location_t locus = goto_locus;
480
481                   if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
482                       && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
483                       && new_locus != locus)
484                     new_target = NULL;
485                   else
486                     {
487                       if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
488                         locus = new_locus;
489
490                       rtx_insn *last = BB_END (target);
491                       if (DEBUG_INSN_P (last))
492                         last = prev_nondebug_insn (last);
493                       if (last && INSN_P (last))
494                         new_locus = INSN_LOCATION (last);
495                       else
496                         new_locus = UNKNOWN_LOCATION;
497
498                       if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
499                           && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
500                           && new_locus != locus)
501                         new_target = NULL;
502                       else
503                         {
504                           if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
505                             locus = new_locus;
506
507                           goto_locus = locus;
508                         }
509                     }
510                 }
511             }
512
513           /* Allow to thread only over one edge at time to simplify updating
514              of probabilities.  */
515           else if ((mode & CLEANUP_THREADING) && may_thread)
516             {
517               edge t = thread_jump (e, target);
518               if (t)
519                 {
520                   if (!threaded_edges)
521                     threaded_edges = XNEWVEC (edge,
522                                               n_basic_blocks_for_fn (cfun));
523                   else
524                     {
525                       int i;
526
527                       /* Detect an infinite loop across blocks not
528                          including the start block.  */
529                       for (i = 0; i < nthreaded_edges; ++i)
530                         if (threaded_edges[i] == t)
531                           break;
532                       if (i < nthreaded_edges)
533                         {
534                           counter = n_basic_blocks_for_fn (cfun);
535                           break;
536                         }
537                     }
538
539                   /* Detect an infinite loop across the start block.  */
540                   if (t->dest == b)
541                     break;
542
543                   gcc_assert (nthreaded_edges
544                               < (n_basic_blocks_for_fn (cfun)
545                                  - NUM_FIXED_BLOCKS));
546                   threaded_edges[nthreaded_edges++] = t;
547
548                   new_target = t->dest;
549                   new_target_threaded = true;
550                 }
551             }
552
553           if (!new_target)
554             break;
555
556           counter++;
557           target = new_target;
558           threaded |= new_target_threaded;
559         }
560
561       if (counter >= n_basic_blocks_for_fn (cfun))
562         {
563           if (dump_file)
564             fprintf (dump_file, "Infinite loop in BB %i.\n",
565                      target->index);
566         }
567       else if (target == first)
568         ; /* We didn't do anything.  */
569       else
570         {
571           /* Save the values now, as the edge may get removed.  */
572           gcov_type edge_count = e->count;
573           int edge_probability = e->probability;
574           int edge_frequency;
575           int n = 0;
576
577           e->goto_locus = goto_locus;
578
579           /* Don't force if target is exit block.  */
580           if (threaded && target != EXIT_BLOCK_PTR_FOR_FN (cfun))
581             {
582               notice_new_block (redirect_edge_and_branch_force (e, target));
583               if (dump_file)
584                 fprintf (dump_file, "Conditionals threaded.\n");
585             }
586           else if (!redirect_edge_and_branch (e, target))
587             {
588               if (dump_file)
589                 fprintf (dump_file,
590                          "Forwarding edge %i->%i to %i failed.\n",
591                          b->index, e->dest->index, target->index);
592               ei_next (&ei);
593               continue;
594             }
595
596           /* We successfully forwarded the edge.  Now update profile
597              data: for each edge we traversed in the chain, remove
598              the original edge's execution count.  */
599           edge_frequency = apply_probability (b->frequency, edge_probability);
600
601           do
602             {
603               edge t;
604
605               if (!single_succ_p (first))
606                 {
607                   gcc_assert (n < nthreaded_edges);
608                   t = threaded_edges [n++];
609                   gcc_assert (t->src == first);
610                   update_bb_profile_for_threading (first, edge_frequency,
611                                                    edge_count, t);
612                   update_br_prob_note (first);
613                 }
614               else
615                 {
616                   first->count -= edge_count;
617                   if (first->count < 0)
618                     first->count = 0;
619                   first->frequency -= edge_frequency;
620                   if (first->frequency < 0)
621                     first->frequency = 0;
622                   /* It is possible that as the result of
623                      threading we've removed edge as it is
624                      threaded to the fallthru edge.  Avoid
625                      getting out of sync.  */
626                   if (n < nthreaded_edges
627                       && first == threaded_edges [n]->src)
628                     n++;
629                   t = single_succ_edge (first);
630                 }
631
632               t->count -= edge_count;
633               if (t->count < 0)
634                 t->count = 0;
635               first = t->dest;
636             }
637           while (first != target);
638
639           changed = true;
640           continue;
641         }
642       ei_next (&ei);
643     }
644
645   free (threaded_edges);
646   return changed;
647 }
648 \f
649
650 /* Blocks A and B are to be merged into a single block.  A has no incoming
651    fallthru edge, so it can be moved before B without adding or modifying
652    any jumps (aside from the jump from A to B).  */
653
654 static void
655 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
656 {
657   rtx_insn *barrier;
658
659   /* If we are partitioning hot/cold basic blocks, we don't want to
660      mess up unconditional or indirect jumps that cross between hot
661      and cold sections.
662
663      Basic block partitioning may result in some jumps that appear to
664      be optimizable (or blocks that appear to be mergeable), but which really
665      must be left untouched (they are required to make it safely across
666      partition boundaries).  See the comments at the top of
667      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
668
669   if (BB_PARTITION (a) != BB_PARTITION (b))
670     return;
671
672   barrier = next_nonnote_insn (BB_END (a));
673   gcc_assert (BARRIER_P (barrier));
674   delete_insn (barrier);
675
676   /* Scramble the insn chain.  */
677   if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
678     reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
679   df_set_bb_dirty (a);
680
681   if (dump_file)
682     fprintf (dump_file, "Moved block %d before %d and merged.\n",
683              a->index, b->index);
684
685   /* Swap the records for the two blocks around.  */
686
687   unlink_block (a);
688   link_block (a, b->prev_bb);
689
690   /* Now blocks A and B are contiguous.  Merge them.  */
691   merge_blocks (a, b);
692 }
693
694 /* Blocks A and B are to be merged into a single block.  B has no outgoing
695    fallthru edge, so it can be moved after A without adding or modifying
696    any jumps (aside from the jump from A to B).  */
697
698 static void
699 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
700 {
701   rtx_insn *barrier, *real_b_end;
702   rtx label;
703   rtx_jump_table_data *table;
704
705   /* If we are partitioning hot/cold basic blocks, we don't want to
706      mess up unconditional or indirect jumps that cross between hot
707      and cold sections.
708
709      Basic block partitioning may result in some jumps that appear to
710      be optimizable (or blocks that appear to be mergeable), but which really
711      must be left untouched (they are required to make it safely across
712      partition boundaries).  See the comments at the top of
713      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
714
715   if (BB_PARTITION (a) != BB_PARTITION (b))
716     return;
717
718   real_b_end = BB_END (b);
719
720   /* If there is a jump table following block B temporarily add the jump table
721      to block B so that it will also be moved to the correct location.  */
722   if (tablejump_p (BB_END (b), &label, &table)
723       && prev_active_insn (label) == BB_END (b))
724     {
725       BB_END (b) = table;
726     }
727
728   /* There had better have been a barrier there.  Delete it.  */
729   barrier = NEXT_INSN (BB_END (b));
730   if (barrier && BARRIER_P (barrier))
731     delete_insn (barrier);
732
733
734   /* Scramble the insn chain.  */
735   reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
736
737   /* Restore the real end of b.  */
738   BB_END (b) = real_b_end;
739
740   if (dump_file)
741     fprintf (dump_file, "Moved block %d after %d and merged.\n",
742              b->index, a->index);
743
744   /* Now blocks A and B are contiguous.  Merge them.  */
745   merge_blocks (a, b);
746 }
747
748 /* Attempt to merge basic blocks that are potentially non-adjacent.
749    Return NULL iff the attempt failed, otherwise return basic block
750    where cleanup_cfg should continue.  Because the merging commonly
751    moves basic block away or introduces another optimization
752    possibility, return basic block just before B so cleanup_cfg don't
753    need to iterate.
754
755    It may be good idea to return basic block before C in the case
756    C has been moved after B and originally appeared earlier in the
757    insn sequence, but we have no information available about the
758    relative ordering of these two.  Hopefully it is not too common.  */
759
760 static basic_block
761 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
762 {
763   basic_block next;
764
765   /* If we are partitioning hot/cold basic blocks, we don't want to
766      mess up unconditional or indirect jumps that cross between hot
767      and cold sections.
768
769      Basic block partitioning may result in some jumps that appear to
770      be optimizable (or blocks that appear to be mergeable), but which really
771      must be left untouched (they are required to make it safely across
772      partition boundaries).  See the comments at the top of
773      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
774
775   if (BB_PARTITION (b) != BB_PARTITION (c))
776     return NULL;
777
778   /* If B has a fallthru edge to C, no need to move anything.  */
779   if (e->flags & EDGE_FALLTHRU)
780     {
781       int b_index = b->index, c_index = c->index;
782
783       /* Protect the loop latches.  */
784       if (current_loops && c->loop_father->latch == c)
785         return NULL;
786
787       merge_blocks (b, c);
788       update_forwarder_flag (b);
789
790       if (dump_file)
791         fprintf (dump_file, "Merged %d and %d without moving.\n",
792                  b_index, c_index);
793
794       return b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? b : b->prev_bb;
795     }
796
797   /* Otherwise we will need to move code around.  Do that only if expensive
798      transformations are allowed.  */
799   else if (mode & CLEANUP_EXPENSIVE)
800     {
801       edge tmp_edge, b_fallthru_edge;
802       bool c_has_outgoing_fallthru;
803       bool b_has_incoming_fallthru;
804
805       /* Avoid overactive code motion, as the forwarder blocks should be
806          eliminated by edge redirection instead.  One exception might have
807          been if B is a forwarder block and C has no fallthru edge, but
808          that should be cleaned up by bb-reorder instead.  */
809       if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
810         return NULL;
811
812       /* We must make sure to not munge nesting of lexical blocks,
813          and loop notes.  This is done by squeezing out all the notes
814          and leaving them there to lie.  Not ideal, but functional.  */
815
816       tmp_edge = find_fallthru_edge (c->succs);
817       c_has_outgoing_fallthru = (tmp_edge != NULL);
818
819       tmp_edge = find_fallthru_edge (b->preds);
820       b_has_incoming_fallthru = (tmp_edge != NULL);
821       b_fallthru_edge = tmp_edge;
822       next = b->prev_bb;
823       if (next == c)
824         next = next->prev_bb;
825
826       /* Otherwise, we're going to try to move C after B.  If C does
827          not have an outgoing fallthru, then it can be moved
828          immediately after B without introducing or modifying jumps.  */
829       if (! c_has_outgoing_fallthru)
830         {
831           merge_blocks_move_successor_nojumps (b, c);
832           return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
833         }
834
835       /* If B does not have an incoming fallthru, then it can be moved
836          immediately before C without introducing or modifying jumps.
837          C cannot be the first block, so we do not have to worry about
838          accessing a non-existent block.  */
839
840       if (b_has_incoming_fallthru)
841         {
842           basic_block bb;
843
844           if (b_fallthru_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
845             return NULL;
846           bb = force_nonfallthru (b_fallthru_edge);
847           if (bb)
848             notice_new_block (bb);
849         }
850
851       merge_blocks_move_predecessor_nojumps (b, c);
852       return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
853     }
854
855   return NULL;
856 }
857 \f
858
859 /* Removes the memory attributes of MEM expression
860    if they are not equal.  */
861
862 static void
863 merge_memattrs (rtx x, rtx y)
864 {
865   int i;
866   int j;
867   enum rtx_code code;
868   const char *fmt;
869
870   if (x == y)
871     return;
872   if (x == 0 || y == 0)
873     return;
874
875   code = GET_CODE (x);
876
877   if (code != GET_CODE (y))
878     return;
879
880   if (GET_MODE (x) != GET_MODE (y))
881     return;
882
883   if (code == MEM && !mem_attrs_eq_p (MEM_ATTRS (x), MEM_ATTRS (y)))
884     {
885       if (! MEM_ATTRS (x))
886         MEM_ATTRS (y) = 0;
887       else if (! MEM_ATTRS (y))
888         MEM_ATTRS (x) = 0;
889       else
890         {
891           HOST_WIDE_INT mem_size;
892
893           if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
894             {
895               set_mem_alias_set (x, 0);
896               set_mem_alias_set (y, 0);
897             }
898
899           if (! mem_expr_equal_p (MEM_EXPR (x), MEM_EXPR (y)))
900             {
901               set_mem_expr (x, 0);
902               set_mem_expr (y, 0);
903               clear_mem_offset (x);
904               clear_mem_offset (y);
905             }
906           else if (MEM_OFFSET_KNOWN_P (x) != MEM_OFFSET_KNOWN_P (y)
907                    || (MEM_OFFSET_KNOWN_P (x)
908                        && MEM_OFFSET (x) != MEM_OFFSET (y)))
909             {
910               clear_mem_offset (x);
911               clear_mem_offset (y);
912             }
913
914           if (MEM_SIZE_KNOWN_P (x) && MEM_SIZE_KNOWN_P (y))
915             {
916               mem_size = MAX (MEM_SIZE (x), MEM_SIZE (y));
917               set_mem_size (x, mem_size);
918               set_mem_size (y, mem_size);
919             }
920           else
921             {
922               clear_mem_size (x);
923               clear_mem_size (y);
924             }
925
926           set_mem_align (x, MIN (MEM_ALIGN (x), MEM_ALIGN (y)));
927           set_mem_align (y, MEM_ALIGN (x));
928         }
929     }
930   if (code == MEM)
931     {
932       if (MEM_READONLY_P (x) != MEM_READONLY_P (y))
933         {
934           MEM_READONLY_P (x) = 0;
935           MEM_READONLY_P (y) = 0;
936         }
937       if (MEM_NOTRAP_P (x) != MEM_NOTRAP_P (y))
938         {
939           MEM_NOTRAP_P (x) = 0;
940           MEM_NOTRAP_P (y) = 0;
941         }
942       if (MEM_VOLATILE_P (x) != MEM_VOLATILE_P (y))
943         {
944           MEM_VOLATILE_P (x) = 1;
945           MEM_VOLATILE_P (y) = 1;
946         }
947     }
948
949   fmt = GET_RTX_FORMAT (code);
950   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
951     {
952       switch (fmt[i])
953         {
954         case 'E':
955           /* Two vectors must have the same length.  */
956           if (XVECLEN (x, i) != XVECLEN (y, i))
957             return;
958
959           for (j = 0; j < XVECLEN (x, i); j++)
960             merge_memattrs (XVECEXP (x, i, j), XVECEXP (y, i, j));
961
962           break;
963
964         case 'e':
965           merge_memattrs (XEXP (x, i), XEXP (y, i));
966         }
967     }
968   return;
969 }
970
971
972  /* Checks if patterns P1 and P2 are equivalent, apart from the possibly
973     different single sets S1 and S2.  */
974
975 static bool
976 equal_different_set_p (rtx p1, rtx s1, rtx p2, rtx s2)
977 {
978   int i;
979   rtx e1, e2;
980
981   if (p1 == s1 && p2 == s2)
982     return true;
983
984   if (GET_CODE (p1) != PARALLEL || GET_CODE (p2) != PARALLEL)
985     return false;
986
987   if (XVECLEN (p1, 0) != XVECLEN (p2, 0))
988     return false;
989
990   for (i = 0; i < XVECLEN (p1, 0); i++)
991     {
992       e1 = XVECEXP (p1, 0, i);
993       e2 = XVECEXP (p2, 0, i);
994       if (e1 == s1 && e2 == s2)
995         continue;
996       if (reload_completed
997           ? rtx_renumbered_equal_p (e1, e2) : rtx_equal_p (e1, e2))
998         continue;
999
1000       return false;
1001     }
1002
1003   return true;
1004 }
1005
1006
1007 /* NOTE1 is the REG_EQUAL note, if any, attached to an insn
1008    that is a single_set with a SET_SRC of SRC1.  Similarly
1009    for NOTE2/SRC2.
1010
1011    So effectively NOTE1/NOTE2 are an alternate form of 
1012    SRC1/SRC2 respectively.
1013
1014    Return nonzero if SRC1 or NOTE1 has the same constant
1015    integer value as SRC2 or NOTE2.   Else return zero.  */
1016 static int
1017 values_equal_p (rtx note1, rtx note2, rtx src1, rtx src2)
1018 {
1019   if (note1
1020       && note2
1021       && CONST_INT_P (XEXP (note1, 0))
1022       && rtx_equal_p (XEXP (note1, 0), XEXP (note2, 0)))
1023     return 1;
1024
1025   if (!note1
1026       && !note2
1027       && CONST_INT_P (src1)
1028       && CONST_INT_P (src2)
1029       && rtx_equal_p (src1, src2))
1030     return 1;
1031
1032   if (note1
1033       && CONST_INT_P (src2)
1034       && rtx_equal_p (XEXP (note1, 0), src2))
1035     return 1;
1036
1037   if (note2
1038       && CONST_INT_P (src1)
1039       && rtx_equal_p (XEXP (note2, 0), src1))
1040     return 1;
1041
1042   return 0;
1043 }
1044
1045 /* Examine register notes on I1 and I2 and return:
1046    - dir_forward if I1 can be replaced by I2, or
1047    - dir_backward if I2 can be replaced by I1, or
1048    - dir_both if both are the case.  */
1049
1050 static enum replace_direction
1051 can_replace_by (rtx_insn *i1, rtx_insn *i2)
1052 {
1053   rtx s1, s2, d1, d2, src1, src2, note1, note2;
1054   bool c1, c2;
1055
1056   /* Check for 2 sets.  */
1057   s1 = single_set (i1);
1058   s2 = single_set (i2);
1059   if (s1 == NULL_RTX || s2 == NULL_RTX)
1060     return dir_none;
1061
1062   /* Check that the 2 sets set the same dest.  */
1063   d1 = SET_DEST (s1);
1064   d2 = SET_DEST (s2);
1065   if (!(reload_completed
1066         ? rtx_renumbered_equal_p (d1, d2) : rtx_equal_p (d1, d2)))
1067     return dir_none;
1068
1069   /* Find identical req_equiv or reg_equal note, which implies that the 2 sets
1070      set dest to the same value.  */
1071   note1 = find_reg_equal_equiv_note (i1);
1072   note2 = find_reg_equal_equiv_note (i2);
1073
1074   src1 = SET_SRC (s1);
1075   src2 = SET_SRC (s2);
1076
1077   if (!values_equal_p (note1, note2, src1, src2))
1078     return dir_none;
1079
1080   if (!equal_different_set_p (PATTERN (i1), s1, PATTERN (i2), s2))
1081     return dir_none;
1082
1083   /* Although the 2 sets set dest to the same value, we cannot replace
1084        (set (dest) (const_int))
1085      by
1086        (set (dest) (reg))
1087      because we don't know if the reg is live and has the same value at the
1088      location of replacement.  */
1089   c1 = CONST_INT_P (src1);
1090   c2 = CONST_INT_P (src2);
1091   if (c1 && c2)
1092     return dir_both;
1093   else if (c2)
1094     return dir_forward;
1095   else if (c1)
1096     return dir_backward;
1097
1098   return dir_none;
1099 }
1100
1101 /* Merges directions A and B.  */
1102
1103 static enum replace_direction
1104 merge_dir (enum replace_direction a, enum replace_direction b)
1105 {
1106   /* Implements the following table:
1107         |bo fw bw no
1108      ---+-----------
1109      bo |bo fw bw no
1110      fw |-- fw no no
1111      bw |-- -- bw no
1112      no |-- -- -- no.  */
1113
1114   if (a == b)
1115     return a;
1116
1117   if (a == dir_both)
1118     return b;
1119   if (b == dir_both)
1120     return a;
1121
1122   return dir_none;
1123 }
1124
1125 /* Examine I1 and I2 and return:
1126    - dir_forward if I1 can be replaced by I2, or
1127    - dir_backward if I2 can be replaced by I1, or
1128    - dir_both if both are the case.  */
1129
1130 static enum replace_direction
1131 old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
1132 {
1133   rtx p1, p2;
1134
1135   /* Verify that I1 and I2 are equivalent.  */
1136   if (GET_CODE (i1) != GET_CODE (i2))
1137     return dir_none;
1138
1139   /* __builtin_unreachable() may lead to empty blocks (ending with
1140      NOTE_INSN_BASIC_BLOCK).  They may be crossjumped. */
1141   if (NOTE_INSN_BASIC_BLOCK_P (i1) && NOTE_INSN_BASIC_BLOCK_P (i2))
1142     return dir_both;
1143
1144   /* ??? Do not allow cross-jumping between different stack levels.  */
1145   p1 = find_reg_note (i1, REG_ARGS_SIZE, NULL);
1146   p2 = find_reg_note (i2, REG_ARGS_SIZE, NULL);
1147   if (p1 && p2)
1148     {
1149       p1 = XEXP (p1, 0);
1150       p2 = XEXP (p2, 0);
1151       if (!rtx_equal_p (p1, p2))
1152         return dir_none;
1153
1154       /* ??? Worse, this adjustment had better be constant lest we
1155          have differing incoming stack levels.  */
1156       if (!frame_pointer_needed
1157           && find_args_size_adjust (i1) == HOST_WIDE_INT_MIN)
1158         return dir_none;
1159     }
1160   else if (p1 || p2)
1161     return dir_none;
1162
1163   p1 = PATTERN (i1);
1164   p2 = PATTERN (i2);
1165
1166   if (GET_CODE (p1) != GET_CODE (p2))
1167     return dir_none;
1168
1169   /* If this is a CALL_INSN, compare register usage information.
1170      If we don't check this on stack register machines, the two
1171      CALL_INSNs might be merged leaving reg-stack.c with mismatching
1172      numbers of stack registers in the same basic block.
1173      If we don't check this on machines with delay slots, a delay slot may
1174      be filled that clobbers a parameter expected by the subroutine.
1175
1176      ??? We take the simple route for now and assume that if they're
1177      equal, they were constructed identically.
1178
1179      Also check for identical exception regions.  */
1180
1181   if (CALL_P (i1))
1182     {
1183       /* Ensure the same EH region.  */
1184       rtx n1 = find_reg_note (i1, REG_EH_REGION, 0);
1185       rtx n2 = find_reg_note (i2, REG_EH_REGION, 0);
1186
1187       if (!n1 && n2)
1188         return dir_none;
1189
1190       if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1191         return dir_none;
1192
1193       if (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
1194                         CALL_INSN_FUNCTION_USAGE (i2))
1195           || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2))
1196         return dir_none;
1197
1198       /* For address sanitizer, never crossjump __asan_report_* builtins,
1199          otherwise errors might be reported on incorrect lines.  */
1200       if (flag_sanitize & SANITIZE_ADDRESS)
1201         {
1202           rtx call = get_call_rtx_from (i1);
1203           if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
1204             {
1205               rtx symbol = XEXP (XEXP (call, 0), 0);
1206               if (SYMBOL_REF_DECL (symbol)
1207                   && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
1208                 {
1209                   if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
1210                        == BUILT_IN_NORMAL)
1211                       && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1212                          >= BUILT_IN_ASAN_REPORT_LOAD1
1213                       && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1214                          <= BUILT_IN_ASAN_STOREN)
1215                     return dir_none;
1216                 }
1217             }
1218         }
1219     }
1220
1221 #ifdef STACK_REGS
1222   /* If cross_jump_death_matters is not 0, the insn's mode
1223      indicates whether or not the insn contains any stack-like
1224      regs.  */
1225
1226   if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
1227     {
1228       /* If register stack conversion has already been done, then
1229          death notes must also be compared before it is certain that
1230          the two instruction streams match.  */
1231
1232       rtx note;
1233       HARD_REG_SET i1_regset, i2_regset;
1234
1235       CLEAR_HARD_REG_SET (i1_regset);
1236       CLEAR_HARD_REG_SET (i2_regset);
1237
1238       for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
1239         if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1240           SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
1241
1242       for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
1243         if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1244           SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
1245
1246       if (!hard_reg_set_equal_p (i1_regset, i2_regset))
1247         return dir_none;
1248     }
1249 #endif
1250
1251   if (reload_completed
1252       ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
1253     return dir_both;
1254
1255   return can_replace_by (i1, i2);
1256 }
1257 \f
1258 /* When comparing insns I1 and I2 in flow_find_cross_jump or
1259    flow_find_head_matching_sequence, ensure the notes match.  */
1260
1261 static void
1262 merge_notes (rtx_insn *i1, rtx_insn *i2)
1263 {
1264   /* If the merged insns have different REG_EQUAL notes, then
1265      remove them.  */
1266   rtx equiv1 = find_reg_equal_equiv_note (i1);
1267   rtx equiv2 = find_reg_equal_equiv_note (i2);
1268
1269   if (equiv1 && !equiv2)
1270     remove_note (i1, equiv1);
1271   else if (!equiv1 && equiv2)
1272     remove_note (i2, equiv2);
1273   else if (equiv1 && equiv2
1274            && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1275     {
1276       remove_note (i1, equiv1);
1277       remove_note (i2, equiv2);
1278     }
1279 }
1280
1281  /* Walks from I1 in BB1 backward till the next non-debug insn, and returns the
1282     resulting insn in I1, and the corresponding bb in BB1.  At the head of a
1283     bb, if there is a predecessor bb that reaches this bb via fallthru, and
1284     FOLLOW_FALLTHRU, walks further in the predecessor bb and registers this in
1285     DID_FALLTHRU.  Otherwise, stops at the head of the bb.  */
1286
1287 static void
1288 walk_to_nondebug_insn (rtx_insn **i1, basic_block *bb1, bool follow_fallthru,
1289                        bool *did_fallthru)
1290 {
1291   edge fallthru;
1292
1293   *did_fallthru = false;
1294
1295   /* Ignore notes.  */
1296   while (!NONDEBUG_INSN_P (*i1))
1297     {
1298       if (*i1 != BB_HEAD (*bb1))
1299         {
1300           *i1 = PREV_INSN (*i1);
1301           continue;
1302         }
1303
1304       if (!follow_fallthru)
1305         return;
1306
1307       fallthru = find_fallthru_edge ((*bb1)->preds);
1308       if (!fallthru || fallthru->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
1309           || !single_succ_p (fallthru->src))
1310         return;
1311
1312       *bb1 = fallthru->src;
1313       *i1 = BB_END (*bb1);
1314       *did_fallthru = true;
1315      }
1316 }
1317
1318 /* Look through the insns at the end of BB1 and BB2 and find the longest
1319    sequence that are either equivalent, or allow forward or backward
1320    replacement.  Store the first insns for that sequence in *F1 and *F2 and
1321    return the sequence length.
1322
1323    DIR_P indicates the allowed replacement direction on function entry, and
1324    the actual replacement direction on function exit.  If NULL, only equivalent
1325    sequences are allowed.
1326
1327    To simplify callers of this function, if the blocks match exactly,
1328    store the head of the blocks in *F1 and *F2.  */
1329
1330 int
1331 flow_find_cross_jump (basic_block bb1, basic_block bb2, rtx_insn **f1,
1332                       rtx_insn **f2, enum replace_direction *dir_p)
1333 {
1334   rtx_insn *i1, *i2, *last1, *last2, *afterlast1, *afterlast2;
1335   int ninsns = 0;
1336   enum replace_direction dir, last_dir, afterlast_dir;
1337   bool follow_fallthru, did_fallthru;
1338
1339   if (dir_p)
1340     dir = *dir_p;
1341   else
1342     dir = dir_both;
1343   afterlast_dir = dir;
1344   last_dir = afterlast_dir;
1345
1346   /* Skip simple jumps at the end of the blocks.  Complex jumps still
1347      need to be compared for equivalence, which we'll do below.  */
1348
1349   i1 = BB_END (bb1);
1350   last1 = afterlast1 = last2 = afterlast2 = NULL;
1351   if (onlyjump_p (i1)
1352       || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1353     {
1354       last1 = i1;
1355       i1 = PREV_INSN (i1);
1356     }
1357
1358   i2 = BB_END (bb2);
1359   if (onlyjump_p (i2)
1360       || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1361     {
1362       last2 = i2;
1363       /* Count everything except for unconditional jump as insn.
1364          Don't count any jumps if dir_p is NULL.  */
1365       if (!simplejump_p (i2) && !returnjump_p (i2) && last1 && dir_p)
1366         ninsns++;
1367       i2 = PREV_INSN (i2);
1368     }
1369
1370   while (true)
1371     {
1372       /* In the following example, we can replace all jumps to C by jumps to A.
1373
1374          This removes 4 duplicate insns.
1375          [bb A] insn1            [bb C] insn1
1376                 insn2                   insn2
1377          [bb B] insn3                   insn3
1378                 insn4                   insn4
1379                 jump_insn               jump_insn
1380
1381          We could also replace all jumps to A by jumps to C, but that leaves B
1382          alive, and removes only 2 duplicate insns.  In a subsequent crossjump
1383          step, all jumps to B would be replaced with jumps to the middle of C,
1384          achieving the same result with more effort.
1385          So we allow only the first possibility, which means that we don't allow
1386          fallthru in the block that's being replaced.  */
1387
1388       follow_fallthru = dir_p && dir != dir_forward;
1389       walk_to_nondebug_insn (&i1, &bb1, follow_fallthru, &did_fallthru);
1390       if (did_fallthru)
1391         dir = dir_backward;
1392
1393       follow_fallthru = dir_p && dir != dir_backward;
1394       walk_to_nondebug_insn (&i2, &bb2, follow_fallthru, &did_fallthru);
1395       if (did_fallthru)
1396         dir = dir_forward;
1397
1398       if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1399         break;
1400
1401       dir = merge_dir (dir, old_insns_match_p (0, i1, i2));
1402       if (dir == dir_none || (!dir_p && dir != dir_both))
1403         break;
1404
1405       merge_memattrs (i1, i2);
1406
1407       /* Don't begin a cross-jump with a NOTE insn.  */
1408       if (INSN_P (i1))
1409         {
1410           merge_notes (i1, i2);
1411
1412           afterlast1 = last1, afterlast2 = last2;
1413           last1 = i1, last2 = i2;
1414           afterlast_dir = last_dir;
1415           last_dir = dir;
1416           if (active_insn_p (i1))
1417             ninsns++;
1418         }
1419
1420       i1 = PREV_INSN (i1);
1421       i2 = PREV_INSN (i2);
1422     }
1423
1424   /* Don't allow the insn after a compare to be shared by
1425      cross-jumping unless the compare is also shared.  */
1426   if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1427       && ! sets_cc0_p (last1))
1428     last1 = afterlast1, last2 = afterlast2, last_dir = afterlast_dir, ninsns--;
1429
1430   /* Include preceding notes and labels in the cross-jump.  One,
1431      this may bring us to the head of the blocks as requested above.
1432      Two, it keeps line number notes as matched as may be.  */
1433   if (ninsns)
1434     {
1435       bb1 = BLOCK_FOR_INSN (last1);
1436       while (last1 != BB_HEAD (bb1) && !NONDEBUG_INSN_P (PREV_INSN (last1)))
1437         last1 = PREV_INSN (last1);
1438
1439       if (last1 != BB_HEAD (bb1) && LABEL_P (PREV_INSN (last1)))
1440         last1 = PREV_INSN (last1);
1441
1442       bb2 = BLOCK_FOR_INSN (last2);
1443       while (last2 != BB_HEAD (bb2) && !NONDEBUG_INSN_P (PREV_INSN (last2)))
1444         last2 = PREV_INSN (last2);
1445
1446       if (last2 != BB_HEAD (bb2) && LABEL_P (PREV_INSN (last2)))
1447         last2 = PREV_INSN (last2);
1448
1449       *f1 = last1;
1450       *f2 = last2;
1451     }
1452
1453   if (dir_p)
1454     *dir_p = last_dir;
1455   return ninsns;
1456 }
1457
1458 /* Like flow_find_cross_jump, except start looking for a matching sequence from
1459    the head of the two blocks.  Do not include jumps at the end.
1460    If STOP_AFTER is nonzero, stop after finding that many matching
1461    instructions.  If STOP_AFTER is zero, count all INSN_P insns, if it is
1462    non-zero, only count active insns.  */
1463
1464 int
1465 flow_find_head_matching_sequence (basic_block bb1, basic_block bb2, rtx_insn **f1,
1466                                   rtx_insn **f2, int stop_after)
1467 {
1468   rtx_insn *i1, *i2, *last1, *last2, *beforelast1, *beforelast2;
1469   int ninsns = 0;
1470   edge e;
1471   edge_iterator ei;
1472   int nehedges1 = 0, nehedges2 = 0;
1473
1474   FOR_EACH_EDGE (e, ei, bb1->succs)
1475     if (e->flags & EDGE_EH)
1476       nehedges1++;
1477   FOR_EACH_EDGE (e, ei, bb2->succs)
1478     if (e->flags & EDGE_EH)
1479       nehedges2++;
1480
1481   i1 = BB_HEAD (bb1);
1482   i2 = BB_HEAD (bb2);
1483   last1 = beforelast1 = last2 = beforelast2 = NULL;
1484
1485   while (true)
1486     {
1487       /* Ignore notes, except NOTE_INSN_EPILOGUE_BEG.  */
1488       while (!NONDEBUG_INSN_P (i1) && i1 != BB_END (bb1))
1489         {
1490           if (NOTE_P (i1) && NOTE_KIND (i1) == NOTE_INSN_EPILOGUE_BEG)
1491             break;
1492           i1 = NEXT_INSN (i1);
1493         }
1494
1495       while (!NONDEBUG_INSN_P (i2) && i2 != BB_END (bb2))
1496         {
1497           if (NOTE_P (i2) && NOTE_KIND (i2) == NOTE_INSN_EPILOGUE_BEG)
1498             break;
1499           i2 = NEXT_INSN (i2);
1500         }
1501
1502       if ((i1 == BB_END (bb1) && !NONDEBUG_INSN_P (i1))
1503           || (i2 == BB_END (bb2) && !NONDEBUG_INSN_P (i2)))
1504         break;
1505
1506       if (NOTE_P (i1) || NOTE_P (i2)
1507           || JUMP_P (i1) || JUMP_P (i2))
1508         break;
1509
1510       /* A sanity check to make sure we're not merging insns with different
1511          effects on EH.  If only one of them ends a basic block, it shouldn't
1512          have an EH edge; if both end a basic block, there should be the same
1513          number of EH edges.  */
1514       if ((i1 == BB_END (bb1) && i2 != BB_END (bb2)
1515            && nehedges1 > 0)
1516           || (i2 == BB_END (bb2) && i1 != BB_END (bb1)
1517               && nehedges2 > 0)
1518           || (i1 == BB_END (bb1) && i2 == BB_END (bb2)
1519               && nehedges1 != nehedges2))
1520         break;
1521
1522       if (old_insns_match_p (0, i1, i2) != dir_both)
1523         break;
1524
1525       merge_memattrs (i1, i2);
1526
1527       /* Don't begin a cross-jump with a NOTE insn.  */
1528       if (INSN_P (i1))
1529         {
1530           merge_notes (i1, i2);
1531
1532           beforelast1 = last1, beforelast2 = last2;
1533           last1 = i1, last2 = i2;
1534           if (!stop_after || active_insn_p (i1))
1535             ninsns++;
1536         }
1537
1538       if (i1 == BB_END (bb1) || i2 == BB_END (bb2)
1539           || (stop_after > 0 && ninsns == stop_after))
1540         break;
1541
1542       i1 = NEXT_INSN (i1);
1543       i2 = NEXT_INSN (i2);
1544     }
1545
1546   /* Don't allow a compare to be shared by cross-jumping unless the insn
1547      after the compare is also shared.  */
1548   if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1549       && sets_cc0_p (last1))
1550     last1 = beforelast1, last2 = beforelast2, ninsns--;
1551
1552   if (ninsns)
1553     {
1554       *f1 = last1;
1555       *f2 = last2;
1556     }
1557
1558   return ninsns;
1559 }
1560
1561 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1562    the branch instruction.  This means that if we commonize the control
1563    flow before end of the basic block, the semantic remains unchanged.
1564
1565    We may assume that there exists one edge with a common destination.  */
1566
1567 static bool
1568 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1569 {
1570   int nehedges1 = 0, nehedges2 = 0;
1571   edge fallthru1 = 0, fallthru2 = 0;
1572   edge e1, e2;
1573   edge_iterator ei;
1574
1575   /* If we performed shrink-wrapping, edges to the exit block can
1576      only be distinguished for JUMP_INSNs.  The two paths may differ in
1577      whether they went through the prologue.  Sibcalls are fine, we know
1578      that we either didn't need or inserted an epilogue before them.  */
1579   if (crtl->shrink_wrapped
1580       && single_succ_p (bb1)
1581       && single_succ (bb1) == EXIT_BLOCK_PTR_FOR_FN (cfun)
1582       && !JUMP_P (BB_END (bb1))
1583       && !(CALL_P (BB_END (bb1)) && SIBLING_CALL_P (BB_END (bb1))))
1584     return false;
1585   
1586   /* If BB1 has only one successor, we may be looking at either an
1587      unconditional jump, or a fake edge to exit.  */
1588   if (single_succ_p (bb1)
1589       && (single_succ_edge (bb1)->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1590       && (!JUMP_P (BB_END (bb1)) || simplejump_p (BB_END (bb1))))
1591     return (single_succ_p (bb2)
1592             && (single_succ_edge (bb2)->flags
1593                 & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1594             && (!JUMP_P (BB_END (bb2)) || simplejump_p (BB_END (bb2))));
1595
1596   /* Match conditional jumps - this may get tricky when fallthru and branch
1597      edges are crossed.  */
1598   if (EDGE_COUNT (bb1->succs) == 2
1599       && any_condjump_p (BB_END (bb1))
1600       && onlyjump_p (BB_END (bb1)))
1601     {
1602       edge b1, f1, b2, f2;
1603       bool reverse, match;
1604       rtx set1, set2, cond1, cond2;
1605       enum rtx_code code1, code2;
1606
1607       if (EDGE_COUNT (bb2->succs) != 2
1608           || !any_condjump_p (BB_END (bb2))
1609           || !onlyjump_p (BB_END (bb2)))
1610         return false;
1611
1612       b1 = BRANCH_EDGE (bb1);
1613       b2 = BRANCH_EDGE (bb2);
1614       f1 = FALLTHRU_EDGE (bb1);
1615       f2 = FALLTHRU_EDGE (bb2);
1616
1617       /* Get around possible forwarders on fallthru edges.  Other cases
1618          should be optimized out already.  */
1619       if (FORWARDER_BLOCK_P (f1->dest))
1620         f1 = single_succ_edge (f1->dest);
1621
1622       if (FORWARDER_BLOCK_P (f2->dest))
1623         f2 = single_succ_edge (f2->dest);
1624
1625       /* To simplify use of this function, return false if there are
1626          unneeded forwarder blocks.  These will get eliminated later
1627          during cleanup_cfg.  */
1628       if (FORWARDER_BLOCK_P (f1->dest)
1629           || FORWARDER_BLOCK_P (f2->dest)
1630           || FORWARDER_BLOCK_P (b1->dest)
1631           || FORWARDER_BLOCK_P (b2->dest))
1632         return false;
1633
1634       if (f1->dest == f2->dest && b1->dest == b2->dest)
1635         reverse = false;
1636       else if (f1->dest == b2->dest && b1->dest == f2->dest)
1637         reverse = true;
1638       else
1639         return false;
1640
1641       set1 = pc_set (BB_END (bb1));
1642       set2 = pc_set (BB_END (bb2));
1643       if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1644           != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1645         reverse = !reverse;
1646
1647       cond1 = XEXP (SET_SRC (set1), 0);
1648       cond2 = XEXP (SET_SRC (set2), 0);
1649       code1 = GET_CODE (cond1);
1650       if (reverse)
1651         code2 = reversed_comparison_code (cond2, BB_END (bb2));
1652       else
1653         code2 = GET_CODE (cond2);
1654
1655       if (code2 == UNKNOWN)
1656         return false;
1657
1658       /* Verify codes and operands match.  */
1659       match = ((code1 == code2
1660                 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1661                 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1662                || (code1 == swap_condition (code2)
1663                    && rtx_renumbered_equal_p (XEXP (cond1, 1),
1664                                               XEXP (cond2, 0))
1665                    && rtx_renumbered_equal_p (XEXP (cond1, 0),
1666                                               XEXP (cond2, 1))));
1667
1668       /* If we return true, we will join the blocks.  Which means that
1669          we will only have one branch prediction bit to work with.  Thus
1670          we require the existing branches to have probabilities that are
1671          roughly similar.  */
1672       if (match
1673           && optimize_bb_for_speed_p (bb1)
1674           && optimize_bb_for_speed_p (bb2))
1675         {
1676           int prob2;
1677
1678           if (b1->dest == b2->dest)
1679             prob2 = b2->probability;
1680           else
1681             /* Do not use f2 probability as f2 may be forwarded.  */
1682             prob2 = REG_BR_PROB_BASE - b2->probability;
1683
1684           /* Fail if the difference in probabilities is greater than 50%.
1685              This rules out two well-predicted branches with opposite
1686              outcomes.  */
1687           if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1688             {
1689               if (dump_file)
1690                 fprintf (dump_file,
1691                          "Outcomes of branch in bb %i and %i differ too much (%i %i)\n",
1692                          bb1->index, bb2->index, b1->probability, prob2);
1693
1694               return false;
1695             }
1696         }
1697
1698       if (dump_file && match)
1699         fprintf (dump_file, "Conditionals in bb %i and %i match.\n",
1700                  bb1->index, bb2->index);
1701
1702       return match;
1703     }
1704
1705   /* Generic case - we are seeing a computed jump, table jump or trapping
1706      instruction.  */
1707
1708   /* Check whether there are tablejumps in the end of BB1 and BB2.
1709      Return true if they are identical.  */
1710     {
1711       rtx label1, label2;
1712       rtx_jump_table_data *table1, *table2;
1713
1714       if (tablejump_p (BB_END (bb1), &label1, &table1)
1715           && tablejump_p (BB_END (bb2), &label2, &table2)
1716           && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1717         {
1718           /* The labels should never be the same rtx.  If they really are same
1719              the jump tables are same too. So disable crossjumping of blocks BB1
1720              and BB2 because when deleting the common insns in the end of BB1
1721              by delete_basic_block () the jump table would be deleted too.  */
1722           /* If LABEL2 is referenced in BB1->END do not do anything
1723              because we would loose information when replacing
1724              LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END.  */
1725           if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1726             {
1727               /* Set IDENTICAL to true when the tables are identical.  */
1728               bool identical = false;
1729               rtx p1, p2;
1730
1731               p1 = PATTERN (table1);
1732               p2 = PATTERN (table2);
1733               if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1734                 {
1735                   identical = true;
1736                 }
1737               else if (GET_CODE (p1) == ADDR_DIFF_VEC
1738                        && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1739                        && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1740                        && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1741                 {
1742                   int i;
1743
1744                   identical = true;
1745                   for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1746                     if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1747                       identical = false;
1748                 }
1749
1750               if (identical)
1751                 {
1752                   bool match;
1753
1754                   /* Temporarily replace references to LABEL1 with LABEL2
1755                      in BB1->END so that we could compare the instructions.  */
1756                   replace_label_in_insn (BB_END (bb1), label1, label2, false);
1757
1758                   match = (old_insns_match_p (mode, BB_END (bb1), BB_END (bb2))
1759                            == dir_both);
1760                   if (dump_file && match)
1761                     fprintf (dump_file,
1762                              "Tablejumps in bb %i and %i match.\n",
1763                              bb1->index, bb2->index);
1764
1765                   /* Set the original label in BB1->END because when deleting
1766                      a block whose end is a tablejump, the tablejump referenced
1767                      from the instruction is deleted too.  */
1768                   replace_label_in_insn (BB_END (bb1), label2, label1, false);
1769
1770                   return match;
1771                 }
1772             }
1773           return false;
1774         }
1775     }
1776
1777   /* Find the last non-debug non-note instruction in each bb, except
1778      stop when we see the NOTE_INSN_BASIC_BLOCK, as old_insns_match_p
1779      handles that case specially. old_insns_match_p does not handle
1780      other types of instruction notes.  */
1781   rtx_insn *last1 = BB_END (bb1);
1782   rtx_insn *last2 = BB_END (bb2);
1783   while (!NOTE_INSN_BASIC_BLOCK_P (last1) &&
1784          (DEBUG_INSN_P (last1) || NOTE_P (last1)))
1785     last1 = PREV_INSN (last1);
1786   while (!NOTE_INSN_BASIC_BLOCK_P (last2) &&
1787          (DEBUG_INSN_P (last2) || NOTE_P (last2)))
1788     last2 = PREV_INSN (last2);
1789   gcc_assert (last1 && last2);
1790
1791   /* First ensure that the instructions match.  There may be many outgoing
1792      edges so this test is generally cheaper.  */
1793   if (old_insns_match_p (mode, last1, last2) != dir_both)
1794     return false;
1795
1796   /* Search the outgoing edges, ensure that the counts do match, find possible
1797      fallthru and exception handling edges since these needs more
1798      validation.  */
1799   if (EDGE_COUNT (bb1->succs) != EDGE_COUNT (bb2->succs))
1800     return false;
1801
1802   bool nonfakeedges = false;
1803   FOR_EACH_EDGE (e1, ei, bb1->succs)
1804     {
1805       e2 = EDGE_SUCC (bb2, ei.index);
1806
1807       if ((e1->flags & EDGE_FAKE) == 0)
1808         nonfakeedges = true;
1809
1810       if (e1->flags & EDGE_EH)
1811         nehedges1++;
1812
1813       if (e2->flags & EDGE_EH)
1814         nehedges2++;
1815
1816       if (e1->flags & EDGE_FALLTHRU)
1817         fallthru1 = e1;
1818       if (e2->flags & EDGE_FALLTHRU)
1819         fallthru2 = e2;
1820     }
1821
1822   /* If number of edges of various types does not match, fail.  */
1823   if (nehedges1 != nehedges2
1824       || (fallthru1 != 0) != (fallthru2 != 0))
1825     return false;
1826
1827   /* If !ACCUMULATE_OUTGOING_ARGS, bb1 (and bb2) have no successors
1828      and the last real insn doesn't have REG_ARGS_SIZE note, don't
1829      attempt to optimize, as the two basic blocks might have different
1830      REG_ARGS_SIZE depths.  For noreturn calls and unconditional
1831      traps there should be REG_ARG_SIZE notes, they could be missing
1832      for __builtin_unreachable () uses though.  */
1833   if (!nonfakeedges
1834       && !ACCUMULATE_OUTGOING_ARGS
1835       && (!INSN_P (last1)
1836           || !find_reg_note (last1, REG_ARGS_SIZE, NULL)))
1837     return false;
1838
1839   /* fallthru edges must be forwarded to the same destination.  */
1840   if (fallthru1)
1841     {
1842       basic_block d1 = (forwarder_block_p (fallthru1->dest)
1843                         ? single_succ (fallthru1->dest): fallthru1->dest);
1844       basic_block d2 = (forwarder_block_p (fallthru2->dest)
1845                         ? single_succ (fallthru2->dest): fallthru2->dest);
1846
1847       if (d1 != d2)
1848         return false;
1849     }
1850
1851   /* Ensure the same EH region.  */
1852   {
1853     rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1854     rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1855
1856     if (!n1 && n2)
1857       return false;
1858
1859     if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1860       return false;
1861   }
1862
1863   /* The same checks as in try_crossjump_to_edge. It is required for RTL
1864      version of sequence abstraction.  */
1865   FOR_EACH_EDGE (e1, ei, bb2->succs)
1866     {
1867       edge e2;
1868       edge_iterator ei;
1869       basic_block d1 = e1->dest;
1870
1871       if (FORWARDER_BLOCK_P (d1))
1872         d1 = EDGE_SUCC (d1, 0)->dest;
1873
1874       FOR_EACH_EDGE (e2, ei, bb1->succs)
1875         {
1876           basic_block d2 = e2->dest;
1877           if (FORWARDER_BLOCK_P (d2))
1878             d2 = EDGE_SUCC (d2, 0)->dest;
1879           if (d1 == d2)
1880             break;
1881         }
1882
1883       if (!e2)
1884         return false;
1885     }
1886
1887   return true;
1888 }
1889
1890 /* Returns true if BB basic block has a preserve label.  */
1891
1892 static bool
1893 block_has_preserve_label (basic_block bb)
1894 {
1895   return (bb
1896           && block_label (bb)
1897           && LABEL_PRESERVE_P (block_label (bb)));
1898 }
1899
1900 /* E1 and E2 are edges with the same destination block.  Search their
1901    predecessors for common code.  If found, redirect control flow from
1902    (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC (dir_forward),
1903    or the other way around (dir_backward).  DIR specifies the allowed
1904    replacement direction.  */
1905
1906 static bool
1907 try_crossjump_to_edge (int mode, edge e1, edge e2,
1908                        enum replace_direction dir)
1909 {
1910   int nmatch;
1911   basic_block src1 = e1->src, src2 = e2->src;
1912   basic_block redirect_to, redirect_from, to_remove;
1913   basic_block osrc1, osrc2, redirect_edges_to, tmp;
1914   rtx_insn *newpos1, *newpos2;
1915   edge s;
1916   edge_iterator ei;
1917
1918   newpos1 = newpos2 = NULL;
1919
1920   /* If we have partitioned hot/cold basic blocks, it is a bad idea
1921      to try this optimization.
1922
1923      Basic block partitioning may result in some jumps that appear to
1924      be optimizable (or blocks that appear to be mergeable), but which really
1925      must be left untouched (they are required to make it safely across
1926      partition boundaries).  See the comments at the top of
1927      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
1928
1929   if (crtl->has_bb_partition && reload_completed)
1930     return false;
1931
1932   /* Search backward through forwarder blocks.  We don't need to worry
1933      about multiple entry or chained forwarders, as they will be optimized
1934      away.  We do this to look past the unconditional jump following a
1935      conditional jump that is required due to the current CFG shape.  */
1936   if (single_pred_p (src1)
1937       && FORWARDER_BLOCK_P (src1))
1938     e1 = single_pred_edge (src1), src1 = e1->src;
1939
1940   if (single_pred_p (src2)
1941       && FORWARDER_BLOCK_P (src2))
1942     e2 = single_pred_edge (src2), src2 = e2->src;
1943
1944   /* Nothing to do if we reach ENTRY, or a common source block.  */
1945   if (src1 == ENTRY_BLOCK_PTR_FOR_FN (cfun) || src2
1946       == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1947     return false;
1948   if (src1 == src2)
1949     return false;
1950
1951   /* Seeing more than 1 forwarder blocks would confuse us later...  */
1952   if (FORWARDER_BLOCK_P (e1->dest)
1953       && FORWARDER_BLOCK_P (single_succ (e1->dest)))
1954     return false;
1955
1956   if (FORWARDER_BLOCK_P (e2->dest)
1957       && FORWARDER_BLOCK_P (single_succ (e2->dest)))
1958     return false;
1959
1960   /* Likewise with dead code (possibly newly created by the other optimizations
1961      of cfg_cleanup).  */
1962   if (EDGE_COUNT (src1->preds) == 0 || EDGE_COUNT (src2->preds) == 0)
1963     return false;
1964
1965   /* Look for the common insn sequence, part the first ...  */
1966   if (!outgoing_edges_match (mode, src1, src2))
1967     return false;
1968
1969   /* ... and part the second.  */
1970   nmatch = flow_find_cross_jump (src1, src2, &newpos1, &newpos2, &dir);
1971
1972   osrc1 = src1;
1973   osrc2 = src2;
1974   if (newpos1 != NULL_RTX)
1975     src1 = BLOCK_FOR_INSN (newpos1);
1976   if (newpos2 != NULL_RTX)
1977     src2 = BLOCK_FOR_INSN (newpos2);
1978
1979   if (dir == dir_backward)
1980     {
1981 #define SWAP(T, X, Y) do { T tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
1982       SWAP (basic_block, osrc1, osrc2);
1983       SWAP (basic_block, src1, src2);
1984       SWAP (edge, e1, e2);
1985       SWAP (rtx_insn *, newpos1, newpos2);
1986 #undef SWAP
1987     }
1988
1989   /* Don't proceed with the crossjump unless we found a sufficient number
1990      of matching instructions or the 'from' block was totally matched
1991      (such that its predecessors will hopefully be redirected and the
1992      block removed).  */
1993   if ((nmatch < PARAM_VALUE (PARAM_MIN_CROSSJUMP_INSNS))
1994       && (newpos1 != BB_HEAD (src1)))
1995     return false;
1996
1997   /* Avoid deleting preserve label when redirecting ABNORMAL edges.  */
1998   if (block_has_preserve_label (e1->dest)
1999       && (e1->flags & EDGE_ABNORMAL))
2000     return false;
2001
2002   /* Here we know that the insns in the end of SRC1 which are common with SRC2
2003      will be deleted.
2004      If we have tablejumps in the end of SRC1 and SRC2
2005      they have been already compared for equivalence in outgoing_edges_match ()
2006      so replace the references to TABLE1 by references to TABLE2.  */
2007   {
2008       rtx label1, label2;
2009       rtx_jump_table_data *table1, *table2;
2010
2011       if (tablejump_p (BB_END (osrc1), &label1, &table1)
2012           && tablejump_p (BB_END (osrc2), &label2, &table2)
2013           && label1 != label2)
2014         {
2015           rtx_insn *insn;
2016
2017           /* Replace references to LABEL1 with LABEL2.  */
2018           for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2019             {
2020               /* Do not replace the label in SRC1->END because when deleting
2021                  a block whose end is a tablejump, the tablejump referenced
2022                  from the instruction is deleted too.  */
2023               if (insn != BB_END (osrc1))
2024                 replace_label_in_insn (insn, label1, label2, true);
2025             }
2026         }
2027   }
2028
2029   /* Avoid splitting if possible.  We must always split when SRC2 has
2030      EH predecessor edges, or we may end up with basic blocks with both
2031      normal and EH predecessor edges.  */
2032   if (newpos2 == BB_HEAD (src2)
2033       && !(EDGE_PRED (src2, 0)->flags & EDGE_EH))
2034     redirect_to = src2;
2035   else
2036     {
2037       if (newpos2 == BB_HEAD (src2))
2038         {
2039           /* Skip possible basic block header.  */
2040           if (LABEL_P (newpos2))
2041             newpos2 = NEXT_INSN (newpos2);
2042           while (DEBUG_INSN_P (newpos2))
2043             newpos2 = NEXT_INSN (newpos2);
2044           if (NOTE_P (newpos2))
2045             newpos2 = NEXT_INSN (newpos2);
2046           while (DEBUG_INSN_P (newpos2))
2047             newpos2 = NEXT_INSN (newpos2);
2048         }
2049
2050       if (dump_file)
2051         fprintf (dump_file, "Splitting bb %i before %i insns\n",
2052                  src2->index, nmatch);
2053       redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
2054     }
2055
2056   if (dump_file)
2057     fprintf (dump_file,
2058              "Cross jumping from bb %i to bb %i; %i common insns\n",
2059              src1->index, src2->index, nmatch);
2060
2061   /* We may have some registers visible through the block.  */
2062   df_set_bb_dirty (redirect_to);
2063
2064   if (osrc2 == src2)
2065     redirect_edges_to = redirect_to;
2066   else
2067     redirect_edges_to = osrc2;
2068
2069   /* Recompute the frequencies and counts of outgoing edges.  */
2070   FOR_EACH_EDGE (s, ei, redirect_edges_to->succs)
2071     {
2072       edge s2;
2073       edge_iterator ei;
2074       basic_block d = s->dest;
2075
2076       if (FORWARDER_BLOCK_P (d))
2077         d = single_succ (d);
2078
2079       FOR_EACH_EDGE (s2, ei, src1->succs)
2080         {
2081           basic_block d2 = s2->dest;
2082           if (FORWARDER_BLOCK_P (d2))
2083             d2 = single_succ (d2);
2084           if (d == d2)
2085             break;
2086         }
2087
2088       s->count += s2->count;
2089
2090       /* Take care to update possible forwarder blocks.  We verified
2091          that there is no more than one in the chain, so we can't run
2092          into infinite loop.  */
2093       if (FORWARDER_BLOCK_P (s->dest))
2094         {
2095           single_succ_edge (s->dest)->count += s2->count;
2096           s->dest->count += s2->count;
2097           s->dest->frequency += EDGE_FREQUENCY (s);
2098         }
2099
2100       if (FORWARDER_BLOCK_P (s2->dest))
2101         {
2102           single_succ_edge (s2->dest)->count -= s2->count;
2103           if (single_succ_edge (s2->dest)->count < 0)
2104             single_succ_edge (s2->dest)->count = 0;
2105           s2->dest->count -= s2->count;
2106           s2->dest->frequency -= EDGE_FREQUENCY (s);
2107           if (s2->dest->frequency < 0)
2108             s2->dest->frequency = 0;
2109           if (s2->dest->count < 0)
2110             s2->dest->count = 0;
2111         }
2112
2113       if (!redirect_edges_to->frequency && !src1->frequency)
2114         s->probability = (s->probability + s2->probability) / 2;
2115       else
2116         s->probability
2117           = ((s->probability * redirect_edges_to->frequency +
2118               s2->probability * src1->frequency)
2119              / (redirect_edges_to->frequency + src1->frequency));
2120     }
2121
2122   /* Adjust count and frequency for the block.  An earlier jump
2123      threading pass may have left the profile in an inconsistent
2124      state (see update_bb_profile_for_threading) so we must be
2125      prepared for overflows.  */
2126   tmp = redirect_to;
2127   do
2128     {
2129       tmp->count += src1->count;
2130       tmp->frequency += src1->frequency;
2131       if (tmp->frequency > BB_FREQ_MAX)
2132         tmp->frequency = BB_FREQ_MAX;
2133       if (tmp == redirect_edges_to)
2134         break;
2135       tmp = find_fallthru_edge (tmp->succs)->dest;
2136     }
2137   while (true);
2138   update_br_prob_note (redirect_edges_to);
2139
2140   /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1.  */
2141
2142   /* Skip possible basic block header.  */
2143   if (LABEL_P (newpos1))
2144     newpos1 = NEXT_INSN (newpos1);
2145
2146   while (DEBUG_INSN_P (newpos1))
2147     newpos1 = NEXT_INSN (newpos1);
2148
2149   if (NOTE_INSN_BASIC_BLOCK_P (newpos1))
2150     newpos1 = NEXT_INSN (newpos1);
2151
2152   while (DEBUG_INSN_P (newpos1))
2153     newpos1 = NEXT_INSN (newpos1);
2154
2155   redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
2156   to_remove = single_succ (redirect_from);
2157
2158   redirect_edge_and_branch_force (single_succ_edge (redirect_from), redirect_to);
2159   delete_basic_block (to_remove);
2160
2161   update_forwarder_flag (redirect_from);
2162   if (redirect_to != src2)
2163     update_forwarder_flag (src2);
2164
2165   return true;
2166 }
2167
2168 /* Search the predecessors of BB for common insn sequences.  When found,
2169    share code between them by redirecting control flow.  Return true if
2170    any changes made.  */
2171
2172 static bool
2173 try_crossjump_bb (int mode, basic_block bb)
2174 {
2175   edge e, e2, fallthru;
2176   bool changed;
2177   unsigned max, ix, ix2;
2178
2179   /* Nothing to do if there is not at least two incoming edges.  */
2180   if (EDGE_COUNT (bb->preds) < 2)
2181     return false;
2182
2183   /* Don't crossjump if this block ends in a computed jump,
2184      unless we are optimizing for size.  */
2185   if (optimize_bb_for_size_p (bb)
2186       && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2187       && computed_jump_p (BB_END (bb)))
2188     return false;
2189
2190   /* If we are partitioning hot/cold basic blocks, we don't want to
2191      mess up unconditional or indirect jumps that cross between hot
2192      and cold sections.
2193
2194      Basic block partitioning may result in some jumps that appear to
2195      be optimizable (or blocks that appear to be mergeable), but which really
2196      must be left untouched (they are required to make it safely across
2197      partition boundaries).  See the comments at the top of
2198      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
2199
2200   if (BB_PARTITION (EDGE_PRED (bb, 0)->src) !=
2201                                         BB_PARTITION (EDGE_PRED (bb, 1)->src)
2202       || (EDGE_PRED (bb, 0)->flags & EDGE_CROSSING))
2203     return false;
2204
2205   /* It is always cheapest to redirect a block that ends in a branch to
2206      a block that falls through into BB, as that adds no branches to the
2207      program.  We'll try that combination first.  */
2208   fallthru = NULL;
2209   max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
2210
2211   if (EDGE_COUNT (bb->preds) > max)
2212     return false;
2213
2214   fallthru = find_fallthru_edge (bb->preds);
2215
2216   changed = false;
2217   for (ix = 0; ix < EDGE_COUNT (bb->preds);)
2218     {
2219       e = EDGE_PRED (bb, ix);
2220       ix++;
2221
2222       /* As noted above, first try with the fallthru predecessor (or, a
2223          fallthru predecessor if we are in cfglayout mode).  */
2224       if (fallthru)
2225         {
2226           /* Don't combine the fallthru edge into anything else.
2227              If there is a match, we'll do it the other way around.  */
2228           if (e == fallthru)
2229             continue;
2230           /* If nothing changed since the last attempt, there is nothing
2231              we can do.  */
2232           if (!first_pass
2233               && !((e->src->flags & BB_MODIFIED)
2234                    || (fallthru->src->flags & BB_MODIFIED)))
2235             continue;
2236
2237           if (try_crossjump_to_edge (mode, e, fallthru, dir_forward))
2238             {
2239               changed = true;
2240               ix = 0;
2241               continue;
2242             }
2243         }
2244
2245       /* Non-obvious work limiting check: Recognize that we're going
2246          to call try_crossjump_bb on every basic block.  So if we have
2247          two blocks with lots of outgoing edges (a switch) and they
2248          share lots of common destinations, then we would do the
2249          cross-jump check once for each common destination.
2250
2251          Now, if the blocks actually are cross-jump candidates, then
2252          all of their destinations will be shared.  Which means that
2253          we only need check them for cross-jump candidacy once.  We
2254          can eliminate redundant checks of crossjump(A,B) by arbitrarily
2255          choosing to do the check from the block for which the edge
2256          in question is the first successor of A.  */
2257       if (EDGE_SUCC (e->src, 0) != e)
2258         continue;
2259
2260       for (ix2 = 0; ix2 < EDGE_COUNT (bb->preds); ix2++)
2261         {
2262           e2 = EDGE_PRED (bb, ix2);
2263
2264           if (e2 == e)
2265             continue;
2266
2267           /* We've already checked the fallthru edge above.  */
2268           if (e2 == fallthru)
2269             continue;
2270
2271           /* The "first successor" check above only prevents multiple
2272              checks of crossjump(A,B).  In order to prevent redundant
2273              checks of crossjump(B,A), require that A be the block
2274              with the lowest index.  */
2275           if (e->src->index > e2->src->index)
2276             continue;
2277
2278           /* If nothing changed since the last attempt, there is nothing
2279              we can do.  */
2280           if (!first_pass
2281               && !((e->src->flags & BB_MODIFIED)
2282                    || (e2->src->flags & BB_MODIFIED)))
2283             continue;
2284
2285           /* Both e and e2 are not fallthru edges, so we can crossjump in either
2286              direction.  */
2287           if (try_crossjump_to_edge (mode, e, e2, dir_both))
2288             {
2289               changed = true;
2290               ix = 0;
2291               break;
2292             }
2293         }
2294     }
2295
2296   if (changed)
2297     crossjumps_occured = true;
2298
2299   return changed;
2300 }
2301
2302 /* Search the successors of BB for common insn sequences.  When found,
2303    share code between them by moving it across the basic block
2304    boundary.  Return true if any changes made.  */
2305
2306 static bool
2307 try_head_merge_bb (basic_block bb)
2308 {
2309   basic_block final_dest_bb = NULL;
2310   int max_match = INT_MAX;
2311   edge e0;
2312   rtx_insn **headptr, **currptr, **nextptr;
2313   bool changed, moveall;
2314   unsigned ix;
2315   rtx_insn *e0_last_head;
2316   rtx cond;
2317   rtx_insn *move_before;
2318   unsigned nedges = EDGE_COUNT (bb->succs);
2319   rtx_insn *jump = BB_END (bb);
2320   regset live, live_union;
2321
2322   /* Nothing to do if there is not at least two outgoing edges.  */
2323   if (nedges < 2)
2324     return false;
2325
2326   /* Don't crossjump if this block ends in a computed jump,
2327      unless we are optimizing for size.  */
2328   if (optimize_bb_for_size_p (bb)
2329       && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2330       && computed_jump_p (BB_END (bb)))
2331     return false;
2332
2333   cond = get_condition (jump, &move_before, true, false);
2334   if (cond == NULL_RTX)
2335     {
2336       if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2337         move_before = prev_nonnote_nondebug_insn (jump);
2338       else
2339         move_before = jump;
2340     }
2341
2342   for (ix = 0; ix < nedges; ix++)
2343     if (EDGE_SUCC (bb, ix)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
2344       return false;
2345
2346   for (ix = 0; ix < nedges; ix++)
2347     {
2348       edge e = EDGE_SUCC (bb, ix);
2349       basic_block other_bb = e->dest;
2350
2351       if (df_get_bb_dirty (other_bb))
2352         {
2353           block_was_dirty = true;
2354           return false;
2355         }
2356
2357       if (e->flags & EDGE_ABNORMAL)
2358         return false;
2359
2360       /* Normally, all destination blocks must only be reachable from this
2361          block, i.e. they must have one incoming edge.
2362
2363          There is one special case we can handle, that of multiple consecutive
2364          jumps where the first jumps to one of the targets of the second jump.
2365          This happens frequently in switch statements for default labels.
2366          The structure is as follows:
2367          FINAL_DEST_BB
2368          ....
2369          if (cond) jump A;
2370          fall through
2371          BB
2372          jump with targets A, B, C, D...
2373          A
2374          has two incoming edges, from FINAL_DEST_BB and BB
2375
2376          In this case, we can try to move the insns through BB and into
2377          FINAL_DEST_BB.  */
2378       if (EDGE_COUNT (other_bb->preds) != 1)
2379         {
2380           edge incoming_edge, incoming_bb_other_edge;
2381           edge_iterator ei;
2382
2383           if (final_dest_bb != NULL
2384               || EDGE_COUNT (other_bb->preds) != 2)
2385             return false;
2386
2387           /* We must be able to move the insns across the whole block.  */
2388           move_before = BB_HEAD (bb);
2389           while (!NONDEBUG_INSN_P (move_before))
2390             move_before = NEXT_INSN (move_before);
2391
2392           if (EDGE_COUNT (bb->preds) != 1)
2393             return false;
2394           incoming_edge = EDGE_PRED (bb, 0);
2395           final_dest_bb = incoming_edge->src;
2396           if (EDGE_COUNT (final_dest_bb->succs) != 2)
2397             return false;
2398           FOR_EACH_EDGE (incoming_bb_other_edge, ei, final_dest_bb->succs)
2399             if (incoming_bb_other_edge != incoming_edge)
2400               break;
2401           if (incoming_bb_other_edge->dest != other_bb)
2402             return false;
2403         }
2404     }
2405
2406   e0 = EDGE_SUCC (bb, 0);
2407   e0_last_head = NULL;
2408   changed = false;
2409
2410   for (ix = 1; ix < nedges; ix++)
2411     {
2412       edge e = EDGE_SUCC (bb, ix);
2413       rtx_insn *e0_last, *e_last;
2414       int nmatch;
2415
2416       nmatch = flow_find_head_matching_sequence (e0->dest, e->dest,
2417                                                  &e0_last, &e_last, 0);
2418       if (nmatch == 0)
2419         return false;
2420
2421       if (nmatch < max_match)
2422         {
2423           max_match = nmatch;
2424           e0_last_head = e0_last;
2425         }
2426     }
2427
2428   /* If we matched an entire block, we probably have to avoid moving the
2429      last insn.  */
2430   if (max_match > 0
2431       && e0_last_head == BB_END (e0->dest)
2432       && (find_reg_note (e0_last_head, REG_EH_REGION, 0)
2433           || control_flow_insn_p (e0_last_head)))
2434     {
2435       max_match--;
2436       if (max_match == 0)
2437         return false;
2438       do
2439         e0_last_head = prev_real_insn (e0_last_head);
2440       while (DEBUG_INSN_P (e0_last_head));
2441     }
2442
2443   if (max_match == 0)
2444     return false;
2445
2446   /* We must find a union of the live registers at each of the end points.  */
2447   live = BITMAP_ALLOC (NULL);
2448   live_union = BITMAP_ALLOC (NULL);
2449
2450   currptr = XNEWVEC (rtx_insn *, nedges);
2451   headptr = XNEWVEC (rtx_insn *, nedges);
2452   nextptr = XNEWVEC (rtx_insn *, nedges);
2453
2454   for (ix = 0; ix < nedges; ix++)
2455     {
2456       int j;
2457       basic_block merge_bb = EDGE_SUCC (bb, ix)->dest;
2458       rtx_insn *head = BB_HEAD (merge_bb);
2459
2460       while (!NONDEBUG_INSN_P (head))
2461         head = NEXT_INSN (head);
2462       headptr[ix] = head;
2463       currptr[ix] = head;
2464
2465       /* Compute the end point and live information  */
2466       for (j = 1; j < max_match; j++)
2467         do
2468           head = NEXT_INSN (head);
2469         while (!NONDEBUG_INSN_P (head));
2470       simulate_backwards_to_point (merge_bb, live, head);
2471       IOR_REG_SET (live_union, live);
2472     }
2473
2474   /* If we're moving across two blocks, verify the validity of the
2475      first move, then adjust the target and let the loop below deal
2476      with the final move.  */
2477   if (final_dest_bb != NULL)
2478     {
2479       rtx_insn *move_upto;
2480
2481       moveall = can_move_insns_across (currptr[0], e0_last_head, move_before,
2482                                        jump, e0->dest, live_union,
2483                                        NULL, &move_upto);
2484       if (!moveall)
2485         {
2486           if (move_upto == NULL_RTX)
2487             goto out;
2488
2489           while (e0_last_head != move_upto)
2490             {
2491               df_simulate_one_insn_backwards (e0->dest, e0_last_head,
2492                                               live_union);
2493               e0_last_head = PREV_INSN (e0_last_head);
2494             }
2495         }
2496       if (e0_last_head == NULL_RTX)
2497         goto out;
2498
2499       jump = BB_END (final_dest_bb);
2500       cond = get_condition (jump, &move_before, true, false);
2501       if (cond == NULL_RTX)
2502         {
2503           if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2504             move_before = prev_nonnote_nondebug_insn (jump);
2505           else
2506             move_before = jump;
2507         }
2508     }
2509
2510   do
2511     {
2512       rtx_insn *move_upto;
2513       moveall = can_move_insns_across (currptr[0], e0_last_head,
2514                                        move_before, jump, e0->dest, live_union,
2515                                        NULL, &move_upto);
2516       if (!moveall && move_upto == NULL_RTX)
2517         {
2518           if (jump == move_before)
2519             break;
2520
2521           /* Try again, using a different insertion point.  */
2522           move_before = jump;
2523
2524           /* Don't try moving before a cc0 user, as that may invalidate
2525              the cc0.  */
2526           if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2527             break;
2528
2529           continue;
2530         }
2531
2532       if (final_dest_bb && !moveall)
2533         /* We haven't checked whether a partial move would be OK for the first
2534            move, so we have to fail this case.  */
2535         break;
2536
2537       changed = true;
2538       for (;;)
2539         {
2540           if (currptr[0] == move_upto)
2541             break;
2542           for (ix = 0; ix < nedges; ix++)
2543             {
2544               rtx_insn *curr = currptr[ix];
2545               do
2546                 curr = NEXT_INSN (curr);
2547               while (!NONDEBUG_INSN_P (curr));
2548               currptr[ix] = curr;
2549             }
2550         }
2551
2552       /* If we can't currently move all of the identical insns, remember
2553          each insn after the range that we'll merge.  */
2554       if (!moveall)
2555         for (ix = 0; ix < nedges; ix++)
2556           {
2557             rtx_insn *curr = currptr[ix];
2558             do
2559               curr = NEXT_INSN (curr);
2560             while (!NONDEBUG_INSN_P (curr));
2561             nextptr[ix] = curr;
2562           }
2563
2564       reorder_insns (headptr[0], currptr[0], PREV_INSN (move_before));
2565       df_set_bb_dirty (EDGE_SUCC (bb, 0)->dest);
2566       if (final_dest_bb != NULL)
2567         df_set_bb_dirty (final_dest_bb);
2568       df_set_bb_dirty (bb);
2569       for (ix = 1; ix < nedges; ix++)
2570         {
2571           df_set_bb_dirty (EDGE_SUCC (bb, ix)->dest);
2572           delete_insn_chain (headptr[ix], currptr[ix], false);
2573         }
2574       if (!moveall)
2575         {
2576           if (jump == move_before)
2577             break;
2578
2579           /* For the unmerged insns, try a different insertion point.  */
2580           move_before = jump;
2581
2582           /* Don't try moving before a cc0 user, as that may invalidate
2583              the cc0.  */
2584           if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2585             break;
2586
2587           for (ix = 0; ix < nedges; ix++)
2588             currptr[ix] = headptr[ix] = nextptr[ix];
2589         }
2590     }
2591   while (!moveall);
2592
2593  out:
2594   free (currptr);
2595   free (headptr);
2596   free (nextptr);
2597
2598   crossjumps_occured |= changed;
2599
2600   return changed;
2601 }
2602
2603 /* Return true if BB contains just bb note, or bb note followed
2604    by only DEBUG_INSNs.  */
2605
2606 static bool
2607 trivially_empty_bb_p (basic_block bb)
2608 {
2609   rtx_insn *insn = BB_END (bb);
2610
2611   while (1)
2612     {
2613       if (insn == BB_HEAD (bb))
2614         return true;
2615       if (!DEBUG_INSN_P (insn))
2616         return false;
2617       insn = PREV_INSN (insn);
2618     }
2619 }
2620
2621 /* Do simple CFG optimizations - basic block merging, simplifying of jump
2622    instructions etc.  Return nonzero if changes were made.  */
2623
2624 static bool
2625 try_optimize_cfg (int mode)
2626 {
2627   bool changed_overall = false;
2628   bool changed;
2629   int iterations = 0;
2630   basic_block bb, b, next;
2631
2632   if (mode & (CLEANUP_CROSSJUMP | CLEANUP_THREADING))
2633     clear_bb_flags ();
2634
2635   crossjumps_occured = false;
2636
2637   FOR_EACH_BB_FN (bb, cfun)
2638     update_forwarder_flag (bb);
2639
2640   if (! targetm.cannot_modify_jumps_p ())
2641     {
2642       first_pass = true;
2643       /* Attempt to merge blocks as made possible by edge removal.  If
2644          a block has only one successor, and the successor has only
2645          one predecessor, they may be combined.  */
2646       do
2647         {
2648           block_was_dirty = false;
2649           changed = false;
2650           iterations++;
2651
2652           if (dump_file)
2653             fprintf (dump_file,
2654                      "\n\ntry_optimize_cfg iteration %i\n\n",
2655                      iterations);
2656
2657           for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
2658                != EXIT_BLOCK_PTR_FOR_FN (cfun);)
2659             {
2660               basic_block c;
2661               edge s;
2662               bool changed_here = false;
2663
2664               /* Delete trivially dead basic blocks.  This is either
2665                  blocks with no predecessors, or empty blocks with no
2666                  successors.  However if the empty block with no
2667                  successors is the successor of the ENTRY_BLOCK, it is
2668                  kept.  This ensures that the ENTRY_BLOCK will have a
2669                  successor which is a precondition for many RTL
2670                  passes.  Empty blocks may result from expanding
2671                  __builtin_unreachable ().  */
2672               if (EDGE_COUNT (b->preds) == 0
2673                   || (EDGE_COUNT (b->succs) == 0
2674                       && trivially_empty_bb_p (b)
2675                       && single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->dest
2676                       != b))
2677                 {
2678                   c = b->prev_bb;
2679                   if (EDGE_COUNT (b->preds) > 0)
2680                     {
2681                       edge e;
2682                       edge_iterator ei;
2683
2684                       if (current_ir_type () == IR_RTL_CFGLAYOUT)
2685                         {
2686                           if (BB_FOOTER (b)
2687                               && BARRIER_P (BB_FOOTER (b)))
2688                             FOR_EACH_EDGE (e, ei, b->preds)
2689                               if ((e->flags & EDGE_FALLTHRU)
2690                                   && BB_FOOTER (e->src) == NULL)
2691                                 {
2692                                   if (BB_FOOTER (b))
2693                                     {
2694                                       BB_FOOTER (e->src) = BB_FOOTER (b);
2695                                       BB_FOOTER (b) = NULL;
2696                                     }
2697                                   else
2698                                     {
2699                                       start_sequence ();
2700                                       BB_FOOTER (e->src) = emit_barrier ();
2701                                       end_sequence ();
2702                                     }
2703                                 }
2704                         }
2705                       else
2706                         {
2707                           rtx_insn *last = get_last_bb_insn (b);
2708                           if (last && BARRIER_P (last))
2709                             FOR_EACH_EDGE (e, ei, b->preds)
2710                               if ((e->flags & EDGE_FALLTHRU))
2711                                 emit_barrier_after (BB_END (e->src));
2712                         }
2713                     }
2714                   delete_basic_block (b);
2715                   changed = true;
2716                   /* Avoid trying to remove the exit block.  */
2717                   b = (c == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? c->next_bb : c);
2718                   continue;
2719                 }
2720
2721               /* Remove code labels no longer used.  */
2722               if (single_pred_p (b)
2723                   && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2724                   && !(single_pred_edge (b)->flags & EDGE_COMPLEX)
2725                   && LABEL_P (BB_HEAD (b))
2726                   && !LABEL_PRESERVE_P (BB_HEAD (b))
2727                   /* If the previous block ends with a branch to this
2728                      block, we can't delete the label.  Normally this
2729                      is a condjump that is yet to be simplified, but
2730                      if CASE_DROPS_THRU, this can be a tablejump with
2731                      some element going to the same place as the
2732                      default (fallthru).  */
2733                   && (single_pred (b) == ENTRY_BLOCK_PTR_FOR_FN (cfun)
2734                       || !JUMP_P (BB_END (single_pred (b)))
2735                       || ! label_is_jump_target_p (BB_HEAD (b),
2736                                                    BB_END (single_pred (b)))))
2737                 {
2738                   delete_insn (BB_HEAD (b));
2739                   if (dump_file)
2740                     fprintf (dump_file, "Deleted label in block %i.\n",
2741                              b->index);
2742                 }
2743
2744               /* If we fall through an empty block, we can remove it.  */
2745               if (!(mode & (CLEANUP_CFGLAYOUT | CLEANUP_NO_INSN_DEL))
2746                   && single_pred_p (b)
2747                   && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2748                   && !LABEL_P (BB_HEAD (b))
2749                   && FORWARDER_BLOCK_P (b)
2750                   /* Note that forwarder_block_p true ensures that
2751                      there is a successor for this block.  */
2752                   && (single_succ_edge (b)->flags & EDGE_FALLTHRU)
2753                   && n_basic_blocks_for_fn (cfun) > NUM_FIXED_BLOCKS + 1)
2754                 {
2755                   if (dump_file)
2756                     fprintf (dump_file,
2757                              "Deleting fallthru block %i.\n",
2758                              b->index);
2759
2760                   c = ((b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
2761                        ? b->next_bb : b->prev_bb);
2762                   redirect_edge_succ_nodup (single_pred_edge (b),
2763                                             single_succ (b));
2764                   delete_basic_block (b);
2765                   changed = true;
2766                   b = c;
2767                   continue;
2768                 }
2769
2770               /* Merge B with its single successor, if any.  */
2771               if (single_succ_p (b)
2772                   && (s = single_succ_edge (b))
2773                   && !(s->flags & EDGE_COMPLEX)
2774                   && (c = s->dest) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2775                   && single_pred_p (c)
2776                   && b != c)
2777                 {
2778                   /* When not in cfg_layout mode use code aware of reordering
2779                      INSN.  This code possibly creates new basic blocks so it
2780                      does not fit merge_blocks interface and is kept here in
2781                      hope that it will become useless once more of compiler
2782                      is transformed to use cfg_layout mode.  */
2783
2784                   if ((mode & CLEANUP_CFGLAYOUT)
2785                       && can_merge_blocks_p (b, c))
2786                     {
2787                       merge_blocks (b, c);
2788                       update_forwarder_flag (b);
2789                       changed_here = true;
2790                     }
2791                   else if (!(mode & CLEANUP_CFGLAYOUT)
2792                            /* If the jump insn has side effects,
2793                               we can't kill the edge.  */
2794                            && (!JUMP_P (BB_END (b))
2795                                || (reload_completed
2796                                    ? simplejump_p (BB_END (b))
2797                                    : (onlyjump_p (BB_END (b))
2798                                       && !tablejump_p (BB_END (b),
2799                                                        NULL, NULL))))
2800                            && (next = merge_blocks_move (s, b, c, mode)))
2801                       {
2802                         b = next;
2803                         changed_here = true;
2804                       }
2805                 }
2806
2807               /* Simplify branch over branch.  */
2808               if ((mode & CLEANUP_EXPENSIVE)
2809                    && !(mode & CLEANUP_CFGLAYOUT)
2810                    && try_simplify_condjump (b))
2811                 changed_here = true;
2812
2813               /* If B has a single outgoing edge, but uses a
2814                  non-trivial jump instruction without side-effects, we
2815                  can either delete the jump entirely, or replace it
2816                  with a simple unconditional jump.  */
2817               if (single_succ_p (b)
2818                   && single_succ (b) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2819                   && onlyjump_p (BB_END (b))
2820                   && !CROSSING_JUMP_P (BB_END (b))
2821                   && try_redirect_by_replacing_jump (single_succ_edge (b),
2822                                                      single_succ (b),
2823                                                      (mode & CLEANUP_CFGLAYOUT) != 0))
2824                 {
2825                   update_forwarder_flag (b);
2826                   changed_here = true;
2827                 }
2828
2829               /* Simplify branch to branch.  */
2830               if (try_forward_edges (mode, b))
2831                 {
2832                   update_forwarder_flag (b);
2833                   changed_here = true;
2834                 }
2835
2836               /* Look for shared code between blocks.  */
2837               if ((mode & CLEANUP_CROSSJUMP)
2838                   && try_crossjump_bb (mode, b))
2839                 changed_here = true;
2840
2841               if ((mode & CLEANUP_CROSSJUMP)
2842                   /* This can lengthen register lifetimes.  Do it only after
2843                      reload.  */
2844                   && reload_completed
2845                   && try_head_merge_bb (b))
2846                 changed_here = true;
2847
2848               /* Don't get confused by the index shift caused by
2849                  deleting blocks.  */
2850               if (!changed_here)
2851                 b = b->next_bb;
2852               else
2853                 changed = true;
2854             }
2855
2856           if ((mode & CLEANUP_CROSSJUMP)
2857               && try_crossjump_bb (mode, EXIT_BLOCK_PTR_FOR_FN (cfun)))
2858             changed = true;
2859
2860           if (block_was_dirty)
2861             {
2862               /* This should only be set by head-merging.  */
2863               gcc_assert (mode & CLEANUP_CROSSJUMP);
2864               df_analyze ();
2865             }
2866
2867           if (changed)
2868             {
2869               /* Edge forwarding in particular can cause hot blocks previously
2870                  reached by both hot and cold blocks to become dominated only
2871                  by cold blocks. This will cause the verification below to fail,
2872                  and lead to now cold code in the hot section. This is not easy
2873                  to detect and fix during edge forwarding, and in some cases
2874                  is only visible after newly unreachable blocks are deleted,
2875                  which will be done in fixup_partitions.  */
2876               fixup_partitions ();
2877               checking_verify_flow_info ();
2878             }
2879
2880           changed_overall |= changed;
2881           first_pass = false;
2882         }
2883       while (changed);
2884     }
2885
2886   FOR_ALL_BB_FN (b, cfun)
2887     b->flags &= ~(BB_FORWARDER_BLOCK | BB_NONTHREADABLE_BLOCK);
2888
2889   return changed_overall;
2890 }
2891 \f
2892 /* Delete all unreachable basic blocks.  */
2893
2894 bool
2895 delete_unreachable_blocks (void)
2896 {
2897   bool changed = false;
2898   basic_block b, prev_bb;
2899
2900   find_unreachable_blocks ();
2901
2902   /* When we're in GIMPLE mode and there may be debug insns, we should
2903      delete blocks in reverse dominator order, so as to get a chance
2904      to substitute all released DEFs into debug stmts.  If we don't
2905      have dominators information, walking blocks backward gets us a
2906      better chance of retaining most debug information than
2907      otherwise.  */
2908   if (MAY_HAVE_DEBUG_INSNS && current_ir_type () == IR_GIMPLE
2909       && dom_info_available_p (CDI_DOMINATORS))
2910     {
2911       for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2912            b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2913         {
2914           prev_bb = b->prev_bb;
2915
2916           if (!(b->flags & BB_REACHABLE))
2917             {
2918               /* Speed up the removal of blocks that don't dominate
2919                  others.  Walking backwards, this should be the common
2920                  case.  */
2921               if (!first_dom_son (CDI_DOMINATORS, b))
2922                 delete_basic_block (b);
2923               else
2924                 {
2925                   vec<basic_block> h
2926                     = get_all_dominated_blocks (CDI_DOMINATORS, b);
2927
2928                   while (h.length ())
2929                     {
2930                       b = h.pop ();
2931
2932                       prev_bb = b->prev_bb;
2933
2934                       gcc_assert (!(b->flags & BB_REACHABLE));
2935
2936                       delete_basic_block (b);
2937                     }
2938
2939                   h.release ();
2940                 }
2941
2942               changed = true;
2943             }
2944         }
2945     }
2946   else
2947     {
2948       for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2949            b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2950         {
2951           prev_bb = b->prev_bb;
2952
2953           if (!(b->flags & BB_REACHABLE))
2954             {
2955               delete_basic_block (b);
2956               changed = true;
2957             }
2958         }
2959     }
2960
2961   if (changed)
2962     tidy_fallthru_edges ();
2963   return changed;
2964 }
2965
2966 /* Delete any jump tables never referenced.  We can't delete them at the
2967    time of removing tablejump insn as they are referenced by the preceding
2968    insns computing the destination, so we delay deleting and garbagecollect
2969    them once life information is computed.  */
2970 void
2971 delete_dead_jumptables (void)
2972 {
2973   basic_block bb;
2974
2975   /* A dead jump table does not belong to any basic block.  Scan insns
2976      between two adjacent basic blocks.  */
2977   FOR_EACH_BB_FN (bb, cfun)
2978     {
2979       rtx_insn *insn, *next;
2980
2981       for (insn = NEXT_INSN (BB_END (bb));
2982            insn && !NOTE_INSN_BASIC_BLOCK_P (insn);
2983            insn = next)
2984         {
2985           next = NEXT_INSN (insn);
2986           if (LABEL_P (insn)
2987               && LABEL_NUSES (insn) == LABEL_PRESERVE_P (insn)
2988               && JUMP_TABLE_DATA_P (next))
2989             {
2990               rtx_insn *label = insn, *jump = next;
2991
2992               if (dump_file)
2993                 fprintf (dump_file, "Dead jumptable %i removed\n",
2994                          INSN_UID (insn));
2995
2996               next = NEXT_INSN (next);
2997               delete_insn (jump);
2998               delete_insn (label);
2999             }
3000         }
3001     }
3002 }
3003
3004 \f
3005 /* Tidy the CFG by deleting unreachable code and whatnot.  */
3006
3007 bool
3008 cleanup_cfg (int mode)
3009 {
3010   bool changed = false;
3011
3012   /* Set the cfglayout mode flag here.  We could update all the callers
3013      but that is just inconvenient, especially given that we eventually
3014      want to have cfglayout mode as the default.  */
3015   if (current_ir_type () == IR_RTL_CFGLAYOUT)
3016     mode |= CLEANUP_CFGLAYOUT;
3017
3018   timevar_push (TV_CLEANUP_CFG);
3019   if (delete_unreachable_blocks ())
3020     {
3021       changed = true;
3022       /* We've possibly created trivially dead code.  Cleanup it right
3023          now to introduce more opportunities for try_optimize_cfg.  */
3024       if (!(mode & (CLEANUP_NO_INSN_DEL))
3025           && !reload_completed)
3026         delete_trivially_dead_insns (get_insns (), max_reg_num ());
3027     }
3028
3029   compact_blocks ();
3030
3031   /* To tail-merge blocks ending in the same noreturn function (e.g.
3032      a call to abort) we have to insert fake edges to exit.  Do this
3033      here once.  The fake edges do not interfere with any other CFG
3034      cleanups.  */
3035   if (mode & CLEANUP_CROSSJUMP)
3036     add_noreturn_fake_exit_edges ();
3037
3038   if (!dbg_cnt (cfg_cleanup))
3039     return changed;
3040
3041   while (try_optimize_cfg (mode))
3042     {
3043       delete_unreachable_blocks (), changed = true;
3044       if (!(mode & CLEANUP_NO_INSN_DEL))
3045         {
3046           /* Try to remove some trivially dead insns when doing an expensive
3047              cleanup.  But delete_trivially_dead_insns doesn't work after
3048              reload (it only handles pseudos) and run_fast_dce is too costly
3049              to run in every iteration.
3050
3051              For effective cross jumping, we really want to run a fast DCE to
3052              clean up any dead conditions, or they get in the way of performing
3053              useful tail merges.
3054
3055              Other transformations in cleanup_cfg are not so sensitive to dead
3056              code, so delete_trivially_dead_insns or even doing nothing at all
3057              is good enough.  */
3058           if ((mode & CLEANUP_EXPENSIVE) && !reload_completed
3059               && !delete_trivially_dead_insns (get_insns (), max_reg_num ()))
3060             break;
3061           if ((mode & CLEANUP_CROSSJUMP) && crossjumps_occured)
3062             run_fast_dce ();
3063         }
3064       else
3065         break;
3066     }
3067
3068   if (mode & CLEANUP_CROSSJUMP)
3069     remove_fake_exit_edges ();
3070
3071   /* Don't call delete_dead_jumptables in cfglayout mode, because
3072      that function assumes that jump tables are in the insns stream.
3073      But we also don't _have_ to delete dead jumptables in cfglayout
3074      mode because we shouldn't even be looking at things that are
3075      not in a basic block.  Dead jumptables are cleaned up when
3076      going out of cfglayout mode.  */
3077   if (!(mode & CLEANUP_CFGLAYOUT))
3078     delete_dead_jumptables ();
3079
3080   /* ???  We probably do this way too often.  */
3081   if (current_loops
3082       && (changed
3083           || (mode & CLEANUP_CFG_CHANGED)))
3084     {
3085       timevar_push (TV_REPAIR_LOOPS);
3086       /* The above doesn't preserve dominance info if available.  */
3087       gcc_assert (!dom_info_available_p (CDI_DOMINATORS));
3088       calculate_dominance_info (CDI_DOMINATORS);
3089       fix_loop_structure (NULL);
3090       free_dominance_info (CDI_DOMINATORS);
3091       timevar_pop (TV_REPAIR_LOOPS);
3092     }
3093
3094   timevar_pop (TV_CLEANUP_CFG);
3095
3096   return changed;
3097 }
3098 \f
3099 namespace {
3100
3101 const pass_data pass_data_jump =
3102 {
3103   RTL_PASS, /* type */
3104   "jump", /* name */
3105   OPTGROUP_NONE, /* optinfo_flags */
3106   TV_JUMP, /* tv_id */
3107   0, /* properties_required */
3108   0, /* properties_provided */
3109   0, /* properties_destroyed */
3110   0, /* todo_flags_start */
3111   0, /* todo_flags_finish */
3112 };
3113
3114 class pass_jump : public rtl_opt_pass
3115 {
3116 public:
3117   pass_jump (gcc::context *ctxt)
3118     : rtl_opt_pass (pass_data_jump, ctxt)
3119   {}
3120
3121   /* opt_pass methods: */
3122   virtual unsigned int execute (function *);
3123
3124 }; // class pass_jump
3125
3126 unsigned int
3127 pass_jump::execute (function *)
3128 {
3129   delete_trivially_dead_insns (get_insns (), max_reg_num ());
3130   if (dump_file)
3131     dump_flow_info (dump_file, dump_flags);
3132   cleanup_cfg ((optimize ? CLEANUP_EXPENSIVE : 0)
3133                | (flag_thread_jumps ? CLEANUP_THREADING : 0));
3134   return 0;
3135 }
3136
3137 } // anon namespace
3138
3139 rtl_opt_pass *
3140 make_pass_jump (gcc::context *ctxt)
3141 {
3142   return new pass_jump (ctxt);
3143 }
3144 \f
3145 namespace {
3146
3147 const pass_data pass_data_jump2 =
3148 {
3149   RTL_PASS, /* type */
3150   "jump2", /* name */
3151   OPTGROUP_NONE, /* optinfo_flags */
3152   TV_JUMP, /* tv_id */
3153   0, /* properties_required */
3154   0, /* properties_provided */
3155   0, /* properties_destroyed */
3156   0, /* todo_flags_start */
3157   0, /* todo_flags_finish */
3158 };
3159
3160 class pass_jump2 : public rtl_opt_pass
3161 {
3162 public:
3163   pass_jump2 (gcc::context *ctxt)
3164     : rtl_opt_pass (pass_data_jump2, ctxt)
3165   {}
3166
3167   /* opt_pass methods: */
3168   virtual unsigned int execute (function *)
3169     {
3170       cleanup_cfg (flag_crossjumping ? CLEANUP_CROSSJUMP : 0);
3171       return 0;
3172     }
3173
3174 }; // class pass_jump2
3175
3176 } // anon namespace
3177
3178 rtl_opt_pass *
3179 make_pass_jump2 (gcc::context *ctxt)
3180 {
3181   return new pass_jump2 (ctxt);
3182 }