OSDN Git Service

* cfgcleanup.c (try_simplify_condjump): Fix my previous patch.
[pf3gnuchains/gcc-fork.git] / gcc / cfgcleanup.c
1 /* Control flow optimization code for GNU compiler.
2    Copyright (C) 1987, 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 /* This file contains optimizer of the control flow.  The main entrypoint is
23    cleanup_cfg.  Following optimizations are performed:
24
25    - Unreachable blocks removal
26    - Edge forwarding (edge to the forwarder block is forwarded to it's
27      successor.  Simplification of the branch instruction is performed by
28      underlying infrastructure so branch can be converted to simplejump or
29      eliminated).
30    - Cross jumping (tail merging)
31    - Conditional jump-around-simplejump simplification
32    - Basic block merging.  */
33
34 #include "config.h"
35 #include "system.h"
36 #include "coretypes.h"
37 #include "tm.h"
38 #include "rtl.h"
39 #include "hard-reg-set.h"
40 #include "basic-block.h"
41 #include "timevar.h"
42 #include "output.h"
43 #include "insn-config.h"
44 #include "flags.h"
45 #include "recog.h"
46 #include "toplev.h"
47 #include "cselib.h"
48 #include "params.h"
49 #include "tm_p.h"
50 #include "target.h"
51
52 /* cleanup_cfg maintains following flags for each basic block.  */
53
54 enum bb_flags
55 {
56     /* Set if BB is the forwarder block to avoid too many
57        forwarder_block_p calls.  */
58     BB_FORWARDER_BLOCK = 1,
59     BB_NONTHREADABLE_BLOCK = 2
60 };
61
62 #define BB_FLAGS(BB) (enum bb_flags) (BB)->aux
63 #define BB_SET_FLAG(BB, FLAG) \
64   (BB)->aux = (void *) (long) ((enum bb_flags) (BB)->aux | (FLAG))
65 #define BB_CLEAR_FLAG(BB, FLAG) \
66   (BB)->aux = (void *) (long) ((enum bb_flags) (BB)->aux & ~(FLAG))
67
68 #define FORWARDER_BLOCK_P(BB) (BB_FLAGS (BB) & BB_FORWARDER_BLOCK)
69
70 static bool try_crossjump_to_edge (int, edge, edge);
71 static bool try_crossjump_bb (int, basic_block);
72 static bool outgoing_edges_match (int, basic_block, basic_block);
73 static int flow_find_cross_jump (int, basic_block, basic_block, rtx *, rtx *);
74 static bool insns_match_p (int, rtx, rtx);
75
76 static bool label_is_jump_target_p (rtx, rtx);
77 static bool tail_recursion_label_p (rtx);
78 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
79 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
80 static bool try_optimize_cfg (int);
81 static bool try_simplify_condjump (basic_block);
82 static bool try_forward_edges (int, basic_block);
83 static edge thread_jump (int, edge, basic_block);
84 static bool mark_effect (rtx, bitmap);
85 static void notice_new_block (basic_block);
86 static void update_forwarder_flag (basic_block);
87 static int mentions_nonequal_regs (rtx *, void *);
88 \f
89 /* Set flags for newly created block.  */
90
91 static void
92 notice_new_block (basic_block bb)
93 {
94   if (!bb)
95     return;
96
97   if (forwarder_block_p (bb))
98     BB_SET_FLAG (bb, BB_FORWARDER_BLOCK);
99 }
100
101 /* Recompute forwarder flag after block has been modified.  */
102
103 static void
104 update_forwarder_flag (basic_block bb)
105 {
106   if (forwarder_block_p (bb))
107     BB_SET_FLAG (bb, BB_FORWARDER_BLOCK);
108   else
109     BB_CLEAR_FLAG (bb, BB_FORWARDER_BLOCK);
110 }
111 \f
112 /* Simplify a conditional jump around an unconditional jump.
113    Return true if something changed.  */
114
115 static bool
116 try_simplify_condjump (basic_block cbranch_block)
117 {
118   basic_block jump_block, jump_dest_block, cbranch_dest_block;
119   edge cbranch_jump_edge, cbranch_fallthru_edge;
120   rtx cbranch_insn;
121   rtx insn, next;
122   rtx end;
123
124   /* Verify that there are exactly two successors.  */
125   if (!cbranch_block->succ
126       || !cbranch_block->succ->succ_next
127       || cbranch_block->succ->succ_next->succ_next)
128     return false;
129
130   /* Verify that we've got a normal conditional branch at the end
131      of the block.  */
132   cbranch_insn = cbranch_block->end;
133   if (!any_condjump_p (cbranch_insn))
134     return false;
135
136   cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
137   cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
138
139   /* The next block must not have multiple predecessors, must not
140      be the last block in the function, and must contain just the
141      unconditional jump.  */
142   jump_block = cbranch_fallthru_edge->dest;
143   if (jump_block->pred->pred_next
144       || jump_block->next_bb == EXIT_BLOCK_PTR
145       || !FORWARDER_BLOCK_P (jump_block))
146     return false;
147   jump_dest_block = jump_block->succ->dest;
148
149   /* The conditional branch must target the block after the
150      unconditional branch.  */
151   cbranch_dest_block = cbranch_jump_edge->dest;
152
153   if (!can_fallthru (jump_block, cbranch_dest_block))
154     return false;
155
156   /* Invert the conditional branch.  */
157   if (!invert_jump (cbranch_insn, block_label (jump_dest_block), 0))
158     return false;
159
160   if (rtl_dump_file)
161     fprintf (rtl_dump_file, "Simplifying condjump %i around jump %i\n",
162              INSN_UID (cbranch_insn), INSN_UID (jump_block->end));
163
164   /* Success.  Update the CFG to match.  Note that after this point
165      the edge variable names appear backwards; the redirection is done
166      this way to preserve edge profile data.  */
167   cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
168                                                 cbranch_dest_block);
169   cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
170                                                     jump_dest_block);
171   cbranch_jump_edge->flags |= EDGE_FALLTHRU;
172   cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
173   update_br_prob_note (cbranch_block);
174
175   end = jump_block->end;
176   /* Deleting a block may produce unreachable code warning even when we are
177      not deleting anything live.  Supress it by moving all the line number
178      notes out of the block.  */
179   for (insn = jump_block->head; insn != NEXT_INSN (jump_block->end);
180        insn = next)
181     {
182       next = NEXT_INSN (insn);
183       if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
184         {
185           if (insn == end)
186             {
187               jump_block->end = PREV_INSN (insn);
188               if (jump_block->end == end)
189                 break;
190             }
191           reorder_insns_nobb (insn, insn, end);
192           end = insn;
193         }
194     }
195   /* Delete the block with the unconditional jump, and clean up the mess.  */
196   delete_block (jump_block);
197   tidy_fallthru_edge (cbranch_jump_edge, cbranch_block, cbranch_dest_block);
198
199   return true;
200 }
201 \f
202 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
203    on register.  Used by jump threading.  */
204
205 static bool
206 mark_effect (rtx exp, regset nonequal)
207 {
208   int regno;
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       if (REG_P (XEXP (exp, 0)))
216         {
217           dest = XEXP (exp, 0);
218           regno = REGNO (dest);
219           CLEAR_REGNO_REG_SET (nonequal, regno);
220           if (regno < FIRST_PSEUDO_REGISTER)
221             {
222               int n = HARD_REGNO_NREGS (regno, GET_MODE (dest));
223               while (--n > 0)
224                 CLEAR_REGNO_REG_SET (nonequal, regno + n);
225             }
226         }
227       return false;
228
229     case SET:
230       if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
231         return false;
232       dest = SET_DEST (exp);
233       if (dest == pc_rtx)
234         return false;
235       if (!REG_P (dest))
236         return true;
237       regno = REGNO (dest);
238       SET_REGNO_REG_SET (nonequal, regno);
239       if (regno < FIRST_PSEUDO_REGISTER)
240         {
241           int n = HARD_REGNO_NREGS (regno, GET_MODE (dest));
242           while (--n > 0)
243             SET_REGNO_REG_SET (nonequal, regno + n);
244         }
245       return false;
246
247     default:
248       return false;
249     }
250 }
251
252 /* Return nonzero if X is a register set in regset DATA.
253    Called via for_each_rtx.  */
254 static int
255 mentions_nonequal_regs (rtx *x, void *data)
256 {
257   regset nonequal = (regset) data;
258   if (REG_P (*x))
259     {
260       int regno;
261
262       regno = REGNO (*x);
263       if (REGNO_REG_SET_P (nonequal, regno))
264         return 1;
265       if (regno < FIRST_PSEUDO_REGISTER)
266         {
267           int n = HARD_REGNO_NREGS (regno, GET_MODE (*x));
268           while (--n > 0)
269             if (REGNO_REG_SET_P (nonequal, regno + n))
270               return 1;
271         }
272     }
273   return 0;
274 }
275 /* Attempt to prove that the basic block B will have no side effects and
276    always continues in the same edge if reached via E.  Return the edge
277    if exist, NULL otherwise.  */
278
279 static edge
280 thread_jump (int mode, edge e, basic_block b)
281 {
282   rtx set1, set2, cond1, cond2, insn;
283   enum rtx_code code1, code2, reversed_code2;
284   bool reverse1 = false;
285   int i;
286   regset nonequal;
287   bool failed = false;
288
289   if (BB_FLAGS (b) & BB_NONTHREADABLE_BLOCK)
290     return NULL;
291
292   /* At the moment, we do handle only conditional jumps, but later we may
293      want to extend this code to tablejumps and others.  */
294   if (!e->src->succ->succ_next || e->src->succ->succ_next->succ_next)
295     return NULL;
296   if (!b->succ || !b->succ->succ_next || b->succ->succ_next->succ_next)
297     {
298       BB_SET_FLAG (b, BB_NONTHREADABLE_BLOCK);
299       return NULL;
300     }
301
302   /* Second branch must end with onlyjump, as we will eliminate the jump.  */
303   if (!any_condjump_p (e->src->end))
304     return NULL;
305
306   if (!any_condjump_p (b->end) || !onlyjump_p (b->end))
307     {
308       BB_SET_FLAG (b, BB_NONTHREADABLE_BLOCK);
309       return NULL;
310     }
311
312   set1 = pc_set (e->src->end);
313   set2 = pc_set (b->end);
314   if (((e->flags & EDGE_FALLTHRU) != 0)
315       != (XEXP (SET_SRC (set1), 1) == pc_rtx))
316     reverse1 = true;
317
318   cond1 = XEXP (SET_SRC (set1), 0);
319   cond2 = XEXP (SET_SRC (set2), 0);
320   if (reverse1)
321     code1 = reversed_comparison_code (cond1, e->src->end);
322   else
323     code1 = GET_CODE (cond1);
324
325   code2 = GET_CODE (cond2);
326   reversed_code2 = reversed_comparison_code (cond2, b->end);
327
328   if (!comparison_dominates_p (code1, code2)
329       && !comparison_dominates_p (code1, reversed_code2))
330     return NULL;
331
332   /* Ensure that the comparison operators are equivalent.
333      ??? This is far too pessimistic.  We should allow swapped operands,
334      different CCmodes, or for example comparisons for interval, that
335      dominate even when operands are not equivalent.  */
336   if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
337       || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
338     return NULL;
339
340   /* Short circuit cases where block B contains some side effects, as we can't
341      safely bypass it.  */
342   for (insn = NEXT_INSN (b->head); insn != NEXT_INSN (b->end);
343        insn = NEXT_INSN (insn))
344     if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
345       {
346         BB_SET_FLAG (b, BB_NONTHREADABLE_BLOCK);
347         return NULL;
348       }
349
350   cselib_init ();
351
352   /* First process all values computed in the source basic block.  */
353   for (insn = NEXT_INSN (e->src->head); insn != NEXT_INSN (e->src->end);
354        insn = NEXT_INSN (insn))
355     if (INSN_P (insn))
356       cselib_process_insn (insn);
357
358   nonequal = BITMAP_XMALLOC();
359   CLEAR_REG_SET (nonequal);
360
361   /* Now assume that we've continued by the edge E to B and continue
362      processing as if it were same basic block.
363      Our goal is to prove that whole block is an NOOP.  */
364
365   for (insn = NEXT_INSN (b->head); insn != NEXT_INSN (b->end) && !failed;
366        insn = NEXT_INSN (insn))
367     {
368       if (INSN_P (insn))
369         {
370           rtx pat = PATTERN (insn);
371
372           if (GET_CODE (pat) == PARALLEL)
373             {
374               for (i = 0; i < XVECLEN (pat, 0); i++)
375                 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
376             }
377           else
378             failed |= mark_effect (pat, nonequal);
379         }
380
381       cselib_process_insn (insn);
382     }
383
384   /* Later we should clear nonequal of dead registers.  So far we don't
385      have life information in cfg_cleanup.  */
386   if (failed)
387     {
388       BB_SET_FLAG (b, BB_NONTHREADABLE_BLOCK);
389       goto failed_exit;
390     }
391
392   /* cond2 must not mention any register that is not equal to the
393      former block.  */
394   if (for_each_rtx (&cond2, mentions_nonequal_regs, nonequal))
395     goto failed_exit;
396
397   /* In case liveness information is available, we need to prove equivalence
398      only of the live values.  */
399   if (mode & CLEANUP_UPDATE_LIFE)
400     AND_REG_SET (nonequal, b->global_live_at_end);
401
402   EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, goto failed_exit;);
403
404   BITMAP_XFREE (nonequal);
405   cselib_finish ();
406   if ((comparison_dominates_p (code1, code2) != 0)
407       != (XEXP (SET_SRC (set2), 1) == pc_rtx))
408     return BRANCH_EDGE (b);
409   else
410     return FALLTHRU_EDGE (b);
411
412 failed_exit:
413   BITMAP_XFREE (nonequal);
414   cselib_finish ();
415   return NULL;
416 }
417 \f
418 /* Attempt to forward edges leaving basic block B.
419    Return true if successful.  */
420
421 static bool
422 try_forward_edges (int mode, basic_block b)
423 {
424   bool changed = false;
425   edge e, next, *threaded_edges = NULL;
426
427   for (e = b->succ; e; e = next)
428     {
429       basic_block target, first;
430       int counter;
431       bool threaded = false;
432       int nthreaded_edges = 0;
433
434       next = e->succ_next;
435
436       /* Skip complex edges because we don't know how to update them.
437
438          Still handle fallthru edges, as we can succeed to forward fallthru
439          edge to the same place as the branch edge of conditional branch
440          and turn conditional branch to an unconditional branch.  */
441       if (e->flags & EDGE_COMPLEX)
442         continue;
443
444       target = first = e->dest;
445       counter = 0;
446
447       while (counter < n_basic_blocks)
448         {
449           basic_block new_target = NULL;
450           bool new_target_threaded = false;
451
452           if (FORWARDER_BLOCK_P (target)
453               && target->succ->dest != EXIT_BLOCK_PTR)
454             {
455               /* Bypass trivial infinite loops.  */
456               if (target == target->succ->dest)
457                 counter = n_basic_blocks;
458               new_target = target->succ->dest;
459             }
460
461           /* Allow to thread only over one edge at time to simplify updating
462              of probabilities.  */
463           else if (mode & CLEANUP_THREADING)
464             {
465               edge t = thread_jump (mode, e, target);
466               if (t)
467                 {
468                   if (!threaded_edges)
469                     threaded_edges = xmalloc (sizeof (*threaded_edges)
470                                               * n_basic_blocks);
471                   else
472                     {
473                       int i;
474
475                       /* Detect an infinite loop across blocks not
476                          including the start block.  */
477                       for (i = 0; i < nthreaded_edges; ++i)
478                         if (threaded_edges[i] == t)
479                           break;
480                       if (i < nthreaded_edges)
481                         {
482                           counter = n_basic_blocks;
483                           break;
484                         }
485                     }
486
487                   /* Detect an infinite loop across the start block.  */
488                   if (t->dest == b)
489                     break;
490
491                   if (nthreaded_edges >= n_basic_blocks)
492                     abort ();
493                   threaded_edges[nthreaded_edges++] = t;
494
495                   new_target = t->dest;
496                   new_target_threaded = true;
497                 }
498             }
499
500           if (!new_target)
501             break;
502
503           /* Avoid killing of loop pre-headers, as it is the place loop
504              optimizer wants to hoist code to.
505
506              For fallthru forwarders, the LOOP_BEG note must appear between
507              the header of block and CODE_LABEL of the loop, for non forwarders
508              it must appear before the JUMP_INSN.  */
509           if ((mode & CLEANUP_PRE_LOOP) && optimize)
510             {
511               rtx insn = (target->succ->flags & EDGE_FALLTHRU
512                           ? target->head : prev_nonnote_insn (target->end));
513
514               if (GET_CODE (insn) != NOTE)
515                 insn = NEXT_INSN (insn);
516
517               for (; insn && GET_CODE (insn) != CODE_LABEL && !INSN_P (insn);
518                    insn = NEXT_INSN (insn))
519                 if (GET_CODE (insn) == NOTE
520                     && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
521                   break;
522
523               if (GET_CODE (insn) == NOTE)
524                 break;
525
526               /* Do not clean up branches to just past the end of a loop
527                  at this time; it can mess up the loop optimizer's
528                  recognition of some patterns.  */
529
530               insn = PREV_INSN (target->head);
531               if (insn && GET_CODE (insn) == NOTE
532                     && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
533                 break;
534             }
535
536           counter++;
537           target = new_target;
538           threaded |= new_target_threaded;
539         }
540
541       if (counter >= n_basic_blocks)
542         {
543           if (rtl_dump_file)
544             fprintf (rtl_dump_file, "Infinite loop in BB %i.\n",
545                      target->index);
546         }
547       else if (target == first)
548         ; /* We didn't do anything.  */
549       else
550         {
551           /* Save the values now, as the edge may get removed.  */
552           gcov_type edge_count = e->count;
553           int edge_probability = e->probability;
554           int edge_frequency;
555           int n = 0;
556
557           /* Don't force if target is exit block.  */
558           if (threaded && target != EXIT_BLOCK_PTR)
559             {
560               notice_new_block (redirect_edge_and_branch_force (e, target));
561               if (rtl_dump_file)
562                 fprintf (rtl_dump_file, "Conditionals threaded.\n");
563             }
564           else if (!redirect_edge_and_branch (e, target))
565             {
566               if (rtl_dump_file)
567                 fprintf (rtl_dump_file,
568                          "Forwarding edge %i->%i to %i failed.\n",
569                          b->index, e->dest->index, target->index);
570               continue;
571             }
572
573           /* We successfully forwarded the edge.  Now update profile
574              data: for each edge we traversed in the chain, remove
575              the original edge's execution count.  */
576           edge_frequency = ((edge_probability * b->frequency
577                              + REG_BR_PROB_BASE / 2)
578                             / REG_BR_PROB_BASE);
579
580           if (!FORWARDER_BLOCK_P (b) && forwarder_block_p (b))
581             BB_SET_FLAG (b, BB_FORWARDER_BLOCK);
582
583           do
584             {
585               edge t;
586
587               first->count -= edge_count;
588               if (first->count < 0)
589                 first->count = 0;
590               first->frequency -= edge_frequency;
591               if (first->frequency < 0)
592                 first->frequency = 0;
593               if (first->succ->succ_next)
594                 {
595                   edge e;
596                   int prob;
597                   if (n >= nthreaded_edges)
598                     abort ();
599                   t = threaded_edges [n++];
600                   if (t->src != first)
601                     abort ();
602                   if (first->frequency)
603                     prob = edge_frequency * REG_BR_PROB_BASE / first->frequency;
604                   else
605                     prob = 0;
606                   if (prob > t->probability)
607                     prob = t->probability;
608                   t->probability -= prob;
609                   prob = REG_BR_PROB_BASE - prob;
610                   if (prob <= 0)
611                     {
612                       first->succ->probability = REG_BR_PROB_BASE;
613                       first->succ->succ_next->probability = 0;
614                     }
615                   else
616                     for (e = first->succ; e; e = e->succ_next)
617                       e->probability = ((e->probability * REG_BR_PROB_BASE)
618                                         / (double) prob);
619                   update_br_prob_note (first);
620                 }
621               else
622                 {
623                   /* It is possible that as the result of
624                      threading we've removed edge as it is
625                      threaded to the fallthru edge.  Avoid
626                      getting out of sync.  */
627                   if (n < nthreaded_edges
628                       && first == threaded_edges [n]->src)
629                     n++;
630                   t = first->succ;
631                 }
632
633               t->count -= edge_count;
634               if (t->count < 0)
635                 t->count = 0;
636               first = t->dest;
637             }
638           while (first != target);
639
640           changed = true;
641         }
642     }
643
644   if (threaded_edges)
645     free (threaded_edges);
646   return changed;
647 }
648 \f
649 /* Return true if LABEL is a target of JUMP_INSN.  This applies only
650    to non-complex jumps.  That is, direct unconditional, conditional,
651    and tablejumps, but not computed jumps or returns.  It also does
652    not apply to the fallthru case of a conditional jump.  */
653
654 static bool
655 label_is_jump_target_p (rtx label, rtx jump_insn)
656 {
657   rtx tmp = JUMP_LABEL (jump_insn);
658
659   if (label == tmp)
660     return true;
661
662   if (tablejump_p (jump_insn, NULL, &tmp))
663     {
664       rtvec vec = XVEC (tmp, GET_CODE (tmp) == ADDR_DIFF_VEC);
665       int i, veclen = GET_NUM_ELEM (vec);
666
667       for (i = 0; i < veclen; ++i)
668         if (XEXP (RTVEC_ELT (vec, i), 0) == label)
669           return true;
670     }
671
672   return false;
673 }
674
675 /* Return true if LABEL is used for tail recursion.  */
676
677 static bool
678 tail_recursion_label_p (rtx label)
679 {
680   rtx x;
681
682   for (x = tail_recursion_label_list; x; x = XEXP (x, 1))
683     if (label == XEXP (x, 0))
684       return true;
685
686   return false;
687 }
688
689 /* Blocks A and B are to be merged into a single block.  A has no incoming
690    fallthru edge, so it can be moved before B without adding or modifying
691    any jumps (aside from the jump from A to B).  */
692
693 static void
694 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
695 {
696   rtx barrier;
697
698   barrier = next_nonnote_insn (a->end);
699   if (GET_CODE (barrier) != BARRIER)
700     abort ();
701   delete_insn (barrier);
702
703   /* Move block and loop notes out of the chain so that we do not
704      disturb their order.
705
706      ??? A better solution would be to squeeze out all the non-nested notes
707      and adjust the block trees appropriately.   Even better would be to have
708      a tighter connection between block trees and rtl so that this is not
709      necessary.  */
710   if (squeeze_notes (&a->head, &a->end))
711     abort ();
712
713   /* Scramble the insn chain.  */
714   if (a->end != PREV_INSN (b->head))
715     reorder_insns_nobb (a->head, a->end, PREV_INSN (b->head));
716   a->flags |= BB_DIRTY;
717
718   if (rtl_dump_file)
719     fprintf (rtl_dump_file, "Moved block %d before %d and merged.\n",
720              a->index, b->index);
721
722   /* Swap the records for the two blocks around.  */
723
724   unlink_block (a);
725   link_block (a, b->prev_bb);
726
727   /* Now blocks A and B are contiguous.  Merge them.  */
728   merge_blocks (a, b);
729 }
730
731 /* Blocks A and B are to be merged into a single block.  B has no outgoing
732    fallthru edge, so it can be moved after A without adding or modifying
733    any jumps (aside from the jump from A to B).  */
734
735 static void
736 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
737 {
738   rtx barrier, real_b_end;
739   rtx label, table;
740
741   real_b_end = b->end;
742
743   /* If there is a jump table following block B temporarily add the jump table
744      to block B so that it will also be moved to the correct location.  */
745   if (tablejump_p (b->end, &label, &table)
746       && prev_active_insn (label) == b->end)
747     {
748       b->end = table;
749     }
750
751   /* There had better have been a barrier there.  Delete it.  */
752   barrier = NEXT_INSN (b->end);
753   if (barrier && GET_CODE (barrier) == BARRIER)
754     delete_insn (barrier);
755
756   /* Move block and loop notes out of the chain so that we do not
757      disturb their order.
758
759      ??? A better solution would be to squeeze out all the non-nested notes
760      and adjust the block trees appropriately.   Even better would be to have
761      a tighter connection between block trees and rtl so that this is not
762      necessary.  */
763   if (squeeze_notes (&b->head, &b->end))
764     abort ();
765
766   /* Scramble the insn chain.  */
767   reorder_insns_nobb (b->head, b->end, a->end);
768
769   /* Restore the real end of b.  */
770   b->end = real_b_end;
771
772   if (rtl_dump_file)
773     fprintf (rtl_dump_file, "Moved block %d after %d and merged.\n",
774              b->index, a->index);
775
776   /* Now blocks A and B are contiguous.  Merge them.  */
777   merge_blocks (a, b);
778 }
779
780 /* Attempt to merge basic blocks that are potentially non-adjacent.
781    Return NULL iff the attempt failed, otherwise return basic block
782    where cleanup_cfg should continue.  Because the merging commonly
783    moves basic block away or introduces another optimization
784    possibility, return basic block just before B so cleanup_cfg don't
785    need to iterate.
786
787    It may be good idea to return basic block before C in the case
788    C has been moved after B and originally appeared earlier in the
789    insn sequence, but we have no information available about the
790    relative ordering of these two.  Hopefully it is not too common.  */
791
792 static basic_block
793 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
794 {
795   basic_block next;
796   /* If C has a tail recursion label, do not merge.  There is no
797      edge recorded from the call_placeholder back to this label, as
798      that would make optimize_sibling_and_tail_recursive_calls more
799      complex for no gain.  */
800   if ((mode & CLEANUP_PRE_SIBCALL)
801       && GET_CODE (c->head) == CODE_LABEL
802       && tail_recursion_label_p (c->head))
803     return NULL;
804
805   /* If B has a fallthru edge to C, no need to move anything.  */
806   if (e->flags & EDGE_FALLTHRU)
807     {
808       int b_index = b->index, c_index = c->index;
809       merge_blocks (b, c);
810       update_forwarder_flag (b);
811
812       if (rtl_dump_file)
813         fprintf (rtl_dump_file, "Merged %d and %d without moving.\n",
814                  b_index, c_index);
815
816       return b->prev_bb == ENTRY_BLOCK_PTR ? b : b->prev_bb;
817     }
818
819   /* Otherwise we will need to move code around.  Do that only if expensive
820      transformations are allowed.  */
821   else if (mode & CLEANUP_EXPENSIVE)
822     {
823       edge tmp_edge, b_fallthru_edge;
824       bool c_has_outgoing_fallthru;
825       bool b_has_incoming_fallthru;
826
827       /* Avoid overactive code motion, as the forwarder blocks should be
828          eliminated by edge redirection instead.  One exception might have
829          been if B is a forwarder block and C has no fallthru edge, but
830          that should be cleaned up by bb-reorder instead.  */
831       if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
832         return NULL;
833
834       /* We must make sure to not munge nesting of lexical blocks,
835          and loop notes.  This is done by squeezing out all the notes
836          and leaving them there to lie.  Not ideal, but functional.  */
837
838       for (tmp_edge = c->succ; tmp_edge; tmp_edge = tmp_edge->succ_next)
839         if (tmp_edge->flags & EDGE_FALLTHRU)
840           break;
841
842       c_has_outgoing_fallthru = (tmp_edge != NULL);
843
844       for (tmp_edge = b->pred; tmp_edge; tmp_edge = tmp_edge->pred_next)
845         if (tmp_edge->flags & EDGE_FALLTHRU)
846           break;
847
848       b_has_incoming_fallthru = (tmp_edge != NULL);
849       b_fallthru_edge = tmp_edge;
850       next = b->prev_bb;
851       if (next == c)
852         next = next->prev_bb;
853
854       /* Otherwise, we're going to try to move C after B.  If C does
855          not have an outgoing fallthru, then it can be moved
856          immediately after B without introducing or modifying jumps.  */
857       if (! c_has_outgoing_fallthru)
858         {
859           merge_blocks_move_successor_nojumps (b, c);
860           return next == ENTRY_BLOCK_PTR ? next->next_bb : next;
861         }
862
863       /* If B does not have an incoming fallthru, then it can be moved
864          immediately before C without introducing or modifying jumps.
865          C cannot be the first block, so we do not have to worry about
866          accessing a non-existent block.  */
867
868       if (b_has_incoming_fallthru)
869         {
870           basic_block bb;
871
872           if (b_fallthru_edge->src == ENTRY_BLOCK_PTR)
873             return NULL;
874           bb = force_nonfallthru (b_fallthru_edge);
875           if (bb)
876             notice_new_block (bb);
877         }
878
879       merge_blocks_move_predecessor_nojumps (b, c);
880       return next == ENTRY_BLOCK_PTR ? next->next_bb : next;
881     }
882
883   return NULL;
884 }
885 \f
886
887 /* Return true if I1 and I2 are equivalent and thus can be crossjumped.  */
888
889 static bool
890 insns_match_p (int mode ATTRIBUTE_UNUSED, rtx i1, rtx i2)
891 {
892   rtx p1, p2;
893
894   /* Verify that I1 and I2 are equivalent.  */
895   if (GET_CODE (i1) != GET_CODE (i2))
896     return false;
897
898   p1 = PATTERN (i1);
899   p2 = PATTERN (i2);
900
901   if (GET_CODE (p1) != GET_CODE (p2))
902     return false;
903
904   /* If this is a CALL_INSN, compare register usage information.
905      If we don't check this on stack register machines, the two
906      CALL_INSNs might be merged leaving reg-stack.c with mismatching
907      numbers of stack registers in the same basic block.
908      If we don't check this on machines with delay slots, a delay slot may
909      be filled that clobbers a parameter expected by the subroutine.
910
911      ??? We take the simple route for now and assume that if they're
912      equal, they were constructed identically.  */
913
914   if (GET_CODE (i1) == CALL_INSN
915       && (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
916                         CALL_INSN_FUNCTION_USAGE (i2))
917           || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2)))
918     return false;
919
920 #ifdef STACK_REGS
921   /* If cross_jump_death_matters is not 0, the insn's mode
922      indicates whether or not the insn contains any stack-like
923      regs.  */
924
925   if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
926     {
927       /* If register stack conversion has already been done, then
928          death notes must also be compared before it is certain that
929          the two instruction streams match.  */
930
931       rtx note;
932       HARD_REG_SET i1_regset, i2_regset;
933
934       CLEAR_HARD_REG_SET (i1_regset);
935       CLEAR_HARD_REG_SET (i2_regset);
936
937       for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
938         if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
939           SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
940
941       for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
942         if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
943           SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
944
945       GO_IF_HARD_REG_EQUAL (i1_regset, i2_regset, done);
946
947       return false;
948
949     done:
950       ;
951     }
952 #endif
953
954   if (reload_completed
955       ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
956     return true;
957
958   /* Do not do EQUIV substitution after reload.  First, we're undoing the
959      work of reload_cse.  Second, we may be undoing the work of the post-
960      reload splitting pass.  */
961   /* ??? Possibly add a new phase switch variable that can be used by
962      targets to disallow the troublesome insns after splitting.  */
963   if (!reload_completed)
964     {
965       /* The following code helps take care of G++ cleanups.  */
966       rtx equiv1 = find_reg_equal_equiv_note (i1);
967       rtx equiv2 = find_reg_equal_equiv_note (i2);
968
969       if (equiv1 && equiv2
970           /* If the equivalences are not to a constant, they may
971              reference pseudos that no longer exist, so we can't
972              use them.  */
973           && (! reload_completed
974               || (CONSTANT_P (XEXP (equiv1, 0))
975                   && rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))))
976         {
977           rtx s1 = single_set (i1);
978           rtx s2 = single_set (i2);
979           if (s1 != 0 && s2 != 0
980               && rtx_renumbered_equal_p (SET_DEST (s1), SET_DEST (s2)))
981             {
982               validate_change (i1, &SET_SRC (s1), XEXP (equiv1, 0), 1);
983               validate_change (i2, &SET_SRC (s2), XEXP (equiv2, 0), 1);
984               if (! rtx_renumbered_equal_p (p1, p2))
985                 cancel_changes (0);
986               else if (apply_change_group ())
987                 return true;
988             }
989         }
990     }
991
992   return false;
993 }
994 \f
995 /* Look through the insns at the end of BB1 and BB2 and find the longest
996    sequence that are equivalent.  Store the first insns for that sequence
997    in *F1 and *F2 and return the sequence length.
998
999    To simplify callers of this function, if the blocks match exactly,
1000    store the head of the blocks in *F1 and *F2.  */
1001
1002 static int
1003 flow_find_cross_jump (int mode ATTRIBUTE_UNUSED, basic_block bb1,
1004                       basic_block bb2, rtx *f1, rtx *f2)
1005 {
1006   rtx i1, i2, last1, last2, afterlast1, afterlast2;
1007   int ninsns = 0;
1008
1009   /* Skip simple jumps at the end of the blocks.  Complex jumps still
1010      need to be compared for equivalence, which we'll do below.  */
1011
1012   i1 = bb1->end;
1013   last1 = afterlast1 = last2 = afterlast2 = NULL_RTX;
1014   if (onlyjump_p (i1)
1015       || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1016     {
1017       last1 = i1;
1018       i1 = PREV_INSN (i1);
1019     }
1020
1021   i2 = bb2->end;
1022   if (onlyjump_p (i2)
1023       || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1024     {
1025       last2 = i2;
1026       /* Count everything except for unconditional jump as insn.  */
1027       if (!simplejump_p (i2) && !returnjump_p (i2) && last1)
1028         ninsns++;
1029       i2 = PREV_INSN (i2);
1030     }
1031
1032   while (true)
1033     {
1034       /* Ignore notes.  */
1035       while (!INSN_P (i1) && i1 != bb1->head)
1036         i1 = PREV_INSN (i1);
1037
1038       while (!INSN_P (i2) && i2 != bb2->head)
1039         i2 = PREV_INSN (i2);
1040
1041       if (i1 == bb1->head || i2 == bb2->head)
1042         break;
1043
1044       if (!insns_match_p (mode, i1, i2))
1045         break;
1046
1047       /* Don't begin a cross-jump with a NOTE insn.  */
1048       if (INSN_P (i1))
1049         {
1050           /* If the merged insns have different REG_EQUAL notes, then
1051              remove them.  */
1052           rtx equiv1 = find_reg_equal_equiv_note (i1);
1053           rtx equiv2 = find_reg_equal_equiv_note (i2);
1054
1055           if (equiv1 && !equiv2)
1056             remove_note (i1, equiv1);
1057           else if (!equiv1 && equiv2)
1058             remove_note (i2, equiv2);
1059           else if (equiv1 && equiv2
1060                    && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1061             {
1062               remove_note (i1, equiv1);
1063               remove_note (i2, equiv2);
1064             }
1065
1066           afterlast1 = last1, afterlast2 = last2;
1067           last1 = i1, last2 = i2;
1068           ninsns++;
1069         }
1070
1071       i1 = PREV_INSN (i1);
1072       i2 = PREV_INSN (i2);
1073     }
1074
1075 #ifdef HAVE_cc0
1076   /* Don't allow the insn after a compare to be shared by
1077      cross-jumping unless the compare is also shared.  */
1078   if (ninsns && reg_mentioned_p (cc0_rtx, last1) && ! sets_cc0_p (last1))
1079     last1 = afterlast1, last2 = afterlast2, ninsns--;
1080 #endif
1081
1082   /* Include preceding notes and labels in the cross-jump.  One,
1083      this may bring us to the head of the blocks as requested above.
1084      Two, it keeps line number notes as matched as may be.  */
1085   if (ninsns)
1086     {
1087       while (last1 != bb1->head && !INSN_P (PREV_INSN (last1)))
1088         last1 = PREV_INSN (last1);
1089
1090       if (last1 != bb1->head && GET_CODE (PREV_INSN (last1)) == CODE_LABEL)
1091         last1 = PREV_INSN (last1);
1092
1093       while (last2 != bb2->head && !INSN_P (PREV_INSN (last2)))
1094         last2 = PREV_INSN (last2);
1095
1096       if (last2 != bb2->head && GET_CODE (PREV_INSN (last2)) == CODE_LABEL)
1097         last2 = PREV_INSN (last2);
1098
1099       *f1 = last1;
1100       *f2 = last2;
1101     }
1102
1103   return ninsns;
1104 }
1105
1106 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1107    the branch instruction.  This means that if we commonize the control
1108    flow before end of the basic block, the semantic remains unchanged.
1109
1110    We may assume that there exists one edge with a common destination.  */
1111
1112 static bool
1113 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1114 {
1115   int nehedges1 = 0, nehedges2 = 0;
1116   edge fallthru1 = 0, fallthru2 = 0;
1117   edge e1, e2;
1118
1119   /* If BB1 has only one successor, we may be looking at either an
1120      unconditional jump, or a fake edge to exit.  */
1121   if (bb1->succ && !bb1->succ->succ_next
1122       && (bb1->succ->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1123       && (GET_CODE (bb1->end) != JUMP_INSN || simplejump_p (bb1->end)))
1124     return (bb2->succ &&  !bb2->succ->succ_next
1125             && (bb2->succ->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1126             && (GET_CODE (bb2->end) != JUMP_INSN || simplejump_p (bb2->end)));
1127
1128   /* Match conditional jumps - this may get tricky when fallthru and branch
1129      edges are crossed.  */
1130   if (bb1->succ
1131       && bb1->succ->succ_next
1132       && !bb1->succ->succ_next->succ_next
1133       && any_condjump_p (bb1->end)
1134       && onlyjump_p (bb1->end))
1135     {
1136       edge b1, f1, b2, f2;
1137       bool reverse, match;
1138       rtx set1, set2, cond1, cond2;
1139       enum rtx_code code1, code2;
1140
1141       if (!bb2->succ
1142           || !bb2->succ->succ_next
1143           || bb2->succ->succ_next->succ_next
1144           || !any_condjump_p (bb2->end)
1145           || !onlyjump_p (bb2->end))
1146         return false;
1147
1148       b1 = BRANCH_EDGE (bb1);
1149       b2 = BRANCH_EDGE (bb2);
1150       f1 = FALLTHRU_EDGE (bb1);
1151       f2 = FALLTHRU_EDGE (bb2);
1152
1153       /* Get around possible forwarders on fallthru edges.  Other cases
1154          should be optimized out already.  */
1155       if (FORWARDER_BLOCK_P (f1->dest))
1156         f1 = f1->dest->succ;
1157
1158       if (FORWARDER_BLOCK_P (f2->dest))
1159         f2 = f2->dest->succ;
1160
1161       /* To simplify use of this function, return false if there are
1162          unneeded forwarder blocks.  These will get eliminated later
1163          during cleanup_cfg.  */
1164       if (FORWARDER_BLOCK_P (f1->dest)
1165           || FORWARDER_BLOCK_P (f2->dest)
1166           || FORWARDER_BLOCK_P (b1->dest)
1167           || FORWARDER_BLOCK_P (b2->dest))
1168         return false;
1169
1170       if (f1->dest == f2->dest && b1->dest == b2->dest)
1171         reverse = false;
1172       else if (f1->dest == b2->dest && b1->dest == f2->dest)
1173         reverse = true;
1174       else
1175         return false;
1176
1177       set1 = pc_set (bb1->end);
1178       set2 = pc_set (bb2->end);
1179       if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1180           != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1181         reverse = !reverse;
1182
1183       cond1 = XEXP (SET_SRC (set1), 0);
1184       cond2 = XEXP (SET_SRC (set2), 0);
1185       code1 = GET_CODE (cond1);
1186       if (reverse)
1187         code2 = reversed_comparison_code (cond2, bb2->end);
1188       else
1189         code2 = GET_CODE (cond2);
1190
1191       if (code2 == UNKNOWN)
1192         return false;
1193
1194       /* Verify codes and operands match.  */
1195       match = ((code1 == code2
1196                 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1197                 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1198                || (code1 == swap_condition (code2)
1199                    && rtx_renumbered_equal_p (XEXP (cond1, 1),
1200                                               XEXP (cond2, 0))
1201                    && rtx_renumbered_equal_p (XEXP (cond1, 0),
1202                                               XEXP (cond2, 1))));
1203
1204       /* If we return true, we will join the blocks.  Which means that
1205          we will only have one branch prediction bit to work with.  Thus
1206          we require the existing branches to have probabilities that are
1207          roughly similar.  */
1208       if (match
1209           && !optimize_size
1210           && maybe_hot_bb_p (bb1)
1211           && maybe_hot_bb_p (bb2))
1212         {
1213           int prob2;
1214
1215           if (b1->dest == b2->dest)
1216             prob2 = b2->probability;
1217           else
1218             /* Do not use f2 probability as f2 may be forwarded.  */
1219             prob2 = REG_BR_PROB_BASE - b2->probability;
1220
1221           /* Fail if the difference in probabilities is greater than 50%.
1222              This rules out two well-predicted branches with opposite
1223              outcomes.  */
1224           if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1225             {
1226               if (rtl_dump_file)
1227                 fprintf (rtl_dump_file,
1228                          "Outcomes of branch in bb %i and %i differs to much (%i %i)\n",
1229                          bb1->index, bb2->index, b1->probability, prob2);
1230
1231               return false;
1232             }
1233         }
1234
1235       if (rtl_dump_file && match)
1236         fprintf (rtl_dump_file, "Conditionals in bb %i and %i match.\n",
1237                  bb1->index, bb2->index);
1238
1239       return match;
1240     }
1241
1242   /* Generic case - we are seeing a computed jump, table jump or trapping
1243      instruction.  */
1244
1245 #ifndef CASE_DROPS_THROUGH
1246   /* Check whether there are tablejumps in the end of BB1 and BB2.
1247      Return true if they are identical.  */
1248     {
1249       rtx label1, label2;
1250       rtx table1, table2;
1251
1252       if (tablejump_p (bb1->end, &label1, &table1)
1253           && tablejump_p (bb2->end, &label2, &table2)
1254           && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1255         {
1256           /* The labels should never be the same rtx.  If they really are same
1257              the jump tables are same too. So disable crossjumping of blocks BB1
1258              and BB2 because when deleting the common insns in the end of BB1
1259              by delete_block () the jump table would be deleted too.  */
1260           /* If LABEL2 is referenced in BB1->END do not do anything
1261              because we would loose information when replacing
1262              LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END.  */
1263           if (label1 != label2 && !rtx_referenced_p (label2, bb1->end))
1264             {
1265               /* Set IDENTICAL to true when the tables are identical.  */
1266               bool identical = false;
1267               rtx p1, p2;
1268
1269               p1 = PATTERN (table1);
1270               p2 = PATTERN (table2);
1271               if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1272                 {
1273                   identical = true;
1274                 }
1275               else if (GET_CODE (p1) == ADDR_DIFF_VEC
1276                        && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1277                        && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1278                        && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1279                 {
1280                   int i;
1281
1282                   identical = true;
1283                   for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1284                     if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1285                       identical = false;
1286                 }
1287
1288               if (identical)
1289                 {
1290                   replace_label_data rr;
1291                   bool match;
1292
1293                   /* Temporarily replace references to LABEL1 with LABEL2
1294                      in BB1->END so that we could compare the instructions.  */
1295                   rr.r1 = label1;
1296                   rr.r2 = label2;
1297                   rr.update_label_nuses = false;
1298                   for_each_rtx (&bb1->end, replace_label, &rr);
1299
1300                   match = insns_match_p (mode, bb1->end, bb2->end);
1301                   if (rtl_dump_file && match)
1302                     fprintf (rtl_dump_file,
1303                              "Tablejumps in bb %i and %i match.\n",
1304                              bb1->index, bb2->index);
1305
1306                   /* Set the original label in BB1->END because when deleting
1307                      a block whose end is a tablejump, the tablejump referenced
1308                      from the instruction is deleted too.  */
1309                   rr.r1 = label2;
1310                   rr.r2 = label1;
1311                   for_each_rtx (&bb1->end, replace_label, &rr);
1312
1313                   return match;
1314                 }
1315             }
1316           return false;
1317         }
1318     }
1319 #endif
1320
1321   /* First ensure that the instructions match.  There may be many outgoing
1322      edges so this test is generally cheaper.  */
1323   if (!insns_match_p (mode, bb1->end, bb2->end))
1324     return false;
1325
1326   /* Search the outgoing edges, ensure that the counts do match, find possible
1327      fallthru and exception handling edges since these needs more
1328      validation.  */
1329   for (e1 = bb1->succ, e2 = bb2->succ; e1 && e2;
1330        e1 = e1->succ_next, e2 = e2->succ_next)
1331     {
1332       if (e1->flags & EDGE_EH)
1333         nehedges1++;
1334
1335       if (e2->flags & EDGE_EH)
1336         nehedges2++;
1337
1338       if (e1->flags & EDGE_FALLTHRU)
1339         fallthru1 = e1;
1340       if (e2->flags & EDGE_FALLTHRU)
1341         fallthru2 = e2;
1342     }
1343
1344   /* If number of edges of various types does not match, fail.  */
1345   if (e1 || e2
1346       || nehedges1 != nehedges2
1347       || (fallthru1 != 0) != (fallthru2 != 0))
1348     return false;
1349
1350   /* fallthru edges must be forwarded to the same destination.  */
1351   if (fallthru1)
1352     {
1353       basic_block d1 = (forwarder_block_p (fallthru1->dest)
1354                         ? fallthru1->dest->succ->dest: fallthru1->dest);
1355       basic_block d2 = (forwarder_block_p (fallthru2->dest)
1356                         ? fallthru2->dest->succ->dest: fallthru2->dest);
1357
1358       if (d1 != d2)
1359         return false;
1360     }
1361
1362   /* Ensure the same EH region.  */
1363   {
1364     rtx n1 = find_reg_note (bb1->end, REG_EH_REGION, 0);
1365     rtx n2 = find_reg_note (bb2->end, REG_EH_REGION, 0);
1366
1367     if (!n1 && n2)
1368       return false;
1369
1370     if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1371       return false;
1372   }
1373
1374   /* We don't need to match the rest of edges as above checks should be enough
1375      to ensure that they are equivalent.  */
1376   return true;
1377 }
1378
1379 /* E1 and E2 are edges with the same destination block.  Search their
1380    predecessors for common code.  If found, redirect control flow from
1381    (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC.  */
1382
1383 static bool
1384 try_crossjump_to_edge (int mode, edge e1, edge e2)
1385 {
1386   int nmatch;
1387   basic_block src1 = e1->src, src2 = e2->src;
1388   basic_block redirect_to, redirect_from, to_remove;
1389   rtx newpos1, newpos2;
1390   edge s;
1391
1392   /* Search backward through forwarder blocks.  We don't need to worry
1393      about multiple entry or chained forwarders, as they will be optimized
1394      away.  We do this to look past the unconditional jump following a
1395      conditional jump that is required due to the current CFG shape.  */
1396   if (src1->pred
1397       && !src1->pred->pred_next
1398       && FORWARDER_BLOCK_P (src1))
1399     e1 = src1->pred, src1 = e1->src;
1400
1401   if (src2->pred
1402       && !src2->pred->pred_next
1403       && FORWARDER_BLOCK_P (src2))
1404     e2 = src2->pred, src2 = e2->src;
1405
1406   /* Nothing to do if we reach ENTRY, or a common source block.  */
1407   if (src1 == ENTRY_BLOCK_PTR || src2 == ENTRY_BLOCK_PTR)
1408     return false;
1409   if (src1 == src2)
1410     return false;
1411
1412   /* Seeing more than 1 forwarder blocks would confuse us later...  */
1413   if (FORWARDER_BLOCK_P (e1->dest)
1414       && FORWARDER_BLOCK_P (e1->dest->succ->dest))
1415     return false;
1416
1417   if (FORWARDER_BLOCK_P (e2->dest)
1418       && FORWARDER_BLOCK_P (e2->dest->succ->dest))
1419     return false;
1420
1421   /* Likewise with dead code (possibly newly created by the other optimizations
1422      of cfg_cleanup).  */
1423   if (!src1->pred || !src2->pred)
1424     return false;
1425
1426   /* Look for the common insn sequence, part the first ...  */
1427   if (!outgoing_edges_match (mode, src1, src2))
1428     return false;
1429
1430   /* ... and part the second.  */
1431   nmatch = flow_find_cross_jump (mode, src1, src2, &newpos1, &newpos2);
1432   if (!nmatch)
1433     return false;
1434
1435 #ifndef CASE_DROPS_THROUGH
1436   /* Here we know that the insns in the end of SRC1 which are common with SRC2
1437      will be deleted.
1438      If we have tablejumps in the end of SRC1 and SRC2
1439      they have been already compared for equivalence in outgoing_edges_match ()
1440      so replace the references to TABLE1 by references to TABLE2.  */
1441     {
1442       rtx label1, label2;
1443       rtx table1, table2;
1444
1445       if (tablejump_p (src1->end, &label1, &table1)
1446           && tablejump_p (src2->end, &label2, &table2)
1447           && label1 != label2)
1448         {
1449           replace_label_data rr;
1450           rtx insn;
1451
1452           /* Replace references to LABEL1 with LABEL2.  */
1453           rr.r1 = label1;
1454           rr.r2 = label2;
1455           rr.update_label_nuses = true;
1456           for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
1457             {
1458               /* Do not replace the label in SRC1->END because when deleting
1459                  a block whose end is a tablejump, the tablejump referenced
1460                  from the instruction is deleted too.  */
1461               if (insn != src1->end)
1462                 for_each_rtx (&insn, replace_label, &rr);
1463             }
1464         }
1465     }
1466 #endif
1467
1468   /* Avoid splitting if possible.  */
1469   if (newpos2 == src2->head)
1470     redirect_to = src2;
1471   else
1472     {
1473       if (rtl_dump_file)
1474         fprintf (rtl_dump_file, "Splitting bb %i before %i insns\n",
1475                  src2->index, nmatch);
1476       redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
1477     }
1478
1479   if (rtl_dump_file)
1480     fprintf (rtl_dump_file,
1481              "Cross jumping from bb %i to bb %i; %i common insns\n",
1482              src1->index, src2->index, nmatch);
1483
1484   redirect_to->count += src1->count;
1485   redirect_to->frequency += src1->frequency;
1486   /* We may have some registers visible trought the block.  */
1487   redirect_to->flags |= BB_DIRTY;
1488
1489   /* Recompute the frequencies and counts of outgoing edges.  */
1490   for (s = redirect_to->succ; s; s = s->succ_next)
1491     {
1492       edge s2;
1493       basic_block d = s->dest;
1494
1495       if (FORWARDER_BLOCK_P (d))
1496         d = d->succ->dest;
1497
1498       for (s2 = src1->succ; ; s2 = s2->succ_next)
1499         {
1500           basic_block d2 = s2->dest;
1501           if (FORWARDER_BLOCK_P (d2))
1502             d2 = d2->succ->dest;
1503           if (d == d2)
1504             break;
1505         }
1506
1507       s->count += s2->count;
1508
1509       /* Take care to update possible forwarder blocks.  We verified
1510          that there is no more than one in the chain, so we can't run
1511          into infinite loop.  */
1512       if (FORWARDER_BLOCK_P (s->dest))
1513         {
1514           s->dest->succ->count += s2->count;
1515           s->dest->count += s2->count;
1516           s->dest->frequency += EDGE_FREQUENCY (s);
1517         }
1518
1519       if (FORWARDER_BLOCK_P (s2->dest))
1520         {
1521           s2->dest->succ->count -= s2->count;
1522           if (s2->dest->succ->count < 0)
1523             s2->dest->succ->count = 0;
1524           s2->dest->count -= s2->count;
1525           s2->dest->frequency -= EDGE_FREQUENCY (s);
1526           if (s2->dest->frequency < 0)
1527             s2->dest->frequency = 0;
1528           if (s2->dest->count < 0)
1529             s2->dest->count = 0;
1530         }
1531
1532       if (!redirect_to->frequency && !src1->frequency)
1533         s->probability = (s->probability + s2->probability) / 2;
1534       else
1535         s->probability
1536           = ((s->probability * redirect_to->frequency +
1537               s2->probability * src1->frequency)
1538              / (redirect_to->frequency + src1->frequency));
1539     }
1540
1541   update_br_prob_note (redirect_to);
1542
1543   /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1.  */
1544
1545   /* Skip possible basic block header.  */
1546   if (GET_CODE (newpos1) == CODE_LABEL)
1547     newpos1 = NEXT_INSN (newpos1);
1548
1549   if (GET_CODE (newpos1) == NOTE)
1550     newpos1 = NEXT_INSN (newpos1);
1551
1552   redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
1553   to_remove = redirect_from->succ->dest;
1554
1555   redirect_edge_and_branch_force (redirect_from->succ, redirect_to);
1556   delete_block (to_remove);
1557
1558   update_forwarder_flag (redirect_from);
1559
1560   return true;
1561 }
1562
1563 /* Search the predecessors of BB for common insn sequences.  When found,
1564    share code between them by redirecting control flow.  Return true if
1565    any changes made.  */
1566
1567 static bool
1568 try_crossjump_bb (int mode, basic_block bb)
1569 {
1570   edge e, e2, nexte2, nexte, fallthru;
1571   bool changed;
1572   int n = 0, max;
1573
1574   /* Nothing to do if there is not at least two incoming edges.  */
1575   if (!bb->pred || !bb->pred->pred_next)
1576     return false;
1577
1578   /* It is always cheapest to redirect a block that ends in a branch to
1579      a block that falls through into BB, as that adds no branches to the
1580      program.  We'll try that combination first.  */
1581   fallthru = NULL;
1582   max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
1583   for (e = bb->pred; e ; e = e->pred_next, n++)
1584     {
1585       if (e->flags & EDGE_FALLTHRU)
1586         fallthru = e;
1587       if (n > max)
1588         return false;
1589     }
1590
1591   changed = false;
1592   for (e = bb->pred; e; e = nexte)
1593     {
1594       nexte = e->pred_next;
1595
1596       /* As noted above, first try with the fallthru predecessor.  */
1597       if (fallthru)
1598         {
1599           /* Don't combine the fallthru edge into anything else.
1600              If there is a match, we'll do it the other way around.  */
1601           if (e == fallthru)
1602             continue;
1603
1604           if (try_crossjump_to_edge (mode, e, fallthru))
1605             {
1606               changed = true;
1607               nexte = bb->pred;
1608               continue;
1609             }
1610         }
1611
1612       /* Non-obvious work limiting check: Recognize that we're going
1613          to call try_crossjump_bb on every basic block.  So if we have
1614          two blocks with lots of outgoing edges (a switch) and they
1615          share lots of common destinations, then we would do the
1616          cross-jump check once for each common destination.
1617
1618          Now, if the blocks actually are cross-jump candidates, then
1619          all of their destinations will be shared.  Which means that
1620          we only need check them for cross-jump candidacy once.  We
1621          can eliminate redundant checks of crossjump(A,B) by arbitrarily
1622          choosing to do the check from the block for which the edge
1623          in question is the first successor of A.  */
1624       if (e->src->succ != e)
1625         continue;
1626
1627       for (e2 = bb->pred; e2; e2 = nexte2)
1628         {
1629           nexte2 = e2->pred_next;
1630
1631           if (e2 == e)
1632             continue;
1633
1634           /* We've already checked the fallthru edge above.  */
1635           if (e2 == fallthru)
1636             continue;
1637
1638           /* The "first successor" check above only prevents multiple
1639              checks of crossjump(A,B).  In order to prevent redundant
1640              checks of crossjump(B,A), require that A be the block
1641              with the lowest index.  */
1642           if (e->src->index > e2->src->index)
1643             continue;
1644
1645           if (try_crossjump_to_edge (mode, e, e2))
1646             {
1647               changed = true;
1648               nexte = bb->pred;
1649               break;
1650             }
1651         }
1652     }
1653
1654   return changed;
1655 }
1656
1657 /* Do simple CFG optimizations - basic block merging, simplifying of jump
1658    instructions etc.  Return nonzero if changes were made.  */
1659
1660 static bool
1661 try_optimize_cfg (int mode)
1662 {
1663   bool changed_overall = false;
1664   bool changed;
1665   int iterations = 0;
1666   basic_block bb, b, next;
1667
1668   if (mode & CLEANUP_CROSSJUMP)
1669     add_noreturn_fake_exit_edges ();
1670
1671   FOR_EACH_BB (bb)
1672     update_forwarder_flag (bb);
1673
1674   if (mode & CLEANUP_UPDATE_LIFE)
1675     clear_bb_flags ();
1676
1677   if (! (* targetm.cannot_modify_jumps_p) ())
1678     {
1679       /* Attempt to merge blocks as made possible by edge removal.  If
1680          a block has only one successor, and the successor has only
1681          one predecessor, they may be combined.  */
1682       do
1683         {
1684           changed = false;
1685           iterations++;
1686
1687           if (rtl_dump_file)
1688             fprintf (rtl_dump_file,
1689                      "\n\ntry_optimize_cfg iteration %i\n\n",
1690                      iterations);
1691
1692           for (b = ENTRY_BLOCK_PTR->next_bb; b != EXIT_BLOCK_PTR;)
1693             {
1694               basic_block c;
1695               edge s;
1696               bool changed_here = false;
1697
1698               /* Delete trivially dead basic blocks.  */
1699               while (b->pred == NULL)
1700                 {
1701                   c = b->prev_bb;
1702                   if (rtl_dump_file)
1703                     fprintf (rtl_dump_file, "Deleting block %i.\n",
1704                              b->index);
1705
1706                   delete_block (b);
1707                   if (!(mode & CLEANUP_CFGLAYOUT))
1708                     changed = true;
1709                   b = c;
1710                 }
1711
1712               /* Remove code labels no longer used.  Don't do this
1713                  before CALL_PLACEHOLDER is removed, as some branches
1714                  may be hidden within.  */
1715               if (b->pred->pred_next == NULL
1716                   && (b->pred->flags & EDGE_FALLTHRU)
1717                   && !(b->pred->flags & EDGE_COMPLEX)
1718                   && GET_CODE (b->head) == CODE_LABEL
1719                   && (!(mode & CLEANUP_PRE_SIBCALL)
1720                       || !tail_recursion_label_p (b->head))
1721                   /* If the previous block ends with a branch to this
1722                      block, we can't delete the label.  Normally this
1723                      is a condjump that is yet to be simplified, but
1724                      if CASE_DROPS_THRU, this can be a tablejump with
1725                      some element going to the same place as the
1726                      default (fallthru).  */
1727                   && (b->pred->src == ENTRY_BLOCK_PTR
1728                       || GET_CODE (b->pred->src->end) != JUMP_INSN
1729                       || ! label_is_jump_target_p (b->head,
1730                                                    b->pred->src->end)))
1731                 {
1732                   rtx label = b->head;
1733
1734                   delete_insn_chain (label, label);
1735                   /* In the case label is undeletable, move it after the
1736                      BASIC_BLOCK note.  */
1737                   if (NOTE_LINE_NUMBER (b->head) == NOTE_INSN_DELETED_LABEL)
1738                     {
1739                       rtx bb_note = NEXT_INSN (b->head);
1740
1741                       reorder_insns_nobb (label, label, bb_note);
1742                       b->head = bb_note;
1743                     }
1744                   if (rtl_dump_file)
1745                     fprintf (rtl_dump_file, "Deleted label in block %i.\n",
1746                              b->index);
1747                 }
1748
1749               /* If we fall through an empty block, we can remove it.  */
1750               if (!(mode & CLEANUP_CFGLAYOUT)
1751                   && b->pred->pred_next == NULL
1752                   && (b->pred->flags & EDGE_FALLTHRU)
1753                   && GET_CODE (b->head) != CODE_LABEL
1754                   && FORWARDER_BLOCK_P (b)
1755                   /* Note that forwarder_block_p true ensures that
1756                      there is a successor for this block.  */
1757                   && (b->succ->flags & EDGE_FALLTHRU)
1758                   && n_basic_blocks > 1)
1759                 {
1760                   if (rtl_dump_file)
1761                     fprintf (rtl_dump_file,
1762                              "Deleting fallthru block %i.\n",
1763                              b->index);
1764
1765                   c = b->prev_bb == ENTRY_BLOCK_PTR ? b->next_bb : b->prev_bb;
1766                   redirect_edge_succ_nodup (b->pred, b->succ->dest);
1767                   delete_block (b);
1768                   changed = true;
1769                   b = c;
1770                 }
1771
1772               if ((s = b->succ) != NULL
1773                   && s->succ_next == NULL
1774                   && !(s->flags & EDGE_COMPLEX)
1775                   && (c = s->dest) != EXIT_BLOCK_PTR
1776                   && c->pred->pred_next == NULL
1777                   && b != c)
1778                 {
1779                   /* When not in cfg_layout mode use code aware of reordering
1780                      INSN.  This code possibly creates new basic blocks so it
1781                      does not fit merge_blocks interface and is kept here in
1782                      hope that it will become useless once more of compiler
1783                      is transformed to use cfg_layout mode.  */
1784                      
1785                   if ((mode & CLEANUP_CFGLAYOUT)
1786                       && can_merge_blocks_p (b, c))
1787                     {
1788                       merge_blocks (b, c);
1789                       update_forwarder_flag (b);
1790                       changed_here = true;
1791                     }
1792                   else if (!(mode & CLEANUP_CFGLAYOUT)
1793                            /* If the jump insn has side effects,
1794                               we can't kill the edge.  */
1795                            && (GET_CODE (b->end) != JUMP_INSN
1796                                || (flow2_completed
1797                                    ? simplejump_p (b->end)
1798                                    : onlyjump_p (b->end)))
1799                            && (next = merge_blocks_move (s, b, c, mode)))
1800                       {
1801                         b = next;
1802                         changed_here = true;
1803                       }
1804                 }
1805
1806               /* Simplify branch over branch.  */
1807               if ((mode & CLEANUP_EXPENSIVE)
1808                    && !(mode & CLEANUP_CFGLAYOUT)
1809                    && try_simplify_condjump (b))
1810                 changed_here = true;
1811
1812               /* If B has a single outgoing edge, but uses a
1813                  non-trivial jump instruction without side-effects, we
1814                  can either delete the jump entirely, or replace it
1815                  with a simple unconditional jump.  Use
1816                  redirect_edge_and_branch to do the dirty work.  */
1817               if (b->succ
1818                   && ! b->succ->succ_next
1819                   && b->succ->dest != EXIT_BLOCK_PTR
1820                   && onlyjump_p (b->end)
1821                   && redirect_edge_and_branch (b->succ, b->succ->dest))
1822                 {
1823                   update_forwarder_flag (b);
1824                   changed_here = true;
1825                 }
1826
1827               /* Simplify branch to branch.  */
1828               if (try_forward_edges (mode, b))
1829                 changed_here = true;
1830
1831               /* Look for shared code between blocks.  */
1832               if ((mode & CLEANUP_CROSSJUMP)
1833                   && try_crossjump_bb (mode, b))
1834                 changed_here = true;
1835
1836               /* Don't get confused by the index shift caused by
1837                  deleting blocks.  */
1838               if (!changed_here)
1839                 b = b->next_bb;
1840               else
1841                 changed = true;
1842             }
1843
1844           if ((mode & CLEANUP_CROSSJUMP)
1845               && try_crossjump_bb (mode, EXIT_BLOCK_PTR))
1846             changed = true;
1847
1848 #ifdef ENABLE_CHECKING
1849           if (changed)
1850             verify_flow_info ();
1851 #endif
1852
1853           changed_overall |= changed;
1854         }
1855       while (changed);
1856     }
1857
1858   if (mode & CLEANUP_CROSSJUMP)
1859     remove_fake_edges ();
1860
1861   clear_aux_for_blocks ();
1862
1863   return changed_overall;
1864 }
1865 \f
1866 /* Delete all unreachable basic blocks.  */
1867
1868 bool
1869 delete_unreachable_blocks (void)
1870 {
1871   bool changed = false;
1872   basic_block b, next_bb;
1873
1874   find_unreachable_blocks ();
1875
1876   /* Delete all unreachable basic blocks.  */
1877
1878   for (b = ENTRY_BLOCK_PTR->next_bb; b != EXIT_BLOCK_PTR; b = next_bb)
1879     {
1880       next_bb = b->next_bb;
1881
1882       if (!(b->flags & BB_REACHABLE))
1883         {
1884           delete_block (b);
1885           changed = true;
1886         }
1887     }
1888
1889   if (changed)
1890     tidy_fallthru_edges ();
1891   return changed;
1892 }
1893 \f
1894 /* Tidy the CFG by deleting unreachable code and whatnot.  */
1895
1896 bool
1897 cleanup_cfg (int mode)
1898 {
1899   bool changed = false;
1900
1901   timevar_push (TV_CLEANUP_CFG);
1902   if (delete_unreachable_blocks ())
1903     {
1904       changed = true;
1905       /* We've possibly created trivially dead code.  Cleanup it right
1906          now to introduce more opportunities for try_optimize_cfg.  */
1907       if (!(mode & (CLEANUP_NO_INSN_DEL
1908                     | CLEANUP_UPDATE_LIFE | CLEANUP_PRE_SIBCALL))
1909           && !reload_completed)
1910         delete_trivially_dead_insns (get_insns(), max_reg_num ());
1911     }
1912
1913   compact_blocks ();
1914
1915   while (try_optimize_cfg (mode))
1916     {
1917       delete_unreachable_blocks (), changed = true;
1918       if (mode & CLEANUP_UPDATE_LIFE)
1919         {
1920           /* Cleaning up CFG introduces more opportunities for dead code
1921              removal that in turn may introduce more opportunities for
1922              cleaning up the CFG.  */
1923           if (!update_life_info_in_dirty_blocks (UPDATE_LIFE_GLOBAL_RM_NOTES,
1924                                                  PROP_DEATH_NOTES
1925                                                  | PROP_SCAN_DEAD_CODE
1926                                                  | PROP_KILL_DEAD_CODE
1927                                                  | PROP_LOG_LINKS))
1928             break;
1929         }
1930       else if (!(mode & (CLEANUP_NO_INSN_DEL | CLEANUP_PRE_SIBCALL))
1931                && (mode & CLEANUP_EXPENSIVE)
1932                && !reload_completed)
1933         {
1934           if (!delete_trivially_dead_insns (get_insns(), max_reg_num ()))
1935             break;
1936         }
1937       else
1938         break;
1939       delete_dead_jumptables ();
1940     }
1941
1942   /* Kill the data we won't maintain.  */
1943   free_EXPR_LIST_list (&label_value_list);
1944   timevar_pop (TV_CLEANUP_CFG);
1945
1946   return changed;
1947 }