OSDN Git Service

* config/i386/i386.h: Remove an unnecessary #undef.
[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 = BB_END (cbranch_block);
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 (BB_END (jump_block)));
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 = BB_END (jump_block);
176   /* Deleting a block may produce unreachable code warning even when we are
177      not deleting anything live.  Suppress it by moving all the line number
178      notes out of the block.  */
179   for (insn = BB_HEAD (jump_block); insn != NEXT_INSN (BB_END (jump_block));
180        insn = next)
181     {
182       next = NEXT_INSN (insn);
183       if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
184         {
185           if (insn == BB_END (jump_block))
186             {
187               BB_END (jump_block) = PREV_INSN (insn);
188               if (insn == 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 (BB_END (e->src)))
304     return NULL;
305
306   if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
307     {
308       BB_SET_FLAG (b, BB_NONTHREADABLE_BLOCK);
309       return NULL;
310     }
311
312   set1 = pc_set (BB_END (e->src));
313   set2 = pc_set (BB_END (b));
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, BB_END (e->src));
322   else
323     code1 = GET_CODE (cond1);
324
325   code2 = GET_CODE (cond2);
326   reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
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 (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
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 (BB_HEAD (e->src)); insn != NEXT_INSN (BB_END (e->src));
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 (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b)) && !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                           ? BB_HEAD (target) : prev_nonnote_insn (BB_END (target)));
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 (BB_HEAD (target));
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 (PATTERN (tmp),
665                         GET_CODE (PATTERN (tmp)) == ADDR_DIFF_VEC);
666       int i, veclen = GET_NUM_ELEM (vec);
667
668       for (i = 0; i < veclen; ++i)
669         if (XEXP (RTVEC_ELT (vec, i), 0) == label)
670           return true;
671     }
672
673   return false;
674 }
675
676 /* Return true if LABEL is used for tail recursion.  */
677
678 static bool
679 tail_recursion_label_p (rtx label)
680 {
681   rtx x;
682
683   for (x = tail_recursion_label_list; x; x = XEXP (x, 1))
684     if (label == XEXP (x, 0))
685       return true;
686
687   return false;
688 }
689
690 /* Blocks A and B are to be merged into a single block.  A has no incoming
691    fallthru edge, so it can be moved before B without adding or modifying
692    any jumps (aside from the jump from A to B).  */
693
694 static void
695 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
696 {
697   rtx barrier;
698
699   barrier = next_nonnote_insn (BB_END (a));
700   if (GET_CODE (barrier) != BARRIER)
701     abort ();
702   delete_insn (barrier);
703
704   /* Move block and loop notes out of the chain so that we do not
705      disturb their order.
706
707      ??? A better solution would be to squeeze out all the non-nested notes
708      and adjust the block trees appropriately.   Even better would be to have
709      a tighter connection between block trees and rtl so that this is not
710      necessary.  */
711   if (squeeze_notes (&BB_HEAD (a), &BB_END (a)))
712     abort ();
713
714   /* Scramble the insn chain.  */
715   if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
716     reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
717   a->flags |= BB_DIRTY;
718
719   if (rtl_dump_file)
720     fprintf (rtl_dump_file, "Moved block %d before %d and merged.\n",
721              a->index, b->index);
722
723   /* Swap the records for the two blocks around.  */
724
725   unlink_block (a);
726   link_block (a, b->prev_bb);
727
728   /* Now blocks A and B are contiguous.  Merge them.  */
729   merge_blocks (a, b);
730 }
731
732 /* Blocks A and B are to be merged into a single block.  B has no outgoing
733    fallthru edge, so it can be moved after A without adding or modifying
734    any jumps (aside from the jump from A to B).  */
735
736 static void
737 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
738 {
739   rtx barrier, real_b_end;
740   rtx label, table;
741
742   real_b_end = BB_END (b);
743
744   /* If there is a jump table following block B temporarily add the jump table
745      to block B so that it will also be moved to the correct location.  */
746   if (tablejump_p (BB_END (b), &label, &table)
747       && prev_active_insn (label) == BB_END (b))
748     {
749       BB_END (b) = table;
750     }
751
752   /* There had better have been a barrier there.  Delete it.  */
753   barrier = NEXT_INSN (BB_END (b));
754   if (barrier && GET_CODE (barrier) == BARRIER)
755     delete_insn (barrier);
756
757   /* Move block and loop notes out of the chain so that we do not
758      disturb their order.
759
760      ??? A better solution would be to squeeze out all the non-nested notes
761      and adjust the block trees appropriately.   Even better would be to have
762      a tighter connection between block trees and rtl so that this is not
763      necessary.  */
764   if (squeeze_notes (&BB_HEAD (b), &BB_END (b)))
765     abort ();
766
767   /* Scramble the insn chain.  */
768   reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
769
770   /* Restore the real end of b.  */
771   BB_END (b) = real_b_end;
772
773   if (rtl_dump_file)
774     fprintf (rtl_dump_file, "Moved block %d after %d and merged.\n",
775              b->index, a->index);
776
777   /* Now blocks A and B are contiguous.  Merge them.  */
778   merge_blocks (a, b);
779 }
780
781 /* Attempt to merge basic blocks that are potentially non-adjacent.
782    Return NULL iff the attempt failed, otherwise return basic block
783    where cleanup_cfg should continue.  Because the merging commonly
784    moves basic block away or introduces another optimization
785    possibility, return basic block just before B so cleanup_cfg don't
786    need to iterate.
787
788    It may be good idea to return basic block before C in the case
789    C has been moved after B and originally appeared earlier in the
790    insn sequence, but we have no information available about the
791    relative ordering of these two.  Hopefully it is not too common.  */
792
793 static basic_block
794 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
795 {
796   basic_block next;
797   /* If C has a tail recursion label, do not merge.  There is no
798      edge recorded from the call_placeholder back to this label, as
799      that would make optimize_sibling_and_tail_recursive_calls more
800      complex for no gain.  */
801   if ((mode & CLEANUP_PRE_SIBCALL)
802       && GET_CODE (BB_HEAD (c)) == CODE_LABEL
803       && tail_recursion_label_p (BB_HEAD (c)))
804     return NULL;
805
806   /* If B has a fallthru edge to C, no need to move anything.  */
807   if (e->flags & EDGE_FALLTHRU)
808     {
809       int b_index = b->index, c_index = c->index;
810       merge_blocks (b, c);
811       update_forwarder_flag (b);
812
813       if (rtl_dump_file)
814         fprintf (rtl_dump_file, "Merged %d and %d without moving.\n",
815                  b_index, c_index);
816
817       return b->prev_bb == ENTRY_BLOCK_PTR ? b : b->prev_bb;
818     }
819
820   /* Otherwise we will need to move code around.  Do that only if expensive
821      transformations are allowed.  */
822   else if (mode & CLEANUP_EXPENSIVE)
823     {
824       edge tmp_edge, b_fallthru_edge;
825       bool c_has_outgoing_fallthru;
826       bool b_has_incoming_fallthru;
827
828       /* Avoid overactive code motion, as the forwarder blocks should be
829          eliminated by edge redirection instead.  One exception might have
830          been if B is a forwarder block and C has no fallthru edge, but
831          that should be cleaned up by bb-reorder instead.  */
832       if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
833         return NULL;
834
835       /* We must make sure to not munge nesting of lexical blocks,
836          and loop notes.  This is done by squeezing out all the notes
837          and leaving them there to lie.  Not ideal, but functional.  */
838
839       for (tmp_edge = c->succ; tmp_edge; tmp_edge = tmp_edge->succ_next)
840         if (tmp_edge->flags & EDGE_FALLTHRU)
841           break;
842
843       c_has_outgoing_fallthru = (tmp_edge != NULL);
844
845       for (tmp_edge = b->pred; tmp_edge; tmp_edge = tmp_edge->pred_next)
846         if (tmp_edge->flags & EDGE_FALLTHRU)
847           break;
848
849       b_has_incoming_fallthru = (tmp_edge != NULL);
850       b_fallthru_edge = tmp_edge;
851       next = b->prev_bb;
852       if (next == c)
853         next = next->prev_bb;
854
855       /* Otherwise, we're going to try to move C after B.  If C does
856          not have an outgoing fallthru, then it can be moved
857          immediately after B without introducing or modifying jumps.  */
858       if (! c_has_outgoing_fallthru)
859         {
860           merge_blocks_move_successor_nojumps (b, c);
861           return next == ENTRY_BLOCK_PTR ? next->next_bb : next;
862         }
863
864       /* If B does not have an incoming fallthru, then it can be moved
865          immediately before C without introducing or modifying jumps.
866          C cannot be the first block, so we do not have to worry about
867          accessing a non-existent block.  */
868
869       if (b_has_incoming_fallthru)
870         {
871           basic_block bb;
872
873           if (b_fallthru_edge->src == ENTRY_BLOCK_PTR)
874             return NULL;
875           bb = force_nonfallthru (b_fallthru_edge);
876           if (bb)
877             notice_new_block (bb);
878         }
879
880       merge_blocks_move_predecessor_nojumps (b, c);
881       return next == ENTRY_BLOCK_PTR ? next->next_bb : next;
882     }
883
884   return NULL;
885 }
886 \f
887
888 /* Return true if I1 and I2 are equivalent and thus can be crossjumped.  */
889
890 static bool
891 insns_match_p (int mode ATTRIBUTE_UNUSED, rtx i1, rtx i2)
892 {
893   rtx p1, p2;
894
895   /* Verify that I1 and I2 are equivalent.  */
896   if (GET_CODE (i1) != GET_CODE (i2))
897     return false;
898
899   p1 = PATTERN (i1);
900   p2 = PATTERN (i2);
901
902   if (GET_CODE (p1) != GET_CODE (p2))
903     return false;
904
905   /* If this is a CALL_INSN, compare register usage information.
906      If we don't check this on stack register machines, the two
907      CALL_INSNs might be merged leaving reg-stack.c with mismatching
908      numbers of stack registers in the same basic block.
909      If we don't check this on machines with delay slots, a delay slot may
910      be filled that clobbers a parameter expected by the subroutine.
911
912      ??? We take the simple route for now and assume that if they're
913      equal, they were constructed identically.  */
914
915   if (GET_CODE (i1) == CALL_INSN
916       && (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
917                         CALL_INSN_FUNCTION_USAGE (i2))
918           || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2)))
919     return false;
920
921 #ifdef STACK_REGS
922   /* If cross_jump_death_matters is not 0, the insn's mode
923      indicates whether or not the insn contains any stack-like
924      regs.  */
925
926   if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
927     {
928       /* If register stack conversion has already been done, then
929          death notes must also be compared before it is certain that
930          the two instruction streams match.  */
931
932       rtx note;
933       HARD_REG_SET i1_regset, i2_regset;
934
935       CLEAR_HARD_REG_SET (i1_regset);
936       CLEAR_HARD_REG_SET (i2_regset);
937
938       for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
939         if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
940           SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
941
942       for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
943         if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
944           SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
945
946       GO_IF_HARD_REG_EQUAL (i1_regset, i2_regset, done);
947
948       return false;
949
950     done:
951       ;
952     }
953 #endif
954
955   if (reload_completed
956       ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
957     return true;
958
959   /* Do not do EQUIV substitution after reload.  First, we're undoing the
960      work of reload_cse.  Second, we may be undoing the work of the post-
961      reload splitting pass.  */
962   /* ??? Possibly add a new phase switch variable that can be used by
963      targets to disallow the troublesome insns after splitting.  */
964   if (!reload_completed)
965     {
966       /* The following code helps take care of G++ cleanups.  */
967       rtx equiv1 = find_reg_equal_equiv_note (i1);
968       rtx equiv2 = find_reg_equal_equiv_note (i2);
969
970       if (equiv1 && equiv2
971           /* If the equivalences are not to a constant, they may
972              reference pseudos that no longer exist, so we can't
973              use them.  */
974           && (! reload_completed
975               || (CONSTANT_P (XEXP (equiv1, 0))
976                   && rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))))
977         {
978           rtx s1 = single_set (i1);
979           rtx s2 = single_set (i2);
980           if (s1 != 0 && s2 != 0
981               && rtx_renumbered_equal_p (SET_DEST (s1), SET_DEST (s2)))
982             {
983               validate_change (i1, &SET_SRC (s1), XEXP (equiv1, 0), 1);
984               validate_change (i2, &SET_SRC (s2), XEXP (equiv2, 0), 1);
985               if (! rtx_renumbered_equal_p (p1, p2))
986                 cancel_changes (0);
987               else if (apply_change_group ())
988                 return true;
989             }
990         }
991     }
992
993   return false;
994 }
995 \f
996 /* Look through the insns at the end of BB1 and BB2 and find the longest
997    sequence that are equivalent.  Store the first insns for that sequence
998    in *F1 and *F2 and return the sequence length.
999
1000    To simplify callers of this function, if the blocks match exactly,
1001    store the head of the blocks in *F1 and *F2.  */
1002
1003 static int
1004 flow_find_cross_jump (int mode ATTRIBUTE_UNUSED, basic_block bb1,
1005                       basic_block bb2, rtx *f1, rtx *f2)
1006 {
1007   rtx i1, i2, last1, last2, afterlast1, afterlast2;
1008   int ninsns = 0;
1009
1010   /* Skip simple jumps at the end of the blocks.  Complex jumps still
1011      need to be compared for equivalence, which we'll do below.  */
1012
1013   i1 = BB_END (bb1);
1014   last1 = afterlast1 = last2 = afterlast2 = NULL_RTX;
1015   if (onlyjump_p (i1)
1016       || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1017     {
1018       last1 = i1;
1019       i1 = PREV_INSN (i1);
1020     }
1021
1022   i2 = BB_END (bb2);
1023   if (onlyjump_p (i2)
1024       || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1025     {
1026       last2 = i2;
1027       /* Count everything except for unconditional jump as insn.  */
1028       if (!simplejump_p (i2) && !returnjump_p (i2) && last1)
1029         ninsns++;
1030       i2 = PREV_INSN (i2);
1031     }
1032
1033   while (true)
1034     {
1035       /* Ignore notes.  */
1036       while (!INSN_P (i1) && i1 != BB_HEAD (bb1))
1037         i1 = PREV_INSN (i1);
1038
1039       while (!INSN_P (i2) && i2 != BB_HEAD (bb2))
1040         i2 = PREV_INSN (i2);
1041
1042       if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1043         break;
1044
1045       if (!insns_match_p (mode, i1, i2))
1046         break;
1047
1048       /* Don't begin a cross-jump with a NOTE insn.  */
1049       if (INSN_P (i1))
1050         {
1051           /* If the merged insns have different REG_EQUAL notes, then
1052              remove them.  */
1053           rtx equiv1 = find_reg_equal_equiv_note (i1);
1054           rtx equiv2 = find_reg_equal_equiv_note (i2);
1055
1056           if (equiv1 && !equiv2)
1057             remove_note (i1, equiv1);
1058           else if (!equiv1 && equiv2)
1059             remove_note (i2, equiv2);
1060           else if (equiv1 && equiv2
1061                    && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1062             {
1063               remove_note (i1, equiv1);
1064               remove_note (i2, equiv2);
1065             }
1066
1067           afterlast1 = last1, afterlast2 = last2;
1068           last1 = i1, last2 = i2;
1069           ninsns++;
1070         }
1071
1072       i1 = PREV_INSN (i1);
1073       i2 = PREV_INSN (i2);
1074     }
1075
1076 #ifdef HAVE_cc0
1077   /* Don't allow the insn after a compare to be shared by
1078      cross-jumping unless the compare is also shared.  */
1079   if (ninsns && reg_mentioned_p (cc0_rtx, last1) && ! sets_cc0_p (last1))
1080     last1 = afterlast1, last2 = afterlast2, ninsns--;
1081 #endif
1082
1083   /* Include preceding notes and labels in the cross-jump.  One,
1084      this may bring us to the head of the blocks as requested above.
1085      Two, it keeps line number notes as matched as may be.  */
1086   if (ninsns)
1087     {
1088       while (last1 != BB_HEAD (bb1) && !INSN_P (PREV_INSN (last1)))
1089         last1 = PREV_INSN (last1);
1090
1091       if (last1 != BB_HEAD (bb1) && GET_CODE (PREV_INSN (last1)) == CODE_LABEL)
1092         last1 = PREV_INSN (last1);
1093
1094       while (last2 != BB_HEAD (bb2) && !INSN_P (PREV_INSN (last2)))
1095         last2 = PREV_INSN (last2);
1096
1097       if (last2 != BB_HEAD (bb2) && GET_CODE (PREV_INSN (last2)) == CODE_LABEL)
1098         last2 = PREV_INSN (last2);
1099
1100       *f1 = last1;
1101       *f2 = last2;
1102     }
1103
1104   return ninsns;
1105 }
1106
1107 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1108    the branch instruction.  This means that if we commonize the control
1109    flow before end of the basic block, the semantic remains unchanged.
1110
1111    We may assume that there exists one edge with a common destination.  */
1112
1113 static bool
1114 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1115 {
1116   int nehedges1 = 0, nehedges2 = 0;
1117   edge fallthru1 = 0, fallthru2 = 0;
1118   edge e1, e2;
1119
1120   /* If BB1 has only one successor, we may be looking at either an
1121      unconditional jump, or a fake edge to exit.  */
1122   if (bb1->succ && !bb1->succ->succ_next
1123       && (bb1->succ->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1124       && (GET_CODE (BB_END (bb1)) != JUMP_INSN || simplejump_p (BB_END (bb1))))
1125     return (bb2->succ &&  !bb2->succ->succ_next
1126             && (bb2->succ->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1127             && (GET_CODE (BB_END (bb2)) != JUMP_INSN || simplejump_p (BB_END (bb2))));
1128
1129   /* Match conditional jumps - this may get tricky when fallthru and branch
1130      edges are crossed.  */
1131   if (bb1->succ
1132       && bb1->succ->succ_next
1133       && !bb1->succ->succ_next->succ_next
1134       && any_condjump_p (BB_END (bb1))
1135       && onlyjump_p (BB_END (bb1)))
1136     {
1137       edge b1, f1, b2, f2;
1138       bool reverse, match;
1139       rtx set1, set2, cond1, cond2;
1140       enum rtx_code code1, code2;
1141
1142       if (!bb2->succ
1143           || !bb2->succ->succ_next
1144           || bb2->succ->succ_next->succ_next
1145           || !any_condjump_p (BB_END (bb2))
1146           || !onlyjump_p (BB_END (bb2)))
1147         return false;
1148
1149       b1 = BRANCH_EDGE (bb1);
1150       b2 = BRANCH_EDGE (bb2);
1151       f1 = FALLTHRU_EDGE (bb1);
1152       f2 = FALLTHRU_EDGE (bb2);
1153
1154       /* Get around possible forwarders on fallthru edges.  Other cases
1155          should be optimized out already.  */
1156       if (FORWARDER_BLOCK_P (f1->dest))
1157         f1 = f1->dest->succ;
1158
1159       if (FORWARDER_BLOCK_P (f2->dest))
1160         f2 = f2->dest->succ;
1161
1162       /* To simplify use of this function, return false if there are
1163          unneeded forwarder blocks.  These will get eliminated later
1164          during cleanup_cfg.  */
1165       if (FORWARDER_BLOCK_P (f1->dest)
1166           || FORWARDER_BLOCK_P (f2->dest)
1167           || FORWARDER_BLOCK_P (b1->dest)
1168           || FORWARDER_BLOCK_P (b2->dest))
1169         return false;
1170
1171       if (f1->dest == f2->dest && b1->dest == b2->dest)
1172         reverse = false;
1173       else if (f1->dest == b2->dest && b1->dest == f2->dest)
1174         reverse = true;
1175       else
1176         return false;
1177
1178       set1 = pc_set (BB_END (bb1));
1179       set2 = pc_set (BB_END (bb2));
1180       if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1181           != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1182         reverse = !reverse;
1183
1184       cond1 = XEXP (SET_SRC (set1), 0);
1185       cond2 = XEXP (SET_SRC (set2), 0);
1186       code1 = GET_CODE (cond1);
1187       if (reverse)
1188         code2 = reversed_comparison_code (cond2, BB_END (bb2));
1189       else
1190         code2 = GET_CODE (cond2);
1191
1192       if (code2 == UNKNOWN)
1193         return false;
1194
1195       /* Verify codes and operands match.  */
1196       match = ((code1 == code2
1197                 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1198                 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1199                || (code1 == swap_condition (code2)
1200                    && rtx_renumbered_equal_p (XEXP (cond1, 1),
1201                                               XEXP (cond2, 0))
1202                    && rtx_renumbered_equal_p (XEXP (cond1, 0),
1203                                               XEXP (cond2, 1))));
1204
1205       /* If we return true, we will join the blocks.  Which means that
1206          we will only have one branch prediction bit to work with.  Thus
1207          we require the existing branches to have probabilities that are
1208          roughly similar.  */
1209       if (match
1210           && !optimize_size
1211           && maybe_hot_bb_p (bb1)
1212           && maybe_hot_bb_p (bb2))
1213         {
1214           int prob2;
1215
1216           if (b1->dest == b2->dest)
1217             prob2 = b2->probability;
1218           else
1219             /* Do not use f2 probability as f2 may be forwarded.  */
1220             prob2 = REG_BR_PROB_BASE - b2->probability;
1221
1222           /* Fail if the difference in probabilities is greater than 50%.
1223              This rules out two well-predicted branches with opposite
1224              outcomes.  */
1225           if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1226             {
1227               if (rtl_dump_file)
1228                 fprintf (rtl_dump_file,
1229                          "Outcomes of branch in bb %i and %i differs to much (%i %i)\n",
1230                          bb1->index, bb2->index, b1->probability, prob2);
1231
1232               return false;
1233             }
1234         }
1235
1236       if (rtl_dump_file && match)
1237         fprintf (rtl_dump_file, "Conditionals in bb %i and %i match.\n",
1238                  bb1->index, bb2->index);
1239
1240       return match;
1241     }
1242
1243   /* Generic case - we are seeing a computed jump, table jump or trapping
1244      instruction.  */
1245
1246 #ifndef CASE_DROPS_THROUGH
1247   /* Check whether there are tablejumps in the end of BB1 and BB2.
1248      Return true if they are identical.  */
1249     {
1250       rtx label1, label2;
1251       rtx table1, table2;
1252
1253       if (tablejump_p (BB_END (bb1), &label1, &table1)
1254           && tablejump_p (BB_END (bb2), &label2, &table2)
1255           && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1256         {
1257           /* The labels should never be the same rtx.  If they really are same
1258              the jump tables are same too. So disable crossjumping of blocks BB1
1259              and BB2 because when deleting the common insns in the end of BB1
1260              by delete_block () the jump table would be deleted too.  */
1261           /* If LABEL2 is referenced in BB1->END do not do anything
1262              because we would loose information when replacing
1263              LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END.  */
1264           if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1265             {
1266               /* Set IDENTICAL to true when the tables are identical.  */
1267               bool identical = false;
1268               rtx p1, p2;
1269
1270               p1 = PATTERN (table1);
1271               p2 = PATTERN (table2);
1272               if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1273                 {
1274                   identical = true;
1275                 }
1276               else if (GET_CODE (p1) == ADDR_DIFF_VEC
1277                        && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1278                        && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1279                        && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1280                 {
1281                   int i;
1282
1283                   identical = true;
1284                   for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1285                     if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1286                       identical = false;
1287                 }
1288
1289               if (identical)
1290                 {
1291                   replace_label_data rr;
1292                   bool match;
1293
1294                   /* Temporarily replace references to LABEL1 with LABEL2
1295                      in BB1->END so that we could compare the instructions.  */
1296                   rr.r1 = label1;
1297                   rr.r2 = label2;
1298                   rr.update_label_nuses = false;
1299                   for_each_rtx (&BB_END (bb1), replace_label, &rr);
1300
1301                   match = insns_match_p (mode, BB_END (bb1), BB_END (bb2));
1302                   if (rtl_dump_file && match)
1303                     fprintf (rtl_dump_file,
1304                              "Tablejumps in bb %i and %i match.\n",
1305                              bb1->index, bb2->index);
1306
1307                   /* Set the original label in BB1->END because when deleting
1308                      a block whose end is a tablejump, the tablejump referenced
1309                      from the instruction is deleted too.  */
1310                   rr.r1 = label2;
1311                   rr.r2 = label1;
1312                   for_each_rtx (&BB_END (bb1), replace_label, &rr);
1313
1314                   return match;
1315                 }
1316             }
1317           return false;
1318         }
1319     }
1320 #endif
1321
1322   /* First ensure that the instructions match.  There may be many outgoing
1323      edges so this test is generally cheaper.  */
1324   if (!insns_match_p (mode, BB_END (bb1), BB_END (bb2)))
1325     return false;
1326
1327   /* Search the outgoing edges, ensure that the counts do match, find possible
1328      fallthru and exception handling edges since these needs more
1329      validation.  */
1330   for (e1 = bb1->succ, e2 = bb2->succ; e1 && e2;
1331        e1 = e1->succ_next, e2 = e2->succ_next)
1332     {
1333       if (e1->flags & EDGE_EH)
1334         nehedges1++;
1335
1336       if (e2->flags & EDGE_EH)
1337         nehedges2++;
1338
1339       if (e1->flags & EDGE_FALLTHRU)
1340         fallthru1 = e1;
1341       if (e2->flags & EDGE_FALLTHRU)
1342         fallthru2 = e2;
1343     }
1344
1345   /* If number of edges of various types does not match, fail.  */
1346   if (e1 || e2
1347       || nehedges1 != nehedges2
1348       || (fallthru1 != 0) != (fallthru2 != 0))
1349     return false;
1350
1351   /* fallthru edges must be forwarded to the same destination.  */
1352   if (fallthru1)
1353     {
1354       basic_block d1 = (forwarder_block_p (fallthru1->dest)
1355                         ? fallthru1->dest->succ->dest: fallthru1->dest);
1356       basic_block d2 = (forwarder_block_p (fallthru2->dest)
1357                         ? fallthru2->dest->succ->dest: fallthru2->dest);
1358
1359       if (d1 != d2)
1360         return false;
1361     }
1362
1363   /* Ensure the same EH region.  */
1364   {
1365     rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1366     rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1367
1368     if (!n1 && n2)
1369       return false;
1370
1371     if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1372       return false;
1373   }
1374
1375   /* We don't need to match the rest of edges as above checks should be enough
1376      to ensure that they are equivalent.  */
1377   return true;
1378 }
1379
1380 /* E1 and E2 are edges with the same destination block.  Search their
1381    predecessors for common code.  If found, redirect control flow from
1382    (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC.  */
1383
1384 static bool
1385 try_crossjump_to_edge (int mode, edge e1, edge e2)
1386 {
1387   int nmatch;
1388   basic_block src1 = e1->src, src2 = e2->src;
1389   basic_block redirect_to, redirect_from, to_remove;
1390   rtx newpos1, newpos2;
1391   edge s;
1392
1393   /* Search backward through forwarder blocks.  We don't need to worry
1394      about multiple entry or chained forwarders, as they will be optimized
1395      away.  We do this to look past the unconditional jump following a
1396      conditional jump that is required due to the current CFG shape.  */
1397   if (src1->pred
1398       && !src1->pred->pred_next
1399       && FORWARDER_BLOCK_P (src1))
1400     e1 = src1->pred, src1 = e1->src;
1401
1402   if (src2->pred
1403       && !src2->pred->pred_next
1404       && FORWARDER_BLOCK_P (src2))
1405     e2 = src2->pred, src2 = e2->src;
1406
1407   /* Nothing to do if we reach ENTRY, or a common source block.  */
1408   if (src1 == ENTRY_BLOCK_PTR || src2 == ENTRY_BLOCK_PTR)
1409     return false;
1410   if (src1 == src2)
1411     return false;
1412
1413   /* Seeing more than 1 forwarder blocks would confuse us later...  */
1414   if (FORWARDER_BLOCK_P (e1->dest)
1415       && FORWARDER_BLOCK_P (e1->dest->succ->dest))
1416     return false;
1417
1418   if (FORWARDER_BLOCK_P (e2->dest)
1419       && FORWARDER_BLOCK_P (e2->dest->succ->dest))
1420     return false;
1421
1422   /* Likewise with dead code (possibly newly created by the other optimizations
1423      of cfg_cleanup).  */
1424   if (!src1->pred || !src2->pred)
1425     return false;
1426
1427   /* Look for the common insn sequence, part the first ...  */
1428   if (!outgoing_edges_match (mode, src1, src2))
1429     return false;
1430
1431   /* ... and part the second.  */
1432   nmatch = flow_find_cross_jump (mode, src1, src2, &newpos1, &newpos2);
1433   if (!nmatch)
1434     return false;
1435
1436 #ifndef CASE_DROPS_THROUGH
1437   /* Here we know that the insns in the end of SRC1 which are common with SRC2
1438      will be deleted.
1439      If we have tablejumps in the end of SRC1 and SRC2
1440      they have been already compared for equivalence in outgoing_edges_match ()
1441      so replace the references to TABLE1 by references to TABLE2.  */
1442     {
1443       rtx label1, label2;
1444       rtx table1, table2;
1445
1446       if (tablejump_p (BB_END (src1), &label1, &table1)
1447           && tablejump_p (BB_END (src2), &label2, &table2)
1448           && label1 != label2)
1449         {
1450           replace_label_data rr;
1451           rtx insn;
1452
1453           /* Replace references to LABEL1 with LABEL2.  */
1454           rr.r1 = label1;
1455           rr.r2 = label2;
1456           rr.update_label_nuses = true;
1457           for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
1458             {
1459               /* Do not replace the label in SRC1->END because when deleting
1460                  a block whose end is a tablejump, the tablejump referenced
1461                  from the instruction is deleted too.  */
1462               if (insn != BB_END (src1))
1463                 for_each_rtx (&insn, replace_label, &rr);
1464             }
1465         }
1466     }
1467 #endif
1468
1469   /* Avoid splitting if possible.  */
1470   if (newpos2 == BB_HEAD (src2))
1471     redirect_to = src2;
1472   else
1473     {
1474       if (rtl_dump_file)
1475         fprintf (rtl_dump_file, "Splitting bb %i before %i insns\n",
1476                  src2->index, nmatch);
1477       redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
1478     }
1479
1480   if (rtl_dump_file)
1481     fprintf (rtl_dump_file,
1482              "Cross jumping from bb %i to bb %i; %i common insns\n",
1483              src1->index, src2->index, nmatch);
1484
1485   redirect_to->count += src1->count;
1486   redirect_to->frequency += src1->frequency;
1487   /* We may have some registers visible trought the block.  */
1488   redirect_to->flags |= BB_DIRTY;
1489
1490   /* Recompute the frequencies and counts of outgoing edges.  */
1491   for (s = redirect_to->succ; s; s = s->succ_next)
1492     {
1493       edge s2;
1494       basic_block d = s->dest;
1495
1496       if (FORWARDER_BLOCK_P (d))
1497         d = d->succ->dest;
1498
1499       for (s2 = src1->succ; ; s2 = s2->succ_next)
1500         {
1501           basic_block d2 = s2->dest;
1502           if (FORWARDER_BLOCK_P (d2))
1503             d2 = d2->succ->dest;
1504           if (d == d2)
1505             break;
1506         }
1507
1508       s->count += s2->count;
1509
1510       /* Take care to update possible forwarder blocks.  We verified
1511          that there is no more than one in the chain, so we can't run
1512          into infinite loop.  */
1513       if (FORWARDER_BLOCK_P (s->dest))
1514         {
1515           s->dest->succ->count += s2->count;
1516           s->dest->count += s2->count;
1517           s->dest->frequency += EDGE_FREQUENCY (s);
1518         }
1519
1520       if (FORWARDER_BLOCK_P (s2->dest))
1521         {
1522           s2->dest->succ->count -= s2->count;
1523           if (s2->dest->succ->count < 0)
1524             s2->dest->succ->count = 0;
1525           s2->dest->count -= s2->count;
1526           s2->dest->frequency -= EDGE_FREQUENCY (s);
1527           if (s2->dest->frequency < 0)
1528             s2->dest->frequency = 0;
1529           if (s2->dest->count < 0)
1530             s2->dest->count = 0;
1531         }
1532
1533       if (!redirect_to->frequency && !src1->frequency)
1534         s->probability = (s->probability + s2->probability) / 2;
1535       else
1536         s->probability
1537           = ((s->probability * redirect_to->frequency +
1538               s2->probability * src1->frequency)
1539              / (redirect_to->frequency + src1->frequency));
1540     }
1541
1542   update_br_prob_note (redirect_to);
1543
1544   /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1.  */
1545
1546   /* Skip possible basic block header.  */
1547   if (GET_CODE (newpos1) == CODE_LABEL)
1548     newpos1 = NEXT_INSN (newpos1);
1549
1550   if (GET_CODE (newpos1) == NOTE)
1551     newpos1 = NEXT_INSN (newpos1);
1552
1553   redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
1554   to_remove = redirect_from->succ->dest;
1555
1556   redirect_edge_and_branch_force (redirect_from->succ, redirect_to);
1557   delete_block (to_remove);
1558
1559   update_forwarder_flag (redirect_from);
1560
1561   return true;
1562 }
1563
1564 /* Search the predecessors of BB for common insn sequences.  When found,
1565    share code between them by redirecting control flow.  Return true if
1566    any changes made.  */
1567
1568 static bool
1569 try_crossjump_bb (int mode, basic_block bb)
1570 {
1571   edge e, e2, nexte2, nexte, fallthru;
1572   bool changed;
1573   int n = 0, max;
1574
1575   /* Nothing to do if there is not at least two incoming edges.  */
1576   if (!bb->pred || !bb->pred->pred_next)
1577     return false;
1578
1579   /* It is always cheapest to redirect a block that ends in a branch to
1580      a block that falls through into BB, as that adds no branches to the
1581      program.  We'll try that combination first.  */
1582   fallthru = NULL;
1583   max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
1584   for (e = bb->pred; e ; e = e->pred_next, n++)
1585     {
1586       if (e->flags & EDGE_FALLTHRU)
1587         fallthru = e;
1588       if (n > max)
1589         return false;
1590     }
1591
1592   changed = false;
1593   for (e = bb->pred; e; e = nexte)
1594     {
1595       nexte = e->pred_next;
1596
1597       /* As noted above, first try with the fallthru predecessor.  */
1598       if (fallthru)
1599         {
1600           /* Don't combine the fallthru edge into anything else.
1601              If there is a match, we'll do it the other way around.  */
1602           if (e == fallthru)
1603             continue;
1604
1605           if (try_crossjump_to_edge (mode, e, fallthru))
1606             {
1607               changed = true;
1608               nexte = bb->pred;
1609               continue;
1610             }
1611         }
1612
1613       /* Non-obvious work limiting check: Recognize that we're going
1614          to call try_crossjump_bb on every basic block.  So if we have
1615          two blocks with lots of outgoing edges (a switch) and they
1616          share lots of common destinations, then we would do the
1617          cross-jump check once for each common destination.
1618
1619          Now, if the blocks actually are cross-jump candidates, then
1620          all of their destinations will be shared.  Which means that
1621          we only need check them for cross-jump candidacy once.  We
1622          can eliminate redundant checks of crossjump(A,B) by arbitrarily
1623          choosing to do the check from the block for which the edge
1624          in question is the first successor of A.  */
1625       if (e->src->succ != e)
1626         continue;
1627
1628       for (e2 = bb->pred; e2; e2 = nexte2)
1629         {
1630           nexte2 = e2->pred_next;
1631
1632           if (e2 == e)
1633             continue;
1634
1635           /* We've already checked the fallthru edge above.  */
1636           if (e2 == fallthru)
1637             continue;
1638
1639           /* The "first successor" check above only prevents multiple
1640              checks of crossjump(A,B).  In order to prevent redundant
1641              checks of crossjump(B,A), require that A be the block
1642              with the lowest index.  */
1643           if (e->src->index > e2->src->index)
1644             continue;
1645
1646           if (try_crossjump_to_edge (mode, e, e2))
1647             {
1648               changed = true;
1649               nexte = bb->pred;
1650               break;
1651             }
1652         }
1653     }
1654
1655   return changed;
1656 }
1657
1658 /* Do simple CFG optimizations - basic block merging, simplifying of jump
1659    instructions etc.  Return nonzero if changes were made.  */
1660
1661 static bool
1662 try_optimize_cfg (int mode)
1663 {
1664   bool changed_overall = false;
1665   bool changed;
1666   int iterations = 0;
1667   basic_block bb, b, next;
1668
1669   if (mode & CLEANUP_CROSSJUMP)
1670     add_noreturn_fake_exit_edges ();
1671
1672   FOR_EACH_BB (bb)
1673     update_forwarder_flag (bb);
1674
1675   if (mode & CLEANUP_UPDATE_LIFE)
1676     clear_bb_flags ();
1677
1678   if (! (* targetm.cannot_modify_jumps_p) ())
1679     {
1680       /* Attempt to merge blocks as made possible by edge removal.  If
1681          a block has only one successor, and the successor has only
1682          one predecessor, they may be combined.  */
1683       do
1684         {
1685           changed = false;
1686           iterations++;
1687
1688           if (rtl_dump_file)
1689             fprintf (rtl_dump_file,
1690                      "\n\ntry_optimize_cfg iteration %i\n\n",
1691                      iterations);
1692
1693           for (b = ENTRY_BLOCK_PTR->next_bb; b != EXIT_BLOCK_PTR;)
1694             {
1695               basic_block c;
1696               edge s;
1697               bool changed_here = false;
1698
1699               /* Delete trivially dead basic blocks.  */
1700               while (b->pred == NULL)
1701                 {
1702                   c = b->prev_bb;
1703                   if (rtl_dump_file)
1704                     fprintf (rtl_dump_file, "Deleting block %i.\n",
1705                              b->index);
1706
1707                   delete_block (b);
1708                   if (!(mode & CLEANUP_CFGLAYOUT))
1709                     changed = true;
1710                   b = c;
1711                 }
1712
1713               /* Remove code labels no longer used.  Don't do this
1714                  before CALL_PLACEHOLDER is removed, as some branches
1715                  may be hidden within.  */
1716               if (b->pred->pred_next == NULL
1717                   && (b->pred->flags & EDGE_FALLTHRU)
1718                   && !(b->pred->flags & EDGE_COMPLEX)
1719                   && GET_CODE (BB_HEAD (b)) == CODE_LABEL
1720                   && (!(mode & CLEANUP_PRE_SIBCALL)
1721                       || !tail_recursion_label_p (BB_HEAD (b)))
1722                   /* If the previous block ends with a branch to this
1723                      block, we can't delete the label.  Normally this
1724                      is a condjump that is yet to be simplified, but
1725                      if CASE_DROPS_THRU, this can be a tablejump with
1726                      some element going to the same place as the
1727                      default (fallthru).  */
1728                   && (b->pred->src == ENTRY_BLOCK_PTR
1729                       || GET_CODE (BB_END (b->pred->src)) != JUMP_INSN
1730                       || ! label_is_jump_target_p (BB_HEAD (b),
1731                                                    BB_END (b->pred->src))))
1732                 {
1733                   rtx label = BB_HEAD (b);
1734
1735                   delete_insn_chain (label, label);
1736                   /* In the case label is undeletable, move it after the
1737                      BASIC_BLOCK note.  */
1738                   if (NOTE_LINE_NUMBER (BB_HEAD (b)) == NOTE_INSN_DELETED_LABEL)
1739                     {
1740                       rtx bb_note = NEXT_INSN (BB_HEAD (b));
1741
1742                       reorder_insns_nobb (label, label, bb_note);
1743                       BB_HEAD (b) = bb_note;
1744                     }
1745                   if (rtl_dump_file)
1746                     fprintf (rtl_dump_file, "Deleted label in block %i.\n",
1747                              b->index);
1748                 }
1749
1750               /* If we fall through an empty block, we can remove it.  */
1751               if (!(mode & CLEANUP_CFGLAYOUT)
1752                   && b->pred->pred_next == NULL
1753                   && (b->pred->flags & EDGE_FALLTHRU)
1754                   && GET_CODE (BB_HEAD (b)) != CODE_LABEL
1755                   && FORWARDER_BLOCK_P (b)
1756                   /* Note that forwarder_block_p true ensures that
1757                      there is a successor for this block.  */
1758                   && (b->succ->flags & EDGE_FALLTHRU)
1759                   && n_basic_blocks > 1)
1760                 {
1761                   if (rtl_dump_file)
1762                     fprintf (rtl_dump_file,
1763                              "Deleting fallthru block %i.\n",
1764                              b->index);
1765
1766                   c = b->prev_bb == ENTRY_BLOCK_PTR ? b->next_bb : b->prev_bb;
1767                   redirect_edge_succ_nodup (b->pred, b->succ->dest);
1768                   delete_block (b);
1769                   changed = true;
1770                   b = c;
1771                 }
1772
1773               if ((s = b->succ) != NULL
1774                   && s->succ_next == NULL
1775                   && !(s->flags & EDGE_COMPLEX)
1776                   && (c = s->dest) != EXIT_BLOCK_PTR
1777                   && c->pred->pred_next == NULL
1778                   && b != c)
1779                 {
1780                   /* When not in cfg_layout mode use code aware of reordering
1781                      INSN.  This code possibly creates new basic blocks so it
1782                      does not fit merge_blocks interface and is kept here in
1783                      hope that it will become useless once more of compiler
1784                      is transformed to use cfg_layout mode.  */
1785                      
1786                   if ((mode & CLEANUP_CFGLAYOUT)
1787                       && can_merge_blocks_p (b, c))
1788                     {
1789                       merge_blocks (b, c);
1790                       update_forwarder_flag (b);
1791                       changed_here = true;
1792                     }
1793                   else if (!(mode & CLEANUP_CFGLAYOUT)
1794                            /* If the jump insn has side effects,
1795                               we can't kill the edge.  */
1796                            && (GET_CODE (BB_END (b)) != JUMP_INSN
1797                                || (flow2_completed
1798                                    ? simplejump_p (BB_END (b))
1799                                    : onlyjump_p (BB_END (b))))
1800                            && (next = merge_blocks_move (s, b, c, mode)))
1801                       {
1802                         b = next;
1803                         changed_here = true;
1804                       }
1805                 }
1806
1807               /* Simplify branch over branch.  */
1808               if ((mode & CLEANUP_EXPENSIVE)
1809                    && !(mode & CLEANUP_CFGLAYOUT)
1810                    && try_simplify_condjump (b))
1811                 changed_here = true;
1812
1813               /* If B has a single outgoing edge, but uses a
1814                  non-trivial jump instruction without side-effects, we
1815                  can either delete the jump entirely, or replace it
1816                  with a simple unconditional jump.  Use
1817                  redirect_edge_and_branch to do the dirty work.  */
1818               if (b->succ
1819                   && ! b->succ->succ_next
1820                   && b->succ->dest != EXIT_BLOCK_PTR
1821                   && onlyjump_p (BB_END (b))
1822                   && redirect_edge_and_branch (b->succ, b->succ->dest))
1823                 {
1824                   update_forwarder_flag (b);
1825                   changed_here = true;
1826                 }
1827
1828               /* Simplify branch to branch.  */
1829               if (try_forward_edges (mode, b))
1830                 changed_here = true;
1831
1832               /* Look for shared code between blocks.  */
1833               if ((mode & CLEANUP_CROSSJUMP)
1834                   && try_crossjump_bb (mode, b))
1835                 changed_here = true;
1836
1837               /* Don't get confused by the index shift caused by
1838                  deleting blocks.  */
1839               if (!changed_here)
1840                 b = b->next_bb;
1841               else
1842                 changed = true;
1843             }
1844
1845           if ((mode & CLEANUP_CROSSJUMP)
1846               && try_crossjump_bb (mode, EXIT_BLOCK_PTR))
1847             changed = true;
1848
1849 #ifdef ENABLE_CHECKING
1850           if (changed)
1851             verify_flow_info ();
1852 #endif
1853
1854           changed_overall |= changed;
1855         }
1856       while (changed);
1857     }
1858
1859   if (mode & CLEANUP_CROSSJUMP)
1860     remove_fake_edges ();
1861
1862   clear_aux_for_blocks ();
1863
1864   return changed_overall;
1865 }
1866 \f
1867 /* Delete all unreachable basic blocks.  */
1868
1869 bool
1870 delete_unreachable_blocks (void)
1871 {
1872   bool changed = false;
1873   basic_block b, next_bb;
1874
1875   find_unreachable_blocks ();
1876
1877   /* Delete all unreachable basic blocks.  */
1878
1879   for (b = ENTRY_BLOCK_PTR->next_bb; b != EXIT_BLOCK_PTR; b = next_bb)
1880     {
1881       next_bb = b->next_bb;
1882
1883       if (!(b->flags & BB_REACHABLE))
1884         {
1885           delete_block (b);
1886           changed = true;
1887         }
1888     }
1889
1890   if (changed)
1891     tidy_fallthru_edges ();
1892   return changed;
1893 }
1894 \f
1895 /* Tidy the CFG by deleting unreachable code and whatnot.  */
1896
1897 bool
1898 cleanup_cfg (int mode)
1899 {
1900   bool changed = false;
1901
1902   timevar_push (TV_CLEANUP_CFG);
1903   if (delete_unreachable_blocks ())
1904     {
1905       changed = true;
1906       /* We've possibly created trivially dead code.  Cleanup it right
1907          now to introduce more opportunities for try_optimize_cfg.  */
1908       if (!(mode & (CLEANUP_NO_INSN_DEL
1909                     | CLEANUP_UPDATE_LIFE | CLEANUP_PRE_SIBCALL))
1910           && !reload_completed)
1911         delete_trivially_dead_insns (get_insns(), max_reg_num ());
1912     }
1913
1914   compact_blocks ();
1915
1916   while (try_optimize_cfg (mode))
1917     {
1918       delete_unreachable_blocks (), changed = true;
1919       if (mode & CLEANUP_UPDATE_LIFE)
1920         {
1921           /* Cleaning up CFG introduces more opportunities for dead code
1922              removal that in turn may introduce more opportunities for
1923              cleaning up the CFG.  */
1924           if (!update_life_info_in_dirty_blocks (UPDATE_LIFE_GLOBAL_RM_NOTES,
1925                                                  PROP_DEATH_NOTES
1926                                                  | PROP_SCAN_DEAD_CODE
1927                                                  | PROP_KILL_DEAD_CODE
1928                                                  | PROP_LOG_LINKS))
1929             break;
1930         }
1931       else if (!(mode & (CLEANUP_NO_INSN_DEL | CLEANUP_PRE_SIBCALL))
1932                && (mode & CLEANUP_EXPENSIVE)
1933                && !reload_completed)
1934         {
1935           if (!delete_trivially_dead_insns (get_insns(), max_reg_num ()))
1936             break;
1937         }
1938       else
1939         break;
1940       delete_dead_jumptables ();
1941     }
1942
1943   /* Kill the data we won't maintain.  */
1944   free_EXPR_LIST_list (&label_value_list);
1945   timevar_pop (TV_CLEANUP_CFG);
1946
1947   return changed;
1948 }