OSDN Git Service

Daily bump.
[pf3gnuchains/gcc-fork.git] / gcc / tree-cfg.c
1 /* Control flow functions for trees.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License 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
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "rtl.h"
28 #include "tm_p.h"
29 #include "hard-reg-set.h"
30 #include "basic-block.h"
31 #include "output.h"
32 #include "errors.h"
33 #include "flags.h"
34 #include "function.h"
35 #include "expr.h"
36 #include "ggc.h"
37 #include "langhooks.h"
38 #include "diagnostic.h"
39 #include "tree-flow.h"
40 #include "timevar.h"
41 #include "tree-dump.h"
42 #include "tree-pass.h"
43 #include "toplev.h"
44 #include "except.h"
45 #include "cfgloop.h"
46 #include "cfglayout.h"
47 #include "hashtab.h"
48
49 /* This file contains functions for building the Control Flow Graph (CFG)
50    for a function tree.  */
51
52 /* Local declarations.  */
53
54 /* Initial capacity for the basic block array.  */
55 static const int initial_cfg_capacity = 20;
56
57 /* Mapping of labels to their associated blocks.  This can greatly speed up
58    building of the CFG in code with lots of gotos.  */
59 static GTY(()) varray_type label_to_block_map;
60
61 /* This hash table allows us to efficiently lookup all CASE_LABEL_EXPRs
62    which use a particular edge.  The CASE_LABEL_EXPRs are chained together
63    via their TREE_CHAIN field, which we clear after we're done with the
64    hash table to prevent problems with duplication of SWITCH_EXPRs.
65
66    Access to this list of CASE_LABEL_EXPRs allows us to efficiently
67    update the case vector in response to edge redirections.
68
69    Right now this table is set up and torn down at key points in the
70    compilation process.  It would be nice if we could make the table
71    more persistent.  The key is getting notification of changes to
72    the CFG (particularly edge removal, creation and redirection).  */
73
74 struct edge_to_cases_elt
75 {
76   /* The edge itself.  Necessary for hashing and equality tests.  */
77   edge e;
78
79   /* The case labels associated with this edge.  We link these up via
80      their TREE_CHAIN field, then we wipe out the TREE_CHAIN fields
81      when we destroy the hash table.  This prevents problems when copying
82      SWITCH_EXPRs.  */
83   tree case_labels;
84 };
85
86 static htab_t edge_to_cases;
87
88 /* CFG statistics.  */
89 struct cfg_stats_d
90 {
91   long num_merged_labels;
92 };
93
94 static struct cfg_stats_d cfg_stats;
95
96 /* Nonzero if we found a computed goto while building basic blocks.  */
97 static bool found_computed_goto;
98
99 /* Basic blocks and flowgraphs.  */
100 static basic_block create_bb (void *, void *, basic_block);
101 static void create_block_annotation (basic_block);
102 static void free_blocks_annotations (void);
103 static void clear_blocks_annotations (void);
104 static void make_blocks (tree);
105 static void factor_computed_gotos (void);
106
107 /* Edges.  */
108 static void make_edges (void);
109 static void make_ctrl_stmt_edges (basic_block);
110 static void make_exit_edges (basic_block);
111 static void make_cond_expr_edges (basic_block);
112 static void make_switch_expr_edges (basic_block);
113 static void make_goto_expr_edges (basic_block);
114 static edge tree_redirect_edge_and_branch (edge, basic_block);
115 static edge tree_try_redirect_by_replacing_jump (edge, basic_block);
116 static void split_critical_edges (void);
117 static bool remove_fallthru_edge (VEC(edge) *);
118
119 /* Various helpers.  */
120 static inline bool stmt_starts_bb_p (tree, tree);
121 static int tree_verify_flow_info (void);
122 static void tree_make_forwarder_block (edge);
123 static bool tree_forwarder_block_p (basic_block, bool);
124 static void tree_cfg2vcg (FILE *);
125
126 /* Flowgraph optimization and cleanup.  */
127 static void tree_merge_blocks (basic_block, basic_block);
128 static bool tree_can_merge_blocks_p (basic_block, basic_block);
129 static void remove_bb (basic_block);
130 static bool cleanup_control_flow (void);
131 static bool cleanup_control_expr_graph (basic_block, block_stmt_iterator);
132 static edge find_taken_edge_computed_goto (basic_block, tree);
133 static edge find_taken_edge_cond_expr (basic_block, tree);
134 static edge find_taken_edge_switch_expr (basic_block, tree);
135 static tree find_case_label_for_value (tree, tree);
136 static bool phi_alternatives_equal (basic_block, edge, edge);
137 static bool cleanup_forwarder_blocks (void);
138
139
140 /*---------------------------------------------------------------------------
141                               Create basic blocks
142 ---------------------------------------------------------------------------*/
143
144 /* Entry point to the CFG builder for trees.  TP points to the list of
145    statements to be added to the flowgraph.  */
146
147 static void
148 build_tree_cfg (tree *tp)
149 {
150   /* Register specific tree functions.  */
151   tree_register_cfg_hooks ();
152
153   /* Initialize rbi_pool.  */
154   alloc_rbi_pool ();
155
156   /* Initialize the basic block array.  */
157   init_flow ();
158   profile_status = PROFILE_ABSENT;
159   n_basic_blocks = 0;
160   last_basic_block = 0;
161   VARRAY_BB_INIT (basic_block_info, initial_cfg_capacity, "basic_block_info");
162   memset ((void *) &cfg_stats, 0, sizeof (cfg_stats));
163
164   /* Build a mapping of labels to their associated blocks.  */
165   VARRAY_BB_INIT (label_to_block_map, initial_cfg_capacity,
166                   "label to block map");
167
168   ENTRY_BLOCK_PTR->next_bb = EXIT_BLOCK_PTR;
169   EXIT_BLOCK_PTR->prev_bb = ENTRY_BLOCK_PTR;
170
171   found_computed_goto = 0;
172   make_blocks (*tp);
173
174   /* Computed gotos are hell to deal with, especially if there are
175      lots of them with a large number of destinations.  So we factor
176      them to a common computed goto location before we build the
177      edge list.  After we convert back to normal form, we will un-factor
178      the computed gotos since factoring introduces an unwanted jump.  */
179   if (found_computed_goto)
180     factor_computed_gotos ();
181
182   /* Make sure there is always at least one block, even if it's empty.  */
183   if (n_basic_blocks == 0)
184     create_empty_bb (ENTRY_BLOCK_PTR);
185
186   create_block_annotation (ENTRY_BLOCK_PTR);
187   create_block_annotation (EXIT_BLOCK_PTR);
188   
189   /* Adjust the size of the array.  */
190   VARRAY_GROW (basic_block_info, n_basic_blocks);
191
192   /* To speed up statement iterator walks, we first purge dead labels.  */
193   cleanup_dead_labels ();
194
195   /* Group case nodes to reduce the number of edges.
196      We do this after cleaning up dead labels because otherwise we miss
197      a lot of obvious case merging opportunities.  */
198   group_case_labels ();
199
200   /* Create the edges of the flowgraph.  */
201   make_edges ();
202
203   /* Debugging dumps.  */
204
205   /* Write the flowgraph to a VCG file.  */
206   {
207     int local_dump_flags;
208     FILE *dump_file = dump_begin (TDI_vcg, &local_dump_flags);
209     if (dump_file)
210       {
211         tree_cfg2vcg (dump_file);
212         dump_end (TDI_vcg, dump_file);
213       }
214   }
215
216   /* Dump a textual representation of the flowgraph.  */
217   if (dump_file)
218     dump_tree_cfg (dump_file, dump_flags);
219 }
220
221 static void
222 execute_build_cfg (void)
223 {
224   build_tree_cfg (&DECL_SAVED_TREE (current_function_decl));
225 }
226
227 struct tree_opt_pass pass_build_cfg =
228 {
229   "cfg",                                /* name */
230   NULL,                                 /* gate */
231   execute_build_cfg,                    /* execute */
232   NULL,                                 /* sub */
233   NULL,                                 /* next */
234   0,                                    /* static_pass_number */
235   TV_TREE_CFG,                          /* tv_id */
236   PROP_gimple_leh,                      /* properties_required */
237   PROP_cfg,                             /* properties_provided */
238   0,                                    /* properties_destroyed */
239   0,                                    /* todo_flags_start */
240   TODO_verify_stmts,                    /* todo_flags_finish */
241   0                                     /* letter */
242 };
243
244 /* Search the CFG for any computed gotos.  If found, factor them to a 
245    common computed goto site.  Also record the location of that site so
246    that we can un-factor the gotos after we have converted back to 
247    normal form.  */
248
249 static void
250 factor_computed_gotos (void)
251 {
252   basic_block bb;
253   tree factored_label_decl = NULL;
254   tree var = NULL;
255   tree factored_computed_goto_label = NULL;
256   tree factored_computed_goto = NULL;
257
258   /* We know there are one or more computed gotos in this function.
259      Examine the last statement in each basic block to see if the block
260      ends with a computed goto.  */
261         
262   FOR_EACH_BB (bb)
263     {
264       block_stmt_iterator bsi = bsi_last (bb);
265       tree last;
266
267       if (bsi_end_p (bsi))
268         continue;
269       last = bsi_stmt (bsi);
270
271       /* Ignore the computed goto we create when we factor the original
272          computed gotos.  */
273       if (last == factored_computed_goto)
274         continue;
275
276       /* If the last statement is a computed goto, factor it.  */
277       if (computed_goto_p (last))
278         {
279           tree assignment;
280
281           /* The first time we find a computed goto we need to create
282              the factored goto block and the variable each original
283              computed goto will use for their goto destination.  */
284           if (! factored_computed_goto)
285             {
286               basic_block new_bb = create_empty_bb (bb);
287               block_stmt_iterator new_bsi = bsi_start (new_bb);
288
289               /* Create the destination of the factored goto.  Each original
290                  computed goto will put its desired destination into this
291                  variable and jump to the label we create immediately
292                  below.  */
293               var = create_tmp_var (ptr_type_node, "gotovar");
294
295               /* Build a label for the new block which will contain the
296                  factored computed goto.  */
297               factored_label_decl = create_artificial_label ();
298               factored_computed_goto_label
299                 = build1 (LABEL_EXPR, void_type_node, factored_label_decl);
300               bsi_insert_after (&new_bsi, factored_computed_goto_label,
301                                 BSI_NEW_STMT);
302
303               /* Build our new computed goto.  */
304               factored_computed_goto = build1 (GOTO_EXPR, void_type_node, var);
305               bsi_insert_after (&new_bsi, factored_computed_goto,
306                                 BSI_NEW_STMT);
307             }
308
309           /* Copy the original computed goto's destination into VAR.  */
310           assignment = build (MODIFY_EXPR, ptr_type_node,
311                               var, GOTO_DESTINATION (last));
312           bsi_insert_before (&bsi, assignment, BSI_SAME_STMT);
313
314           /* And re-vector the computed goto to the new destination.  */
315           GOTO_DESTINATION (last) = factored_label_decl;
316         }
317     }
318 }
319
320
321 /* Create annotations for a single basic block.  */
322
323 static void
324 create_block_annotation (basic_block bb)
325 {
326   /* Verify that the tree_annotations field is clear.  */
327   gcc_assert (!bb->tree_annotations);
328   bb->tree_annotations = ggc_alloc_cleared (sizeof (struct bb_ann_d));
329 }
330
331
332 /* Free the annotations for all the basic blocks.  */
333
334 static void free_blocks_annotations (void)
335 {
336   clear_blocks_annotations ();  
337 }
338
339
340 /* Clear the annotations for all the basic blocks.  */
341
342 static void
343 clear_blocks_annotations (void)
344 {
345   basic_block bb;
346
347   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
348     bb->tree_annotations = NULL;
349 }
350
351
352 /* Build a flowgraph for the statement_list STMT_LIST.  */
353
354 static void
355 make_blocks (tree stmt_list)
356 {
357   tree_stmt_iterator i = tsi_start (stmt_list);
358   tree stmt = NULL;
359   bool start_new_block = true;
360   bool first_stmt_of_list = true;
361   basic_block bb = ENTRY_BLOCK_PTR;
362
363   while (!tsi_end_p (i))
364     {
365       tree prev_stmt;
366
367       prev_stmt = stmt;
368       stmt = tsi_stmt (i);
369
370       /* If the statement starts a new basic block or if we have determined
371          in a previous pass that we need to create a new block for STMT, do
372          so now.  */
373       if (start_new_block || stmt_starts_bb_p (stmt, prev_stmt))
374         {
375           if (!first_stmt_of_list)
376             stmt_list = tsi_split_statement_list_before (&i);
377           bb = create_basic_block (stmt_list, NULL, bb);
378           start_new_block = false;
379         }
380
381       /* Now add STMT to BB and create the subgraphs for special statement
382          codes.  */
383       set_bb_for_stmt (stmt, bb);
384
385       if (computed_goto_p (stmt))
386         found_computed_goto = true;
387
388       /* If STMT is a basic block terminator, set START_NEW_BLOCK for the
389          next iteration.  */
390       if (stmt_ends_bb_p (stmt))
391         start_new_block = true;
392
393       tsi_next (&i);
394       first_stmt_of_list = false;
395     }
396 }
397
398
399 /* Create and return a new empty basic block after bb AFTER.  */
400
401 static basic_block
402 create_bb (void *h, void *e, basic_block after)
403 {
404   basic_block bb;
405
406   gcc_assert (!e);
407
408   /* Create and initialize a new basic block.  Since alloc_block uses
409      ggc_alloc_cleared to allocate a basic block, we do not have to
410      clear the newly allocated basic block here.  */
411   bb = alloc_block ();
412
413   bb->index = last_basic_block;
414   bb->flags = BB_NEW;
415   bb->stmt_list = h ? h : alloc_stmt_list ();
416
417   /* Add the new block to the linked list of blocks.  */
418   link_block (bb, after);
419
420   /* Grow the basic block array if needed.  */
421   if ((size_t) last_basic_block == VARRAY_SIZE (basic_block_info))
422     {
423       size_t new_size = last_basic_block + (last_basic_block + 3) / 4;
424       VARRAY_GROW (basic_block_info, new_size);
425     }
426
427   /* Add the newly created block to the array.  */
428   BASIC_BLOCK (last_basic_block) = bb;
429
430   create_block_annotation (bb);
431
432   n_basic_blocks++;
433   last_basic_block++;
434
435   initialize_bb_rbi (bb);
436   return bb;
437 }
438
439
440 /*---------------------------------------------------------------------------
441                                  Edge creation
442 ---------------------------------------------------------------------------*/
443
444 /* Fold COND_EXPR_COND of each COND_EXPR.  */
445
446 static void
447 fold_cond_expr_cond (void)
448 {
449   basic_block bb;
450
451   FOR_EACH_BB (bb)
452     {
453       tree stmt = last_stmt (bb);
454
455       if (stmt
456           && TREE_CODE (stmt) == COND_EXPR)
457         {
458           tree cond = fold (COND_EXPR_COND (stmt));
459           if (integer_zerop (cond))
460             COND_EXPR_COND (stmt) = boolean_false_node;
461           else if (integer_onep (cond))
462             COND_EXPR_COND (stmt) = boolean_true_node;
463         }
464     }
465 }
466
467 /* Join all the blocks in the flowgraph.  */
468
469 static void
470 make_edges (void)
471 {
472   basic_block bb;
473
474   /* Create an edge from entry to the first block with executable
475      statements in it.  */
476   make_edge (ENTRY_BLOCK_PTR, BASIC_BLOCK (0), EDGE_FALLTHRU);
477
478   /* Traverse the basic block array placing edges.  */
479   FOR_EACH_BB (bb)
480     {
481       tree first = first_stmt (bb);
482       tree last = last_stmt (bb);
483
484       if (first)
485         {
486           /* Edges for statements that always alter flow control.  */
487           if (is_ctrl_stmt (last))
488             make_ctrl_stmt_edges (bb);
489
490           /* Edges for statements that sometimes alter flow control.  */
491           if (is_ctrl_altering_stmt (last))
492             make_exit_edges (bb);
493         }
494
495       /* Finally, if no edges were created above, this is a regular
496          basic block that only needs a fallthru edge.  */
497       if (EDGE_COUNT (bb->succs) == 0)
498         make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
499     }
500
501   /* We do not care about fake edges, so remove any that the CFG
502      builder inserted for completeness.  */
503   remove_fake_exit_edges ();
504
505   /* Fold COND_EXPR_COND of each COND_EXPR.  */
506   fold_cond_expr_cond ();
507
508   /* Clean up the graph and warn for unreachable code.  */
509   cleanup_tree_cfg ();
510 }
511
512
513 /* Create edges for control statement at basic block BB.  */
514
515 static void
516 make_ctrl_stmt_edges (basic_block bb)
517 {
518   tree last = last_stmt (bb);
519
520   gcc_assert (last);
521   switch (TREE_CODE (last))
522     {
523     case GOTO_EXPR:
524       make_goto_expr_edges (bb);
525       break;
526
527     case RETURN_EXPR:
528       make_edge (bb, EXIT_BLOCK_PTR, 0);
529       break;
530
531     case COND_EXPR:
532       make_cond_expr_edges (bb);
533       break;
534
535     case SWITCH_EXPR:
536       make_switch_expr_edges (bb);
537       break;
538
539     case RESX_EXPR:
540       make_eh_edges (last);
541       /* Yet another NORETURN hack.  */
542       if (EDGE_COUNT (bb->succs) == 0)
543         make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
544       break;
545
546     default:
547       gcc_unreachable ();
548     }
549 }
550
551
552 /* Create exit edges for statements in block BB that alter the flow of
553    control.  Statements that alter the control flow are 'goto', 'return'
554    and calls to non-returning functions.  */
555
556 static void
557 make_exit_edges (basic_block bb)
558 {
559   tree last = last_stmt (bb), op;
560
561   gcc_assert (last);
562   switch (TREE_CODE (last))
563     {
564     case CALL_EXPR:
565       /* If this function receives a nonlocal goto, then we need to
566          make edges from this call site to all the nonlocal goto
567          handlers.  */
568       if (TREE_SIDE_EFFECTS (last)
569           && current_function_has_nonlocal_label)
570         make_goto_expr_edges (bb);
571
572       /* If this statement has reachable exception handlers, then
573          create abnormal edges to them.  */
574       make_eh_edges (last);
575
576       /* Some calls are known not to return.  For such calls we create
577          a fake edge.
578
579          We really need to revamp how we build edges so that it's not
580          such a bloody pain to avoid creating edges for this case since
581          all we do is remove these edges when we're done building the
582          CFG.  */
583       if (call_expr_flags (last) & ECF_NORETURN)
584         {
585           make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
586           return;
587         }
588
589       /* Don't forget the fall-thru edge.  */
590       make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
591       break;
592
593     case MODIFY_EXPR:
594       /* A MODIFY_EXPR may have a CALL_EXPR on its RHS and the CALL_EXPR
595          may have an abnormal edge.  Search the RHS for this case and
596          create any required edges.  */
597       op = get_call_expr_in (last);
598       if (op && TREE_SIDE_EFFECTS (op)
599           && current_function_has_nonlocal_label)
600         make_goto_expr_edges (bb);
601
602       make_eh_edges (last);
603       make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
604       break;
605
606     default:
607       gcc_unreachable ();
608     }
609 }
610
611
612 /* Create the edges for a COND_EXPR starting at block BB.
613    At this point, both clauses must contain only simple gotos.  */
614
615 static void
616 make_cond_expr_edges (basic_block bb)
617 {
618   tree entry = last_stmt (bb);
619   basic_block then_bb, else_bb;
620   tree then_label, else_label;
621
622   gcc_assert (entry);
623   gcc_assert (TREE_CODE (entry) == COND_EXPR);
624
625   /* Entry basic blocks for each component.  */
626   then_label = GOTO_DESTINATION (COND_EXPR_THEN (entry));
627   else_label = GOTO_DESTINATION (COND_EXPR_ELSE (entry));
628   then_bb = label_to_block (then_label);
629   else_bb = label_to_block (else_label);
630
631   make_edge (bb, then_bb, EDGE_TRUE_VALUE);
632   make_edge (bb, else_bb, EDGE_FALSE_VALUE);
633 }
634
635 /* Hashing routine for EDGE_TO_CASES.  */
636
637 static hashval_t
638 edge_to_cases_hash (const void *p)
639 {
640   edge e = ((struct edge_to_cases_elt *)p)->e;
641
642   /* Hash on the edge itself (which is a pointer).  */
643   return htab_hash_pointer (e);
644 }
645
646 /* Equality routine for EDGE_TO_CASES, edges are unique, so testing
647    for equality is just a pointer comparison.  */
648
649 static int
650 edge_to_cases_eq (const void *p1, const void *p2)
651 {
652   edge e1 = ((struct edge_to_cases_elt *)p1)->e;
653   edge e2 = ((struct edge_to_cases_elt *)p2)->e;
654
655   return e1 == e2;
656 }
657
658 /* Called for each element in the hash table (P) as we delete the
659    edge to cases hash table.
660
661    Clear all the TREE_CHAINs to prevent problems with copying of 
662    SWITCH_EXPRs and structure sharing rules, then free the hash table
663    element.  */
664
665 static void
666 edge_to_cases_cleanup (void *p)
667 {
668   struct edge_to_cases_elt *elt = p;
669   tree t, next;
670
671   for (t = elt->case_labels; t; t = next)
672     {
673       next = TREE_CHAIN (t);
674       TREE_CHAIN (t) = NULL;
675     }
676   free (p);
677 }
678
679 /* Start recording information mapping edges to case labels.  */
680
681 static void
682 start_recording_case_labels (void)
683 {
684   gcc_assert (edge_to_cases == NULL);
685
686   edge_to_cases = htab_create (37,
687                                edge_to_cases_hash,
688                                edge_to_cases_eq,
689                                edge_to_cases_cleanup);
690 }
691
692 /* Return nonzero if we are recording information for case labels.  */
693
694 static bool
695 recording_case_labels_p (void)
696 {
697   return (edge_to_cases != NULL);
698 }
699
700 /* Stop recording information mapping edges to case labels and
701    remove any information we have recorded.  */
702 static void
703 end_recording_case_labels (void)
704 {
705   htab_delete (edge_to_cases);
706   edge_to_cases = NULL;
707 }
708
709 /* Record that CASE_LABEL (a CASE_LABEL_EXPR) references edge E.  */
710
711 static void
712 record_switch_edge (edge e, tree case_label)
713 {
714   struct edge_to_cases_elt *elt;
715   void **slot;
716
717   /* Build a hash table element so we can see if E is already
718      in the table.  */
719   elt = xmalloc (sizeof (struct edge_to_cases_elt));
720   elt->e = e;
721   elt->case_labels = case_label;
722
723   slot = htab_find_slot (edge_to_cases, elt, INSERT);
724
725   if (*slot == NULL)
726     {
727       /* E was not in the hash table.  Install E into the hash table.  */
728       *slot = (void *)elt;
729     }
730   else
731     {
732       /* E was already in the hash table.  Free ELT as we do not need it
733          anymore.  */
734       free (elt);
735
736       /* Get the entry stored in the hash table.  */
737       elt = (struct edge_to_cases_elt *) *slot;
738
739       /* Add it to the chain of CASE_LABEL_EXPRs referencing E.  */
740       TREE_CHAIN (case_label) = elt->case_labels;
741       elt->case_labels = case_label;
742     }
743 }
744
745 /* If we are inside a {start,end}_recording_cases block, then return
746    a chain of CASE_LABEL_EXPRs from T which reference E.
747
748    Otherwise return NULL.  */
749
750 static tree
751 get_cases_for_edge (edge e, tree t)
752 {
753   struct edge_to_cases_elt elt, *elt_p;
754   void **slot;
755   size_t i, n;
756   tree vec;
757
758   /* If we are not recording cases, then we do not have CASE_LABEL_EXPR
759      chains available.  Return NULL so the caller can detect this case.  */
760   if (!recording_case_labels_p ())
761     return NULL;
762   
763 restart:
764   elt.e = e;
765   elt.case_labels = NULL;
766   slot = htab_find_slot (edge_to_cases, &elt, NO_INSERT);
767
768   if (slot)
769     {
770       elt_p = (struct edge_to_cases_elt *)*slot;
771       return elt_p->case_labels;
772     }
773
774   /* If we did not find E in the hash table, then this must be the first
775      time we have been queried for information about E & T.  Add all the
776      elements from T to the hash table then perform the query again.  */
777
778   vec = SWITCH_LABELS (t);
779   n = TREE_VEC_LENGTH (vec);
780   for (i = 0; i < n; i++)
781     {
782       tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
783       basic_block label_bb = label_to_block (lab);
784       record_switch_edge (find_edge (e->src, label_bb), TREE_VEC_ELT (vec, i));
785     }
786   goto restart;
787 }
788
789 /* Create the edges for a SWITCH_EXPR starting at block BB.
790    At this point, the switch body has been lowered and the
791    SWITCH_LABELS filled in, so this is in effect a multi-way branch.  */
792
793 static void
794 make_switch_expr_edges (basic_block bb)
795 {
796   tree entry = last_stmt (bb);
797   size_t i, n;
798   tree vec;
799
800   vec = SWITCH_LABELS (entry);
801   n = TREE_VEC_LENGTH (vec);
802
803   for (i = 0; i < n; ++i)
804     {
805       tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
806       basic_block label_bb = label_to_block (lab);
807       make_edge (bb, label_bb, 0);
808     }
809 }
810
811
812 /* Return the basic block holding label DEST.  */
813
814 basic_block
815 label_to_block (tree dest)
816 {
817   int uid = LABEL_DECL_UID (dest);
818
819   /* We would die hard when faced by an undefined label.  Emit a label to
820      the very first basic block.  This will hopefully make even the dataflow
821      and undefined variable warnings quite right.  */
822   if ((errorcount || sorrycount) && uid < 0)
823     {
824       block_stmt_iterator bsi = bsi_start (BASIC_BLOCK (0));
825       tree stmt;
826
827       stmt = build1 (LABEL_EXPR, void_type_node, dest);
828       bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
829       uid = LABEL_DECL_UID (dest);
830     }
831   return VARRAY_BB (label_to_block_map, uid);
832 }
833
834
835 /* Create edges for a goto statement at block BB.  */
836
837 static void
838 make_goto_expr_edges (basic_block bb)
839 {
840   tree goto_t;
841   basic_block target_bb;
842   int for_call;
843   block_stmt_iterator last = bsi_last (bb);
844
845   goto_t = bsi_stmt (last);
846
847   /* If the last statement is not a GOTO (i.e., it is a RETURN_EXPR,
848      CALL_EXPR or MODIFY_EXPR), then the edge is an abnormal edge resulting
849      from a nonlocal goto.  */
850   if (TREE_CODE (goto_t) != GOTO_EXPR)
851     for_call = 1;
852   else
853     {
854       tree dest = GOTO_DESTINATION (goto_t);
855       for_call = 0;
856
857       /* A GOTO to a local label creates normal edges.  */
858       if (simple_goto_p (goto_t))
859         {
860           edge e = make_edge (bb, label_to_block (dest), EDGE_FALLTHRU);
861 #ifdef USE_MAPPED_LOCATION
862           e->goto_locus = EXPR_LOCATION (goto_t);
863 #else
864           e->goto_locus = EXPR_LOCUS (goto_t);
865 #endif
866           bsi_remove (&last);
867           return;
868         }
869
870       /* Nothing more to do for nonlocal gotos.  */
871       if (TREE_CODE (dest) == LABEL_DECL)
872         return;
873
874       /* Computed gotos remain.  */
875     }
876
877   /* Look for the block starting with the destination label.  In the
878      case of a computed goto, make an edge to any label block we find
879      in the CFG.  */
880   FOR_EACH_BB (target_bb)
881     {
882       block_stmt_iterator bsi;
883
884       for (bsi = bsi_start (target_bb); !bsi_end_p (bsi); bsi_next (&bsi))
885         {
886           tree target = bsi_stmt (bsi);
887
888           if (TREE_CODE (target) != LABEL_EXPR)
889             break;
890
891           if (
892               /* Computed GOTOs.  Make an edge to every label block that has
893                  been marked as a potential target for a computed goto.  */
894               (FORCED_LABEL (LABEL_EXPR_LABEL (target)) && for_call == 0)
895               /* Nonlocal GOTO target.  Make an edge to every label block
896                  that has been marked as a potential target for a nonlocal
897                  goto.  */
898               || (DECL_NONLOCAL (LABEL_EXPR_LABEL (target)) && for_call == 1))
899             {
900               make_edge (bb, target_bb, EDGE_ABNORMAL);
901               break;
902             }
903         }
904     }
905
906   /* Degenerate case of computed goto with no labels.  */
907   if (!for_call && EDGE_COUNT (bb->succs) == 0)
908     make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
909 }
910
911
912 /*---------------------------------------------------------------------------
913                                Flowgraph analysis
914 ---------------------------------------------------------------------------*/
915
916 /* Remove unreachable blocks and other miscellaneous clean up work.  */
917
918 bool
919 cleanup_tree_cfg (void)
920 {
921   bool retval = false;
922
923   timevar_push (TV_TREE_CLEANUP_CFG);
924
925   retval = cleanup_control_flow ();
926   retval |= delete_unreachable_blocks ();
927
928   /* cleanup_forwarder_blocks can redirect edges out of SWITCH_EXPRs,
929      which can get expensive.  So we want to enable recording of edge
930      to CASE_LABEL_EXPR mappings around the call to
931      cleanup_forwarder_blocks.  */
932   start_recording_case_labels ();
933   retval |= cleanup_forwarder_blocks ();
934   end_recording_case_labels ();
935
936 #ifdef ENABLE_CHECKING
937   if (retval)
938     {
939       gcc_assert (!cleanup_control_flow ());
940       gcc_assert (!delete_unreachable_blocks ());
941       gcc_assert (!cleanup_forwarder_blocks ());
942     }
943 #endif
944
945   /* Merging the blocks creates no new opportunities for the other
946      optimizations, so do it here.  */
947   retval |= merge_seq_blocks ();
948
949   compact_blocks ();
950
951 #ifdef ENABLE_CHECKING
952   verify_flow_info ();
953 #endif
954   timevar_pop (TV_TREE_CLEANUP_CFG);
955   return retval;
956 }
957
958
959 /* Cleanup cfg and repair loop structures.  */
960
961 void
962 cleanup_tree_cfg_loop (void)
963 {
964   bitmap changed_bbs = BITMAP_ALLOC (NULL);
965
966   cleanup_tree_cfg ();
967
968   fix_loop_structure (current_loops, changed_bbs);
969   calculate_dominance_info (CDI_DOMINATORS);
970
971   /* This usually does nothing.  But sometimes parts of cfg that originally
972      were inside a loop get out of it due to edge removal (since they
973      become unreachable by back edges from latch).  */
974   rewrite_into_loop_closed_ssa (changed_bbs);
975
976   BITMAP_FREE (changed_bbs);
977
978 #ifdef ENABLE_CHECKING
979   verify_loop_structure (current_loops);
980 #endif
981 }
982
983 /* Cleanup useless labels in basic blocks.  This is something we wish
984    to do early because it allows us to group case labels before creating
985    the edges for the CFG, and it speeds up block statement iterators in
986    all passes later on.
987    We only run this pass once, running it more than once is probably not
988    profitable.  */
989
990 /* A map from basic block index to the leading label of that block.  */
991 static tree *label_for_bb;
992
993 /* Callback for for_each_eh_region.  Helper for cleanup_dead_labels.  */
994 static void
995 update_eh_label (struct eh_region *region)
996 {
997   tree old_label = get_eh_region_tree_label (region);
998   if (old_label)
999     {
1000       tree new_label;
1001       basic_block bb = label_to_block (old_label);
1002
1003       /* ??? After optimizing, there may be EH regions with labels
1004          that have already been removed from the function body, so
1005          there is no basic block for them.  */
1006       if (! bb)
1007         return;
1008
1009       new_label = label_for_bb[bb->index];
1010       set_eh_region_tree_label (region, new_label);
1011     }
1012 }
1013
1014 /* Given LABEL return the first label in the same basic block.  */
1015 static tree
1016 main_block_label (tree label)
1017 {
1018   basic_block bb = label_to_block (label);
1019
1020   /* label_to_block possibly inserted undefined label into the chain.  */
1021   if (!label_for_bb[bb->index])
1022     label_for_bb[bb->index] = label;
1023   return label_for_bb[bb->index];
1024 }
1025
1026 /* Cleanup redundant labels.  This is a three-step process:
1027      1) Find the leading label for each block.
1028      2) Redirect all references to labels to the leading labels.
1029      3) Cleanup all useless labels.  */
1030
1031 void
1032 cleanup_dead_labels (void)
1033 {
1034   basic_block bb;
1035   label_for_bb = xcalloc (last_basic_block, sizeof (tree));
1036
1037   /* Find a suitable label for each block.  We use the first user-defined
1038      label if there is one, or otherwise just the first label we see.  */
1039   FOR_EACH_BB (bb)
1040     {
1041       block_stmt_iterator i;
1042
1043       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
1044         {
1045           tree label, stmt = bsi_stmt (i);
1046
1047           if (TREE_CODE (stmt) != LABEL_EXPR)
1048             break;
1049
1050           label = LABEL_EXPR_LABEL (stmt);
1051
1052           /* If we have not yet seen a label for the current block,
1053              remember this one and see if there are more labels.  */
1054           if (! label_for_bb[bb->index])
1055             {
1056               label_for_bb[bb->index] = label;
1057               continue;
1058             }
1059
1060           /* If we did see a label for the current block already, but it
1061              is an artificially created label, replace it if the current
1062              label is a user defined label.  */
1063           if (! DECL_ARTIFICIAL (label)
1064               && DECL_ARTIFICIAL (label_for_bb[bb->index]))
1065             {
1066               label_for_bb[bb->index] = label;
1067               break;
1068             }
1069         }
1070     }
1071
1072   /* Now redirect all jumps/branches to the selected label.
1073      First do so for each block ending in a control statement.  */
1074   FOR_EACH_BB (bb)
1075     {
1076       tree stmt = last_stmt (bb);
1077       if (!stmt)
1078         continue;
1079
1080       switch (TREE_CODE (stmt))
1081         {
1082         case COND_EXPR:
1083           {
1084             tree true_branch, false_branch;
1085
1086             true_branch = COND_EXPR_THEN (stmt);
1087             false_branch = COND_EXPR_ELSE (stmt);
1088
1089             GOTO_DESTINATION (true_branch)
1090               = main_block_label (GOTO_DESTINATION (true_branch));
1091             GOTO_DESTINATION (false_branch)
1092               = main_block_label (GOTO_DESTINATION (false_branch));
1093
1094             break;
1095           }
1096   
1097         case SWITCH_EXPR:
1098           {
1099             size_t i;
1100             tree vec = SWITCH_LABELS (stmt);
1101             size_t n = TREE_VEC_LENGTH (vec);
1102   
1103             /* Replace all destination labels.  */
1104             for (i = 0; i < n; ++i)
1105               {
1106                 tree elt = TREE_VEC_ELT (vec, i);
1107                 tree label = main_block_label (CASE_LABEL (elt));
1108                 CASE_LABEL (elt) = label;
1109               }
1110             break;
1111           }
1112
1113         /* We have to handle GOTO_EXPRs until they're removed, and we don't
1114            remove them until after we've created the CFG edges.  */
1115         case GOTO_EXPR:
1116           if (! computed_goto_p (stmt))
1117             {
1118               GOTO_DESTINATION (stmt)
1119                 = main_block_label (GOTO_DESTINATION (stmt));
1120               break;
1121             }
1122
1123         default:
1124           break;
1125       }
1126     }
1127
1128   for_each_eh_region (update_eh_label);
1129
1130   /* Finally, purge dead labels.  All user-defined labels and labels that
1131      can be the target of non-local gotos are preserved.  */
1132   FOR_EACH_BB (bb)
1133     {
1134       block_stmt_iterator i;
1135       tree label_for_this_bb = label_for_bb[bb->index];
1136
1137       if (! label_for_this_bb)
1138         continue;
1139
1140       for (i = bsi_start (bb); !bsi_end_p (i); )
1141         {
1142           tree label, stmt = bsi_stmt (i);
1143
1144           if (TREE_CODE (stmt) != LABEL_EXPR)
1145             break;
1146
1147           label = LABEL_EXPR_LABEL (stmt);
1148
1149           if (label == label_for_this_bb
1150               || ! DECL_ARTIFICIAL (label)
1151               || DECL_NONLOCAL (label))
1152             bsi_next (&i);
1153           else
1154             bsi_remove (&i);
1155         }
1156     }
1157
1158   free (label_for_bb);
1159 }
1160
1161 /* Look for blocks ending in a multiway branch (a SWITCH_EXPR in GIMPLE),
1162    and scan the sorted vector of cases.  Combine the ones jumping to the
1163    same label.
1164    Eg. three separate entries 1: 2: 3: become one entry 1..3:  */
1165
1166 void
1167 group_case_labels (void)
1168 {
1169   basic_block bb;
1170
1171   FOR_EACH_BB (bb)
1172     {
1173       tree stmt = last_stmt (bb);
1174       if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
1175         {
1176           tree labels = SWITCH_LABELS (stmt);
1177           int old_size = TREE_VEC_LENGTH (labels);
1178           int i, j, new_size = old_size;
1179           tree default_case = TREE_VEC_ELT (labels, old_size - 1);
1180           tree default_label;
1181
1182           /* The default label is always the last case in a switch
1183              statement after gimplification.  */
1184           default_label = CASE_LABEL (default_case);
1185
1186           /* Look for possible opportunities to merge cases.
1187              Ignore the last element of the label vector because it
1188              must be the default case.  */
1189           i = 0;
1190           while (i < old_size - 1)
1191             {
1192               tree base_case, base_label, base_high;
1193               base_case = TREE_VEC_ELT (labels, i);
1194
1195               gcc_assert (base_case);
1196               base_label = CASE_LABEL (base_case);
1197
1198               /* Discard cases that have the same destination as the
1199                  default case.  */
1200               if (base_label == default_label)
1201                 {
1202                   TREE_VEC_ELT (labels, i) = NULL_TREE;
1203                   i++;
1204                   new_size--;
1205                   continue;
1206                 }
1207
1208               base_high = CASE_HIGH (base_case) ?
1209                 CASE_HIGH (base_case) : CASE_LOW (base_case);
1210               i++;
1211               /* Try to merge case labels.  Break out when we reach the end
1212                  of the label vector or when we cannot merge the next case
1213                  label with the current one.  */
1214               while (i < old_size - 1)
1215                 {
1216                   tree merge_case = TREE_VEC_ELT (labels, i);
1217                   tree merge_label = CASE_LABEL (merge_case);
1218                   tree t = int_const_binop (PLUS_EXPR, base_high,
1219                                             integer_one_node, 1);
1220
1221                   /* Merge the cases if they jump to the same place,
1222                      and their ranges are consecutive.  */
1223                   if (merge_label == base_label
1224                       && tree_int_cst_equal (CASE_LOW (merge_case), t))
1225                     {
1226                       base_high = CASE_HIGH (merge_case) ?
1227                         CASE_HIGH (merge_case) : CASE_LOW (merge_case);
1228                       CASE_HIGH (base_case) = base_high;
1229                       TREE_VEC_ELT (labels, i) = NULL_TREE;
1230                       new_size--;
1231                       i++;
1232                     }
1233                   else
1234                     break;
1235                 }
1236             }
1237
1238           /* Compress the case labels in the label vector, and adjust the
1239              length of the vector.  */
1240           for (i = 0, j = 0; i < new_size; i++)
1241             {
1242               while (! TREE_VEC_ELT (labels, j))
1243                 j++;
1244               TREE_VEC_ELT (labels, i) = TREE_VEC_ELT (labels, j++);
1245             }
1246           TREE_VEC_LENGTH (labels) = new_size;
1247         }
1248     }
1249 }
1250
1251 /* Checks whether we can merge block B into block A.  */
1252
1253 static bool
1254 tree_can_merge_blocks_p (basic_block a, basic_block b)
1255 {
1256   tree stmt;
1257   block_stmt_iterator bsi;
1258
1259   if (!single_succ_p (a))
1260     return false;
1261
1262   if (single_succ_edge (a)->flags & EDGE_ABNORMAL)
1263     return false;
1264
1265   if (single_succ (a) != b)
1266     return false;
1267
1268   if (!single_pred_p (b))
1269     return false;
1270
1271   if (b == EXIT_BLOCK_PTR)
1272     return false;
1273   
1274   /* If A ends by a statement causing exceptions or something similar, we
1275      cannot merge the blocks.  */
1276   stmt = last_stmt (a);
1277   if (stmt && stmt_ends_bb_p (stmt))
1278     return false;
1279
1280   /* Do not allow a block with only a non-local label to be merged.  */
1281   if (stmt && TREE_CODE (stmt) == LABEL_EXPR
1282       && DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
1283     return false;
1284
1285   /* There may be no phi nodes at the start of b.  Most of these degenerate
1286      phi nodes should be cleaned up by kill_redundant_phi_nodes.  */
1287   if (phi_nodes (b))
1288     return false;
1289
1290   /* Do not remove user labels.  */
1291   for (bsi = bsi_start (b); !bsi_end_p (bsi); bsi_next (&bsi))
1292     {
1293       stmt = bsi_stmt (bsi);
1294       if (TREE_CODE (stmt) != LABEL_EXPR)
1295         break;
1296       if (!DECL_ARTIFICIAL (LABEL_EXPR_LABEL (stmt)))
1297         return false;
1298     }
1299
1300   /* Protect the loop latches.  */
1301   if (current_loops
1302       && b->loop_father->latch == b)
1303     return false;
1304
1305   return true;
1306 }
1307
1308
1309 /* Merge block B into block A.  */
1310
1311 static void
1312 tree_merge_blocks (basic_block a, basic_block b)
1313 {
1314   block_stmt_iterator bsi;
1315   tree_stmt_iterator last;
1316
1317   if (dump_file)
1318     fprintf (dump_file, "Merging blocks %d and %d\n", a->index, b->index);
1319
1320   /* Ensure that B follows A.  */
1321   move_block_after (b, a);
1322
1323   gcc_assert (single_succ_edge (a)->flags & EDGE_FALLTHRU);
1324   gcc_assert (!last_stmt (a) || !stmt_ends_bb_p (last_stmt (a)));
1325
1326   /* Remove labels from B and set bb_for_stmt to A for other statements.  */
1327   for (bsi = bsi_start (b); !bsi_end_p (bsi);)
1328     {
1329       if (TREE_CODE (bsi_stmt (bsi)) == LABEL_EXPR)
1330         {
1331           tree label = bsi_stmt (bsi);
1332
1333           bsi_remove (&bsi);
1334           /* Now that we can thread computed gotos, we might have
1335              a situation where we have a forced label in block B
1336              However, the label at the start of block B might still be
1337              used in other ways (think about the runtime checking for
1338              Fortran assigned gotos).  So we can not just delete the
1339              label.  Instead we move the label to the start of block A.  */
1340           if (FORCED_LABEL (LABEL_EXPR_LABEL (label)))
1341             {
1342               block_stmt_iterator dest_bsi = bsi_start (a);
1343               bsi_insert_before (&dest_bsi, label, BSI_NEW_STMT);
1344             }
1345         }
1346       else
1347         {
1348           set_bb_for_stmt (bsi_stmt (bsi), a);
1349           bsi_next (&bsi);
1350         }
1351     }
1352
1353   /* Merge the chains.  */
1354   last = tsi_last (a->stmt_list);
1355   tsi_link_after (&last, b->stmt_list, TSI_NEW_STMT);
1356   b->stmt_list = NULL;
1357 }
1358
1359
1360 /* Walk the function tree removing unnecessary statements.
1361
1362      * Empty statement nodes are removed
1363
1364      * Unnecessary TRY_FINALLY and TRY_CATCH blocks are removed
1365
1366      * Unnecessary COND_EXPRs are removed
1367
1368      * Some unnecessary BIND_EXPRs are removed
1369
1370    Clearly more work could be done.  The trick is doing the analysis
1371    and removal fast enough to be a net improvement in compile times.
1372
1373    Note that when we remove a control structure such as a COND_EXPR
1374    BIND_EXPR, or TRY block, we will need to repeat this optimization pass
1375    to ensure we eliminate all the useless code.  */
1376
1377 struct rus_data
1378 {
1379   tree *last_goto;
1380   bool repeat;
1381   bool may_throw;
1382   bool may_branch;
1383   bool has_label;
1384 };
1385
1386 static void remove_useless_stmts_1 (tree *, struct rus_data *);
1387
1388 static bool
1389 remove_useless_stmts_warn_notreached (tree stmt)
1390 {
1391   if (EXPR_HAS_LOCATION (stmt))
1392     {
1393       location_t loc = EXPR_LOCATION (stmt);
1394       if (LOCATION_LINE (loc) > 0)
1395         {
1396           warning ("%Hwill never be executed", &loc);
1397           return true;
1398         }
1399     }
1400
1401   switch (TREE_CODE (stmt))
1402     {
1403     case STATEMENT_LIST:
1404       {
1405         tree_stmt_iterator i;
1406         for (i = tsi_start (stmt); !tsi_end_p (i); tsi_next (&i))
1407           if (remove_useless_stmts_warn_notreached (tsi_stmt (i)))
1408             return true;
1409       }
1410       break;
1411
1412     case COND_EXPR:
1413       if (remove_useless_stmts_warn_notreached (COND_EXPR_COND (stmt)))
1414         return true;
1415       if (remove_useless_stmts_warn_notreached (COND_EXPR_THEN (stmt)))
1416         return true;
1417       if (remove_useless_stmts_warn_notreached (COND_EXPR_ELSE (stmt)))
1418         return true;
1419       break;
1420
1421     case TRY_FINALLY_EXPR:
1422     case TRY_CATCH_EXPR:
1423       if (remove_useless_stmts_warn_notreached (TREE_OPERAND (stmt, 0)))
1424         return true;
1425       if (remove_useless_stmts_warn_notreached (TREE_OPERAND (stmt, 1)))
1426         return true;
1427       break;
1428
1429     case CATCH_EXPR:
1430       return remove_useless_stmts_warn_notreached (CATCH_BODY (stmt));
1431     case EH_FILTER_EXPR:
1432       return remove_useless_stmts_warn_notreached (EH_FILTER_FAILURE (stmt));
1433     case BIND_EXPR:
1434       return remove_useless_stmts_warn_notreached (BIND_EXPR_BLOCK (stmt));
1435
1436     default:
1437       /* Not a live container.  */
1438       break;
1439     }
1440
1441   return false;
1442 }
1443
1444 static void
1445 remove_useless_stmts_cond (tree *stmt_p, struct rus_data *data)
1446 {
1447   tree then_clause, else_clause, cond;
1448   bool save_has_label, then_has_label, else_has_label;
1449
1450   save_has_label = data->has_label;
1451   data->has_label = false;
1452   data->last_goto = NULL;
1453
1454   remove_useless_stmts_1 (&COND_EXPR_THEN (*stmt_p), data);
1455
1456   then_has_label = data->has_label;
1457   data->has_label = false;
1458   data->last_goto = NULL;
1459
1460   remove_useless_stmts_1 (&COND_EXPR_ELSE (*stmt_p), data);
1461
1462   else_has_label = data->has_label;
1463   data->has_label = save_has_label | then_has_label | else_has_label;
1464
1465   then_clause = COND_EXPR_THEN (*stmt_p);
1466   else_clause = COND_EXPR_ELSE (*stmt_p);
1467   cond = fold (COND_EXPR_COND (*stmt_p));
1468
1469   /* If neither arm does anything at all, we can remove the whole IF.  */
1470   if (!TREE_SIDE_EFFECTS (then_clause) && !TREE_SIDE_EFFECTS (else_clause))
1471     {
1472       *stmt_p = build_empty_stmt ();
1473       data->repeat = true;
1474     }
1475
1476   /* If there are no reachable statements in an arm, then we can
1477      zap the entire conditional.  */
1478   else if (integer_nonzerop (cond) && !else_has_label)
1479     {
1480       if (warn_notreached)
1481         remove_useless_stmts_warn_notreached (else_clause);
1482       *stmt_p = then_clause;
1483       data->repeat = true;
1484     }
1485   else if (integer_zerop (cond) && !then_has_label)
1486     {
1487       if (warn_notreached)
1488         remove_useless_stmts_warn_notreached (then_clause);
1489       *stmt_p = else_clause;
1490       data->repeat = true;
1491     }
1492
1493   /* Check a couple of simple things on then/else with single stmts.  */
1494   else
1495     {
1496       tree then_stmt = expr_only (then_clause);
1497       tree else_stmt = expr_only (else_clause);
1498
1499       /* Notice branches to a common destination.  */
1500       if (then_stmt && else_stmt
1501           && TREE_CODE (then_stmt) == GOTO_EXPR
1502           && TREE_CODE (else_stmt) == GOTO_EXPR
1503           && (GOTO_DESTINATION (then_stmt) == GOTO_DESTINATION (else_stmt)))
1504         {
1505           *stmt_p = then_stmt;
1506           data->repeat = true;
1507         }
1508
1509       /* If the THEN/ELSE clause merely assigns a value to a variable or
1510          parameter which is already known to contain that value, then
1511          remove the useless THEN/ELSE clause.  */
1512       else if (TREE_CODE (cond) == VAR_DECL || TREE_CODE (cond) == PARM_DECL)
1513         {
1514           if (else_stmt
1515               && TREE_CODE (else_stmt) == MODIFY_EXPR
1516               && TREE_OPERAND (else_stmt, 0) == cond
1517               && integer_zerop (TREE_OPERAND (else_stmt, 1)))
1518             COND_EXPR_ELSE (*stmt_p) = alloc_stmt_list ();
1519         }
1520       else if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1521                && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1522                    || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL)
1523                && TREE_CONSTANT (TREE_OPERAND (cond, 1)))
1524         {
1525           tree stmt = (TREE_CODE (cond) == EQ_EXPR
1526                        ? then_stmt : else_stmt);
1527           tree *location = (TREE_CODE (cond) == EQ_EXPR
1528                             ? &COND_EXPR_THEN (*stmt_p)
1529                             : &COND_EXPR_ELSE (*stmt_p));
1530
1531           if (stmt
1532               && TREE_CODE (stmt) == MODIFY_EXPR
1533               && TREE_OPERAND (stmt, 0) == TREE_OPERAND (cond, 0)
1534               && TREE_OPERAND (stmt, 1) == TREE_OPERAND (cond, 1))
1535             *location = alloc_stmt_list ();
1536         }
1537     }
1538
1539   /* Protect GOTOs in the arm of COND_EXPRs from being removed.  They
1540      would be re-introduced during lowering.  */
1541   data->last_goto = NULL;
1542 }
1543
1544
1545 static void
1546 remove_useless_stmts_tf (tree *stmt_p, struct rus_data *data)
1547 {
1548   bool save_may_branch, save_may_throw;
1549   bool this_may_branch, this_may_throw;
1550
1551   /* Collect may_branch and may_throw information for the body only.  */
1552   save_may_branch = data->may_branch;
1553   save_may_throw = data->may_throw;
1554   data->may_branch = false;
1555   data->may_throw = false;
1556   data->last_goto = NULL;
1557
1558   remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 0), data);
1559
1560   this_may_branch = data->may_branch;
1561   this_may_throw = data->may_throw;
1562   data->may_branch |= save_may_branch;
1563   data->may_throw |= save_may_throw;
1564   data->last_goto = NULL;
1565
1566   remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 1), data);
1567
1568   /* If the body is empty, then we can emit the FINALLY block without
1569      the enclosing TRY_FINALLY_EXPR.  */
1570   if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 0)))
1571     {
1572       *stmt_p = TREE_OPERAND (*stmt_p, 1);
1573       data->repeat = true;
1574     }
1575
1576   /* If the handler is empty, then we can emit the TRY block without
1577      the enclosing TRY_FINALLY_EXPR.  */
1578   else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 1)))
1579     {
1580       *stmt_p = TREE_OPERAND (*stmt_p, 0);
1581       data->repeat = true;
1582     }
1583
1584   /* If the body neither throws, nor branches, then we can safely
1585      string the TRY and FINALLY blocks together.  */
1586   else if (!this_may_branch && !this_may_throw)
1587     {
1588       tree stmt = *stmt_p;
1589       *stmt_p = TREE_OPERAND (stmt, 0);
1590       append_to_statement_list (TREE_OPERAND (stmt, 1), stmt_p);
1591       data->repeat = true;
1592     }
1593 }
1594
1595
1596 static void
1597 remove_useless_stmts_tc (tree *stmt_p, struct rus_data *data)
1598 {
1599   bool save_may_throw, this_may_throw;
1600   tree_stmt_iterator i;
1601   tree stmt;
1602
1603   /* Collect may_throw information for the body only.  */
1604   save_may_throw = data->may_throw;
1605   data->may_throw = false;
1606   data->last_goto = NULL;
1607
1608   remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 0), data);
1609
1610   this_may_throw = data->may_throw;
1611   data->may_throw = save_may_throw;
1612
1613   /* If the body cannot throw, then we can drop the entire TRY_CATCH_EXPR.  */
1614   if (!this_may_throw)
1615     {
1616       if (warn_notreached)
1617         remove_useless_stmts_warn_notreached (TREE_OPERAND (*stmt_p, 1));
1618       *stmt_p = TREE_OPERAND (*stmt_p, 0);
1619       data->repeat = true;
1620       return;
1621     }
1622
1623   /* Process the catch clause specially.  We may be able to tell that
1624      no exceptions propagate past this point.  */
1625
1626   this_may_throw = true;
1627   i = tsi_start (TREE_OPERAND (*stmt_p, 1));
1628   stmt = tsi_stmt (i);
1629   data->last_goto = NULL;
1630
1631   switch (TREE_CODE (stmt))
1632     {
1633     case CATCH_EXPR:
1634       for (; !tsi_end_p (i); tsi_next (&i))
1635         {
1636           stmt = tsi_stmt (i);
1637           /* If we catch all exceptions, then the body does not
1638              propagate exceptions past this point.  */
1639           if (CATCH_TYPES (stmt) == NULL)
1640             this_may_throw = false;
1641           data->last_goto = NULL;
1642           remove_useless_stmts_1 (&CATCH_BODY (stmt), data);
1643         }
1644       break;
1645
1646     case EH_FILTER_EXPR:
1647       if (EH_FILTER_MUST_NOT_THROW (stmt))
1648         this_may_throw = false;
1649       else if (EH_FILTER_TYPES (stmt) == NULL)
1650         this_may_throw = false;
1651       remove_useless_stmts_1 (&EH_FILTER_FAILURE (stmt), data);
1652       break;
1653
1654     default:
1655       /* Otherwise this is a cleanup.  */
1656       remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 1), data);
1657
1658       /* If the cleanup is empty, then we can emit the TRY block without
1659          the enclosing TRY_CATCH_EXPR.  */
1660       if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 1)))
1661         {
1662           *stmt_p = TREE_OPERAND (*stmt_p, 0);
1663           data->repeat = true;
1664         }
1665       break;
1666     }
1667   data->may_throw |= this_may_throw;
1668 }
1669
1670
1671 static void
1672 remove_useless_stmts_bind (tree *stmt_p, struct rus_data *data)
1673 {
1674   tree block;
1675
1676   /* First remove anything underneath the BIND_EXPR.  */
1677   remove_useless_stmts_1 (&BIND_EXPR_BODY (*stmt_p), data);
1678
1679   /* If the BIND_EXPR has no variables, then we can pull everything
1680      up one level and remove the BIND_EXPR, unless this is the toplevel
1681      BIND_EXPR for the current function or an inlined function.
1682
1683      When this situation occurs we will want to apply this
1684      optimization again.  */
1685   block = BIND_EXPR_BLOCK (*stmt_p);
1686   if (BIND_EXPR_VARS (*stmt_p) == NULL_TREE
1687       && *stmt_p != DECL_SAVED_TREE (current_function_decl)
1688       && (! block
1689           || ! BLOCK_ABSTRACT_ORIGIN (block)
1690           || (TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block))
1691               != FUNCTION_DECL)))
1692     {
1693       *stmt_p = BIND_EXPR_BODY (*stmt_p);
1694       data->repeat = true;
1695     }
1696 }
1697
1698
1699 static void
1700 remove_useless_stmts_goto (tree *stmt_p, struct rus_data *data)
1701 {
1702   tree dest = GOTO_DESTINATION (*stmt_p);
1703
1704   data->may_branch = true;
1705   data->last_goto = NULL;
1706
1707   /* Record the last goto expr, so that we can delete it if unnecessary.  */
1708   if (TREE_CODE (dest) == LABEL_DECL)
1709     data->last_goto = stmt_p;
1710 }
1711
1712
1713 static void
1714 remove_useless_stmts_label (tree *stmt_p, struct rus_data *data)
1715 {
1716   tree label = LABEL_EXPR_LABEL (*stmt_p);
1717
1718   data->has_label = true;
1719
1720   /* We do want to jump across non-local label receiver code.  */
1721   if (DECL_NONLOCAL (label))
1722     data->last_goto = NULL;
1723
1724   else if (data->last_goto && GOTO_DESTINATION (*data->last_goto) == label)
1725     {
1726       *data->last_goto = build_empty_stmt ();
1727       data->repeat = true;
1728     }
1729
1730   /* ??? Add something here to delete unused labels.  */
1731 }
1732
1733
1734 /* If the function is "const" or "pure", then clear TREE_SIDE_EFFECTS on its
1735    decl.  This allows us to eliminate redundant or useless
1736    calls to "const" functions. 
1737
1738    Gimplifier already does the same operation, but we may notice functions
1739    being const and pure once their calls has been gimplified, so we need
1740    to update the flag.  */
1741
1742 static void
1743 update_call_expr_flags (tree call)
1744 {
1745   tree decl = get_callee_fndecl (call);
1746   if (!decl)
1747     return;
1748   if (call_expr_flags (call) & (ECF_CONST | ECF_PURE))
1749     TREE_SIDE_EFFECTS (call) = 0;
1750   if (TREE_NOTHROW (decl))
1751     TREE_NOTHROW (call) = 1;
1752 }
1753
1754
1755 /* T is CALL_EXPR.  Set current_function_calls_* flags.  */
1756
1757 void
1758 notice_special_calls (tree t)
1759 {
1760   int flags = call_expr_flags (t);
1761
1762   if (flags & ECF_MAY_BE_ALLOCA)
1763     current_function_calls_alloca = true;
1764   if (flags & ECF_RETURNS_TWICE)
1765     current_function_calls_setjmp = true;
1766 }
1767
1768
1769 /* Clear flags set by notice_special_calls.  Used by dead code removal
1770    to update the flags.  */
1771
1772 void
1773 clear_special_calls (void)
1774 {
1775   current_function_calls_alloca = false;
1776   current_function_calls_setjmp = false;
1777 }
1778
1779
1780 static void
1781 remove_useless_stmts_1 (tree *tp, struct rus_data *data)
1782 {
1783   tree t = *tp, op;
1784
1785   switch (TREE_CODE (t))
1786     {
1787     case COND_EXPR:
1788       remove_useless_stmts_cond (tp, data);
1789       break;
1790
1791     case TRY_FINALLY_EXPR:
1792       remove_useless_stmts_tf (tp, data);
1793       break;
1794
1795     case TRY_CATCH_EXPR:
1796       remove_useless_stmts_tc (tp, data);
1797       break;
1798
1799     case BIND_EXPR:
1800       remove_useless_stmts_bind (tp, data);
1801       break;
1802
1803     case GOTO_EXPR:
1804       remove_useless_stmts_goto (tp, data);
1805       break;
1806
1807     case LABEL_EXPR:
1808       remove_useless_stmts_label (tp, data);
1809       break;
1810
1811     case RETURN_EXPR:
1812       fold_stmt (tp);
1813       data->last_goto = NULL;
1814       data->may_branch = true;
1815       break;
1816
1817     case CALL_EXPR:
1818       fold_stmt (tp);
1819       data->last_goto = NULL;
1820       notice_special_calls (t);
1821       update_call_expr_flags (t);
1822       if (tree_could_throw_p (t))
1823         data->may_throw = true;
1824       break;
1825
1826     case MODIFY_EXPR:
1827       data->last_goto = NULL;
1828       fold_stmt (tp);
1829       op = get_call_expr_in (t);
1830       if (op)
1831         {
1832           update_call_expr_flags (op);
1833           notice_special_calls (op);
1834         }
1835       if (tree_could_throw_p (t))
1836         data->may_throw = true;
1837       break;
1838
1839     case STATEMENT_LIST:
1840       {
1841         tree_stmt_iterator i = tsi_start (t);
1842         while (!tsi_end_p (i))
1843           {
1844             t = tsi_stmt (i);
1845             if (IS_EMPTY_STMT (t))
1846               {
1847                 tsi_delink (&i);
1848                 continue;
1849               }
1850             
1851             remove_useless_stmts_1 (tsi_stmt_ptr (i), data);
1852
1853             t = tsi_stmt (i);
1854             if (TREE_CODE (t) == STATEMENT_LIST)
1855               {
1856                 tsi_link_before (&i, t, TSI_SAME_STMT);
1857                 tsi_delink (&i);
1858               }
1859             else
1860               tsi_next (&i);
1861           }
1862       }
1863       break;
1864     case ASM_EXPR:
1865       fold_stmt (tp);
1866       data->last_goto = NULL;
1867       break;
1868
1869     default:
1870       data->last_goto = NULL;
1871       break;
1872     }
1873 }
1874
1875 static void
1876 remove_useless_stmts (void)
1877 {
1878   struct rus_data data;
1879
1880   clear_special_calls ();
1881
1882   do
1883     {
1884       memset (&data, 0, sizeof (data));
1885       remove_useless_stmts_1 (&DECL_SAVED_TREE (current_function_decl), &data);
1886     }
1887   while (data.repeat);
1888 }
1889
1890
1891 struct tree_opt_pass pass_remove_useless_stmts = 
1892 {
1893   "useless",                            /* name */
1894   NULL,                                 /* gate */
1895   remove_useless_stmts,                 /* execute */
1896   NULL,                                 /* sub */
1897   NULL,                                 /* next */
1898   0,                                    /* static_pass_number */
1899   0,                                    /* tv_id */
1900   PROP_gimple_any,                      /* properties_required */
1901   0,                                    /* properties_provided */
1902   0,                                    /* properties_destroyed */
1903   0,                                    /* todo_flags_start */
1904   TODO_dump_func,                       /* todo_flags_finish */
1905   0                                     /* letter */
1906 };
1907
1908
1909 /* Remove obviously useless statements in basic block BB.  */
1910
1911 static void
1912 cfg_remove_useless_stmts_bb (basic_block bb)
1913 {
1914   block_stmt_iterator bsi;
1915   tree stmt = NULL_TREE;
1916   tree cond, var = NULL_TREE, val = NULL_TREE;
1917   struct var_ann_d *ann;
1918
1919   /* Check whether we come here from a condition, and if so, get the
1920      condition.  */
1921   if (!single_pred_p (bb)
1922       || !(single_pred_edge (bb)->flags
1923            & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1924     return;
1925
1926   cond = COND_EXPR_COND (last_stmt (single_pred (bb)));
1927
1928   if (TREE_CODE (cond) == VAR_DECL || TREE_CODE (cond) == PARM_DECL)
1929     {
1930       var = cond;
1931       val = (single_pred_edge (bb)->flags & EDGE_FALSE_VALUE
1932              ? boolean_false_node : boolean_true_node);
1933     }
1934   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR
1935            && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1936                || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL))
1937     {
1938       var = TREE_OPERAND (cond, 0);
1939       val = (single_pred_edge (bb)->flags & EDGE_FALSE_VALUE
1940              ? boolean_true_node : boolean_false_node);
1941     }
1942   else
1943     {
1944       if (single_pred_edge (bb)->flags & EDGE_FALSE_VALUE)
1945         cond = invert_truthvalue (cond);
1946       if (TREE_CODE (cond) == EQ_EXPR
1947           && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1948               || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL)
1949           && (TREE_CODE (TREE_OPERAND (cond, 1)) == VAR_DECL
1950               || TREE_CODE (TREE_OPERAND (cond, 1)) == PARM_DECL
1951               || TREE_CONSTANT (TREE_OPERAND (cond, 1))))
1952         {
1953           var = TREE_OPERAND (cond, 0);
1954           val = TREE_OPERAND (cond, 1);
1955         }
1956       else
1957         return;
1958     }
1959
1960   /* Only work for normal local variables.  */
1961   ann = var_ann (var);
1962   if (!ann
1963       || ann->may_aliases
1964       || TREE_ADDRESSABLE (var))
1965     return;
1966
1967   if (! TREE_CONSTANT (val))
1968     {
1969       ann = var_ann (val);
1970       if (!ann
1971           || ann->may_aliases
1972           || TREE_ADDRESSABLE (val))
1973         return;
1974     }
1975
1976   /* Ignore floating point variables, since comparison behaves weird for
1977      them.  */
1978   if (FLOAT_TYPE_P (TREE_TYPE (var)))
1979     return;
1980
1981   for (bsi = bsi_start (bb); !bsi_end_p (bsi);)
1982     {
1983       stmt = bsi_stmt (bsi);
1984
1985       /* If the THEN/ELSE clause merely assigns a value to a variable/parameter
1986          which is already known to contain that value, then remove the useless
1987          THEN/ELSE clause.  */
1988       if (TREE_CODE (stmt) == MODIFY_EXPR
1989           && TREE_OPERAND (stmt, 0) == var
1990           && operand_equal_p (val, TREE_OPERAND (stmt, 1), 0))
1991         {
1992           bsi_remove (&bsi);
1993           continue;
1994         }
1995
1996       /* Invalidate the var if we encounter something that could modify it.
1997          Likewise for the value it was previously set to.  Note that we only
1998          consider values that are either a VAR_DECL or PARM_DECL so we
1999          can test for conflict very simply.  */
2000       if (TREE_CODE (stmt) == ASM_EXPR
2001           || (TREE_CODE (stmt) == MODIFY_EXPR
2002               && (TREE_OPERAND (stmt, 0) == var
2003                   || TREE_OPERAND (stmt, 0) == val)))
2004         return;
2005   
2006       bsi_next (&bsi);
2007     }
2008 }
2009
2010
2011 /* A CFG-aware version of remove_useless_stmts.  */
2012
2013 void
2014 cfg_remove_useless_stmts (void)
2015 {
2016   basic_block bb;
2017
2018 #ifdef ENABLE_CHECKING
2019   verify_flow_info ();
2020 #endif
2021
2022   FOR_EACH_BB (bb)
2023     {
2024       cfg_remove_useless_stmts_bb (bb);
2025     }
2026 }
2027
2028
2029 /* Remove PHI nodes associated with basic block BB and all edges out of BB.  */
2030
2031 static void
2032 remove_phi_nodes_and_edges_for_unreachable_block (basic_block bb)
2033 {
2034   tree phi;
2035
2036   /* Since this block is no longer reachable, we can just delete all
2037      of its PHI nodes.  */
2038   phi = phi_nodes (bb);
2039   while (phi)
2040     {
2041       tree next = PHI_CHAIN (phi);
2042       remove_phi_node (phi, NULL_TREE);
2043       phi = next;
2044     }
2045
2046   /* Remove edges to BB's successors.  */
2047   while (EDGE_COUNT (bb->succs) > 0)
2048     remove_edge (EDGE_SUCC (bb, 0));
2049 }
2050
2051
2052 /* Remove statements of basic block BB.  */
2053
2054 static void
2055 remove_bb (basic_block bb)
2056 {
2057   block_stmt_iterator i;
2058 #ifdef USE_MAPPED_LOCATION
2059   source_location loc = UNKNOWN_LOCATION;
2060 #else
2061   source_locus loc = 0;
2062 #endif
2063
2064   if (dump_file)
2065     {
2066       fprintf (dump_file, "Removing basic block %d\n", bb->index);
2067       if (dump_flags & TDF_DETAILS)
2068         {
2069           dump_bb (bb, dump_file, 0);
2070           fprintf (dump_file, "\n");
2071         }
2072     }
2073
2074   /* If we remove the header or the latch of a loop, mark the loop for
2075      removal by setting its header and latch to NULL.  */
2076   if (current_loops)
2077     {
2078       struct loop *loop = bb->loop_father;
2079
2080       if (loop->latch == bb
2081           || loop->header == bb)
2082         {
2083           loop->latch = NULL;
2084           loop->header = NULL;
2085         }
2086     }
2087
2088   /* Remove all the instructions in the block.  */
2089   for (i = bsi_start (bb); !bsi_end_p (i);)
2090     {
2091       tree stmt = bsi_stmt (i);
2092       if (TREE_CODE (stmt) == LABEL_EXPR
2093           && FORCED_LABEL (LABEL_EXPR_LABEL (stmt)))
2094         {
2095           basic_block new_bb = bb->prev_bb;
2096           block_stmt_iterator new_bsi = bsi_start (new_bb);
2097                   
2098           bsi_remove (&i);
2099           bsi_insert_before (&new_bsi, stmt, BSI_NEW_STMT);
2100         }
2101       else
2102         {
2103           release_defs (stmt);
2104
2105           set_bb_for_stmt (stmt, NULL);
2106           bsi_remove (&i);
2107         }
2108
2109       /* Don't warn for removed gotos.  Gotos are often removed due to
2110          jump threading, thus resulting in bogus warnings.  Not great,
2111          since this way we lose warnings for gotos in the original
2112          program that are indeed unreachable.  */
2113       if (TREE_CODE (stmt) != GOTO_EXPR && EXPR_HAS_LOCATION (stmt) && !loc)
2114         {
2115 #ifdef USE_MAPPED_LOCATION
2116           if (EXPR_HAS_LOCATION (stmt))
2117             loc = EXPR_LOCATION (stmt);
2118 #else
2119           source_locus t;
2120           t = EXPR_LOCUS (stmt);
2121           if (t && LOCATION_LINE (*t) > 0)
2122             loc = t;
2123 #endif
2124         }
2125     }
2126
2127   /* If requested, give a warning that the first statement in the
2128      block is unreachable.  We walk statements backwards in the
2129      loop above, so the last statement we process is the first statement
2130      in the block.  */
2131 #ifdef USE_MAPPED_LOCATION
2132   if (warn_notreached && loc > BUILTINS_LOCATION)
2133     warning ("%Hwill never be executed", &loc);
2134 #else
2135   if (warn_notreached && loc)
2136     warning ("%Hwill never be executed", loc);
2137 #endif
2138
2139   remove_phi_nodes_and_edges_for_unreachable_block (bb);
2140 }
2141
2142 /* A list of all the noreturn calls passed to modify_stmt.
2143    cleanup_control_flow uses it to detect cases where a mid-block
2144    indirect call has been turned into a noreturn call.  When this
2145    happens, all the instructions after the call are no longer
2146    reachable and must be deleted as dead.  */
2147
2148 VEC(tree) *modified_noreturn_calls;
2149
2150 /* Try to remove superfluous control structures.  */
2151
2152 static bool
2153 cleanup_control_flow (void)
2154 {
2155   basic_block bb;
2156   block_stmt_iterator bsi;
2157   bool retval = false;
2158   tree stmt;
2159
2160   /* Detect cases where a mid-block call is now known not to return.  */
2161   while (VEC_length (tree, modified_noreturn_calls))
2162     {
2163       stmt = VEC_pop (tree, modified_noreturn_calls);
2164       bb = bb_for_stmt (stmt);
2165       if (bb != NULL && last_stmt (bb) != stmt && noreturn_call_p (stmt))
2166         split_block (bb, stmt);
2167     }
2168
2169   FOR_EACH_BB (bb)
2170     {
2171       bsi = bsi_last (bb);
2172
2173       if (bsi_end_p (bsi))
2174         continue;
2175       
2176       stmt = bsi_stmt (bsi);
2177       if (TREE_CODE (stmt) == COND_EXPR
2178           || TREE_CODE (stmt) == SWITCH_EXPR)
2179         retval |= cleanup_control_expr_graph (bb, bsi);
2180
2181       /* If we had a computed goto which has a compile-time determinable
2182          destination, then we can eliminate the goto.  */
2183       if (TREE_CODE (stmt) == GOTO_EXPR
2184           && TREE_CODE (GOTO_DESTINATION (stmt)) == ADDR_EXPR
2185           && TREE_CODE (TREE_OPERAND (GOTO_DESTINATION (stmt), 0)) == LABEL_DECL)
2186         {
2187           edge e;
2188           tree label;
2189           edge_iterator ei;
2190           basic_block target_block;
2191           bool removed_edge = false;
2192
2193           /* First look at all the outgoing edges.  Delete any outgoing
2194              edges which do not go to the right block.  For the one
2195              edge which goes to the right block, fix up its flags.  */
2196           label = TREE_OPERAND (GOTO_DESTINATION (stmt), 0);
2197           target_block = label_to_block (label);
2198           for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
2199             {
2200               if (e->dest != target_block)
2201                 {
2202                   removed_edge = true;
2203                   remove_edge (e);
2204                 }
2205               else
2206                 {
2207                   /* Turn off the EDGE_ABNORMAL flag.  */
2208                   e->flags &= ~EDGE_ABNORMAL;
2209
2210                   /* And set EDGE_FALLTHRU.  */
2211                   e->flags |= EDGE_FALLTHRU;
2212                   ei_next (&ei);
2213                 }
2214             }
2215
2216           /* If we removed one or more edges, then we will need to fix the
2217              dominators.  It may be possible to incrementally update them.  */
2218           if (removed_edge)
2219             free_dominance_info (CDI_DOMINATORS);
2220
2221           /* Remove the GOTO_EXPR as it is not needed.  The CFG has all the
2222              relevant information we need.  */
2223           bsi_remove (&bsi);
2224           retval = true;
2225         }
2226
2227       /* Check for indirect calls that have been turned into
2228          noreturn calls.  */
2229       if (noreturn_call_p (stmt) && remove_fallthru_edge (bb->succs))
2230         {
2231           free_dominance_info (CDI_DOMINATORS);
2232           retval = true;
2233         }
2234     }
2235   return retval;
2236 }
2237
2238
2239 /* Disconnect an unreachable block in the control expression starting
2240    at block BB.  */
2241
2242 static bool
2243 cleanup_control_expr_graph (basic_block bb, block_stmt_iterator bsi)
2244 {
2245   edge taken_edge;
2246   bool retval = false;
2247   tree expr = bsi_stmt (bsi), val;
2248
2249   if (!single_succ_p (bb))
2250     {
2251       edge e;
2252       edge_iterator ei;
2253
2254       switch (TREE_CODE (expr))
2255         {
2256         case COND_EXPR:
2257           val = COND_EXPR_COND (expr);
2258           break;
2259
2260         case SWITCH_EXPR:
2261           val = SWITCH_COND (expr);
2262           if (TREE_CODE (val) != INTEGER_CST)
2263             return false;
2264           break;
2265
2266         default:
2267           gcc_unreachable ();
2268         }
2269
2270       taken_edge = find_taken_edge (bb, val);
2271       if (!taken_edge)
2272         return false;
2273
2274       /* Remove all the edges except the one that is always executed.  */
2275       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
2276         {
2277           if (e != taken_edge)
2278             {
2279               taken_edge->probability += e->probability;
2280               taken_edge->count += e->count;
2281               remove_edge (e);
2282               retval = true;
2283             }
2284           else
2285             ei_next (&ei);
2286         }
2287       if (taken_edge->probability > REG_BR_PROB_BASE)
2288         taken_edge->probability = REG_BR_PROB_BASE;
2289     }
2290   else
2291     taken_edge = single_succ_edge (bb);
2292
2293   bsi_remove (&bsi);
2294   taken_edge->flags = EDGE_FALLTHRU;
2295
2296   /* We removed some paths from the cfg.  */
2297   free_dominance_info (CDI_DOMINATORS);
2298
2299   return retval;
2300 }
2301
2302 /* Remove any fallthru edge from EV.  Return true if an edge was removed.  */
2303
2304 static bool
2305 remove_fallthru_edge (VEC(edge) *ev)
2306 {
2307   edge_iterator ei;
2308   edge e;
2309
2310   FOR_EACH_EDGE (e, ei, ev)
2311     if ((e->flags & EDGE_FALLTHRU) != 0)
2312       {
2313         remove_edge (e);
2314         return true;
2315       }
2316   return false;
2317 }
2318
2319 /* Given a basic block BB ending with COND_EXPR or SWITCH_EXPR, and a
2320    predicate VAL, return the edge that will be taken out of the block.
2321    If VAL does not match a unique edge, NULL is returned.  */
2322
2323 edge
2324 find_taken_edge (basic_block bb, tree val)
2325 {
2326   tree stmt;
2327
2328   stmt = last_stmt (bb);
2329
2330   gcc_assert (stmt);
2331   gcc_assert (is_ctrl_stmt (stmt));
2332   gcc_assert (val);
2333
2334   if (! is_gimple_min_invariant (val))
2335     return NULL;
2336
2337   if (TREE_CODE (stmt) == COND_EXPR)
2338     return find_taken_edge_cond_expr (bb, val);
2339
2340   if (TREE_CODE (stmt) == SWITCH_EXPR)
2341     return find_taken_edge_switch_expr (bb, val);
2342
2343   if (computed_goto_p (stmt))
2344     return find_taken_edge_computed_goto (bb, TREE_OPERAND( val, 0));
2345
2346   gcc_unreachable ();
2347 }
2348
2349 /* Given a constant value VAL and the entry block BB to a GOTO_EXPR
2350    statement, determine which of the outgoing edges will be taken out of the
2351    block.  Return NULL if either edge may be taken.  */
2352
2353 static edge
2354 find_taken_edge_computed_goto (basic_block bb, tree val)
2355 {
2356   basic_block dest;
2357   edge e = NULL;
2358
2359   dest = label_to_block (val);
2360   if (dest)
2361     {
2362       e = find_edge (bb, dest);
2363       gcc_assert (e != NULL);
2364     }
2365
2366   return e;
2367 }
2368
2369 /* Given a constant value VAL and the entry block BB to a COND_EXPR
2370    statement, determine which of the two edges will be taken out of the
2371    block.  Return NULL if either edge may be taken.  */
2372
2373 static edge
2374 find_taken_edge_cond_expr (basic_block bb, tree val)
2375 {
2376   edge true_edge, false_edge;
2377
2378   extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2379   
2380   gcc_assert (TREE_CODE (val) == INTEGER_CST);
2381   return (zero_p (val) ? false_edge : true_edge);
2382 }
2383
2384 /* Given an INTEGER_CST VAL and the entry block BB to a SWITCH_EXPR
2385    statement, determine which edge will be taken out of the block.  Return
2386    NULL if any edge may be taken.  */
2387
2388 static edge
2389 find_taken_edge_switch_expr (basic_block bb, tree val)
2390 {
2391   tree switch_expr, taken_case;
2392   basic_block dest_bb;
2393   edge e;
2394
2395   switch_expr = last_stmt (bb);
2396   taken_case = find_case_label_for_value (switch_expr, val);
2397   dest_bb = label_to_block (CASE_LABEL (taken_case));
2398
2399   e = find_edge (bb, dest_bb);
2400   gcc_assert (e);
2401   return e;
2402 }
2403
2404
2405 /* Return the CASE_LABEL_EXPR that SWITCH_EXPR will take for VAL.
2406    We can make optimal use here of the fact that the case labels are
2407    sorted: We can do a binary search for a case matching VAL.  */
2408
2409 static tree
2410 find_case_label_for_value (tree switch_expr, tree val)
2411 {
2412   tree vec = SWITCH_LABELS (switch_expr);
2413   size_t low, high, n = TREE_VEC_LENGTH (vec);
2414   tree default_case = TREE_VEC_ELT (vec, n - 1);
2415
2416   for (low = -1, high = n - 1; high - low > 1; )
2417     {
2418       size_t i = (high + low) / 2;
2419       tree t = TREE_VEC_ELT (vec, i);
2420       int cmp;
2421
2422       /* Cache the result of comparing CASE_LOW and val.  */
2423       cmp = tree_int_cst_compare (CASE_LOW (t), val);
2424
2425       if (cmp > 0)
2426         high = i;
2427       else
2428         low = i;
2429
2430       if (CASE_HIGH (t) == NULL)
2431         {
2432           /* A singe-valued case label.  */
2433           if (cmp == 0)
2434             return t;
2435         }
2436       else
2437         {
2438           /* A case range.  We can only handle integer ranges.  */
2439           if (cmp <= 0 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
2440             return t;
2441         }
2442     }
2443
2444   return default_case;
2445 }
2446
2447
2448 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
2449    those alternatives are equal in each of the PHI nodes, then return
2450    true, else return false.  */
2451
2452 static bool
2453 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
2454 {
2455   int n1 = e1->dest_idx;
2456   int n2 = e2->dest_idx;
2457   tree phi;
2458
2459   for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
2460     {
2461       tree val1 = PHI_ARG_DEF (phi, n1);
2462       tree val2 = PHI_ARG_DEF (phi, n2);
2463
2464       gcc_assert (val1 != NULL_TREE);
2465       gcc_assert (val2 != NULL_TREE);
2466
2467       if (!operand_equal_for_phi_arg_p (val1, val2))
2468         return false;
2469     }
2470
2471   return true;
2472 }
2473
2474
2475 /*---------------------------------------------------------------------------
2476                               Debugging functions
2477 ---------------------------------------------------------------------------*/
2478
2479 /* Dump tree-specific information of block BB to file OUTF.  */
2480
2481 void
2482 tree_dump_bb (basic_block bb, FILE *outf, int indent)
2483 {
2484   dump_generic_bb (outf, bb, indent, TDF_VOPS);
2485 }
2486
2487
2488 /* Dump a basic block on stderr.  */
2489
2490 void
2491 debug_tree_bb (basic_block bb)
2492 {
2493   dump_bb (bb, stderr, 0);
2494 }
2495
2496
2497 /* Dump basic block with index N on stderr.  */
2498
2499 basic_block
2500 debug_tree_bb_n (int n)
2501 {
2502   debug_tree_bb (BASIC_BLOCK (n));
2503   return BASIC_BLOCK (n);
2504 }        
2505
2506
2507 /* Dump the CFG on stderr.
2508
2509    FLAGS are the same used by the tree dumping functions
2510    (see TDF_* in tree.h).  */
2511
2512 void
2513 debug_tree_cfg (int flags)
2514 {
2515   dump_tree_cfg (stderr, flags);
2516 }
2517
2518
2519 /* Dump the program showing basic block boundaries on the given FILE.
2520
2521    FLAGS are the same used by the tree dumping functions (see TDF_* in
2522    tree.h).  */
2523
2524 void
2525 dump_tree_cfg (FILE *file, int flags)
2526 {
2527   if (flags & TDF_DETAILS)
2528     {
2529       const char *funcname
2530         = lang_hooks.decl_printable_name (current_function_decl, 2);
2531
2532       fputc ('\n', file);
2533       fprintf (file, ";; Function %s\n\n", funcname);
2534       fprintf (file, ";; \n%d basic blocks, %d edges, last basic block %d.\n\n",
2535                n_basic_blocks, n_edges, last_basic_block);
2536
2537       brief_dump_cfg (file);
2538       fprintf (file, "\n");
2539     }
2540
2541   if (flags & TDF_STATS)
2542     dump_cfg_stats (file);
2543
2544   dump_function_to_file (current_function_decl, file, flags | TDF_BLOCKS);
2545 }
2546
2547
2548 /* Dump CFG statistics on FILE.  */
2549
2550 void
2551 dump_cfg_stats (FILE *file)
2552 {
2553   static long max_num_merged_labels = 0;
2554   unsigned long size, total = 0;
2555   int n_edges;
2556   basic_block bb;
2557   const char * const fmt_str   = "%-30s%-13s%12s\n";
2558   const char * const fmt_str_1 = "%-30s%13d%11lu%c\n";
2559   const char * const fmt_str_3 = "%-43s%11lu%c\n";
2560   const char *funcname
2561     = lang_hooks.decl_printable_name (current_function_decl, 2);
2562
2563
2564   fprintf (file, "\nCFG Statistics for %s\n\n", funcname);
2565
2566   fprintf (file, "---------------------------------------------------------\n");
2567   fprintf (file, fmt_str, "", "  Number of  ", "Memory");
2568   fprintf (file, fmt_str, "", "  instances  ", "used ");
2569   fprintf (file, "---------------------------------------------------------\n");
2570
2571   size = n_basic_blocks * sizeof (struct basic_block_def);
2572   total += size;
2573   fprintf (file, fmt_str_1, "Basic blocks", n_basic_blocks,
2574            SCALE (size), LABEL (size));
2575
2576   n_edges = 0;
2577   FOR_EACH_BB (bb)
2578     n_edges += EDGE_COUNT (bb->succs);
2579   size = n_edges * sizeof (struct edge_def);
2580   total += size;
2581   fprintf (file, fmt_str_1, "Edges", n_edges, SCALE (size), LABEL (size));
2582
2583   size = n_basic_blocks * sizeof (struct bb_ann_d);
2584   total += size;
2585   fprintf (file, fmt_str_1, "Basic block annotations", n_basic_blocks,
2586            SCALE (size), LABEL (size));
2587
2588   fprintf (file, "---------------------------------------------------------\n");
2589   fprintf (file, fmt_str_3, "Total memory used by CFG data", SCALE (total),
2590            LABEL (total));
2591   fprintf (file, "---------------------------------------------------------\n");
2592   fprintf (file, "\n");
2593
2594   if (cfg_stats.num_merged_labels > max_num_merged_labels)
2595     max_num_merged_labels = cfg_stats.num_merged_labels;
2596
2597   fprintf (file, "Coalesced label blocks: %ld (Max so far: %ld)\n",
2598            cfg_stats.num_merged_labels, max_num_merged_labels);
2599
2600   fprintf (file, "\n");
2601 }
2602
2603
2604 /* Dump CFG statistics on stderr.  Keep extern so that it's always
2605    linked in the final executable.  */
2606
2607 void
2608 debug_cfg_stats (void)
2609 {
2610   dump_cfg_stats (stderr);
2611 }
2612
2613
2614 /* Dump the flowgraph to a .vcg FILE.  */
2615
2616 static void
2617 tree_cfg2vcg (FILE *file)
2618 {
2619   edge e;
2620   edge_iterator ei;
2621   basic_block bb;
2622   const char *funcname
2623     = lang_hooks.decl_printable_name (current_function_decl, 2);
2624
2625   /* Write the file header.  */
2626   fprintf (file, "graph: { title: \"%s\"\n", funcname);
2627   fprintf (file, "node: { title: \"ENTRY\" label: \"ENTRY\" }\n");
2628   fprintf (file, "node: { title: \"EXIT\" label: \"EXIT\" }\n");
2629
2630   /* Write blocks and edges.  */
2631   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2632     {
2633       fprintf (file, "edge: { sourcename: \"ENTRY\" targetname: \"%d\"",
2634                e->dest->index);
2635
2636       if (e->flags & EDGE_FAKE)
2637         fprintf (file, " linestyle: dotted priority: 10");
2638       else
2639         fprintf (file, " linestyle: solid priority: 100");
2640
2641       fprintf (file, " }\n");
2642     }
2643   fputc ('\n', file);
2644
2645   FOR_EACH_BB (bb)
2646     {
2647       enum tree_code head_code, end_code;
2648       const char *head_name, *end_name;
2649       int head_line = 0;
2650       int end_line = 0;
2651       tree first = first_stmt (bb);
2652       tree last = last_stmt (bb);
2653
2654       if (first)
2655         {
2656           head_code = TREE_CODE (first);
2657           head_name = tree_code_name[head_code];
2658           head_line = get_lineno (first);
2659         }
2660       else
2661         head_name = "no-statement";
2662
2663       if (last)
2664         {
2665           end_code = TREE_CODE (last);
2666           end_name = tree_code_name[end_code];
2667           end_line = get_lineno (last);
2668         }
2669       else
2670         end_name = "no-statement";
2671
2672       fprintf (file, "node: { title: \"%d\" label: \"#%d\\n%s (%d)\\n%s (%d)\"}\n",
2673                bb->index, bb->index, head_name, head_line, end_name,
2674                end_line);
2675
2676       FOR_EACH_EDGE (e, ei, bb->succs)
2677         {
2678           if (e->dest == EXIT_BLOCK_PTR)
2679             fprintf (file, "edge: { sourcename: \"%d\" targetname: \"EXIT\"", bb->index);
2680           else
2681             fprintf (file, "edge: { sourcename: \"%d\" targetname: \"%d\"", bb->index, e->dest->index);
2682
2683           if (e->flags & EDGE_FAKE)
2684             fprintf (file, " priority: 10 linestyle: dotted");
2685           else
2686             fprintf (file, " priority: 100 linestyle: solid");
2687
2688           fprintf (file, " }\n");
2689         }
2690
2691       if (bb->next_bb != EXIT_BLOCK_PTR)
2692         fputc ('\n', file);
2693     }
2694
2695   fputs ("}\n\n", file);
2696 }
2697
2698
2699
2700 /*---------------------------------------------------------------------------
2701                              Miscellaneous helpers
2702 ---------------------------------------------------------------------------*/
2703
2704 /* Return true if T represents a stmt that always transfers control.  */
2705
2706 bool
2707 is_ctrl_stmt (tree t)
2708 {
2709   return (TREE_CODE (t) == COND_EXPR
2710           || TREE_CODE (t) == SWITCH_EXPR
2711           || TREE_CODE (t) == GOTO_EXPR
2712           || TREE_CODE (t) == RETURN_EXPR
2713           || TREE_CODE (t) == RESX_EXPR);
2714 }
2715
2716
2717 /* Return true if T is a statement that may alter the flow of control
2718    (e.g., a call to a non-returning function).  */
2719
2720 bool
2721 is_ctrl_altering_stmt (tree t)
2722 {
2723   tree call;
2724
2725   gcc_assert (t);
2726   call = get_call_expr_in (t);
2727   if (call)
2728     {
2729       /* A non-pure/const CALL_EXPR alters flow control if the current
2730          function has nonlocal labels.  */
2731       if (TREE_SIDE_EFFECTS (call) && current_function_has_nonlocal_label)
2732         return true;
2733
2734       /* A CALL_EXPR also alters control flow if it does not return.  */
2735       if (call_expr_flags (call) & ECF_NORETURN)
2736         return true;
2737     }
2738
2739   /* If a statement can throw, it alters control flow.  */
2740   return tree_can_throw_internal (t);
2741 }
2742
2743
2744 /* Return true if T is a computed goto.  */
2745
2746 bool
2747 computed_goto_p (tree t)
2748 {
2749   return (TREE_CODE (t) == GOTO_EXPR
2750           && TREE_CODE (GOTO_DESTINATION (t)) != LABEL_DECL);
2751 }
2752
2753
2754 /* Checks whether EXPR is a simple local goto.  */
2755
2756 bool
2757 simple_goto_p (tree expr)
2758 {
2759   return (TREE_CODE (expr) == GOTO_EXPR
2760           && TREE_CODE (GOTO_DESTINATION (expr)) == LABEL_DECL);
2761 }
2762
2763
2764 /* Return true if T should start a new basic block.  PREV_T is the
2765    statement preceding T.  It is used when T is a label or a case label.
2766    Labels should only start a new basic block if their previous statement
2767    wasn't a label.  Otherwise, sequence of labels would generate
2768    unnecessary basic blocks that only contain a single label.  */
2769
2770 static inline bool
2771 stmt_starts_bb_p (tree t, tree prev_t)
2772 {
2773   if (t == NULL_TREE)
2774     return false;
2775
2776   /* LABEL_EXPRs start a new basic block only if the preceding
2777      statement wasn't a label of the same type.  This prevents the
2778      creation of consecutive blocks that have nothing but a single
2779      label.  */
2780   if (TREE_CODE (t) == LABEL_EXPR)
2781     {
2782       /* Nonlocal and computed GOTO targets always start a new block.  */
2783       if (DECL_NONLOCAL (LABEL_EXPR_LABEL (t))
2784           || FORCED_LABEL (LABEL_EXPR_LABEL (t)))
2785         return true;
2786
2787       if (prev_t && TREE_CODE (prev_t) == LABEL_EXPR)
2788         {
2789           if (DECL_NONLOCAL (LABEL_EXPR_LABEL (prev_t)))
2790             return true;
2791
2792           cfg_stats.num_merged_labels++;
2793           return false;
2794         }
2795       else
2796         return true;
2797     }
2798
2799   return false;
2800 }
2801
2802
2803 /* Return true if T should end a basic block.  */
2804
2805 bool
2806 stmt_ends_bb_p (tree t)
2807 {
2808   return is_ctrl_stmt (t) || is_ctrl_altering_stmt (t);
2809 }
2810
2811
2812 /* Add gotos that used to be represented implicitly in the CFG.  */
2813
2814 void
2815 disband_implicit_edges (void)
2816 {
2817   basic_block bb;
2818   block_stmt_iterator last;
2819   edge e;
2820   edge_iterator ei;
2821   tree stmt, label;
2822
2823   FOR_EACH_BB (bb)
2824     {
2825       last = bsi_last (bb);
2826       stmt = last_stmt (bb);
2827
2828       if (stmt && TREE_CODE (stmt) == COND_EXPR)
2829         {
2830           /* Remove superfluous gotos from COND_EXPR branches.  Moved
2831              from cfg_remove_useless_stmts here since it violates the
2832              invariants for tree--cfg correspondence and thus fits better
2833              here where we do it anyway.  */
2834           e = find_edge (bb, bb->next_bb);
2835           if (e)
2836             {
2837               if (e->flags & EDGE_TRUE_VALUE)
2838                 COND_EXPR_THEN (stmt) = build_empty_stmt ();
2839               else if (e->flags & EDGE_FALSE_VALUE)
2840                 COND_EXPR_ELSE (stmt) = build_empty_stmt ();
2841               else
2842                 gcc_unreachable ();
2843               e->flags |= EDGE_FALLTHRU;
2844             }
2845
2846           continue;
2847         }
2848
2849       if (stmt && TREE_CODE (stmt) == RETURN_EXPR)
2850         {
2851           /* Remove the RETURN_EXPR if we may fall though to the exit
2852              instead.  */
2853           gcc_assert (single_succ_p (bb));
2854           gcc_assert (single_succ (bb) == EXIT_BLOCK_PTR);
2855
2856           if (bb->next_bb == EXIT_BLOCK_PTR
2857               && !TREE_OPERAND (stmt, 0))
2858             {
2859               bsi_remove (&last);
2860               single_succ_edge (bb)->flags |= EDGE_FALLTHRU;
2861             }
2862           continue;
2863         }
2864
2865       /* There can be no fallthru edge if the last statement is a control
2866          one.  */
2867       if (stmt && is_ctrl_stmt (stmt))
2868         continue;
2869
2870       /* Find a fallthru edge and emit the goto if necessary.  */
2871       FOR_EACH_EDGE (e, ei, bb->succs)
2872         if (e->flags & EDGE_FALLTHRU)
2873           break;
2874
2875       if (!e || e->dest == bb->next_bb)
2876         continue;
2877
2878       gcc_assert (e->dest != EXIT_BLOCK_PTR);
2879       label = tree_block_label (e->dest);
2880
2881       stmt = build1 (GOTO_EXPR, void_type_node, label);
2882 #ifdef USE_MAPPED_LOCATION
2883       SET_EXPR_LOCATION (stmt, e->goto_locus);
2884 #else
2885       SET_EXPR_LOCUS (stmt, e->goto_locus);
2886 #endif
2887       bsi_insert_after (&last, stmt, BSI_NEW_STMT);
2888       e->flags &= ~EDGE_FALLTHRU;
2889     }
2890 }
2891
2892 /* Remove block annotations and other datastructures.  */
2893
2894 void
2895 delete_tree_cfg_annotations (void)
2896 {
2897   basic_block bb;
2898   if (n_basic_blocks > 0)
2899     free_blocks_annotations ();
2900
2901   label_to_block_map = NULL;
2902   free_rbi_pool ();
2903   FOR_EACH_BB (bb)
2904     bb->rbi = NULL;
2905 }
2906
2907
2908 /* Return the first statement in basic block BB.  */
2909
2910 tree
2911 first_stmt (basic_block bb)
2912 {
2913   block_stmt_iterator i = bsi_start (bb);
2914   return !bsi_end_p (i) ? bsi_stmt (i) : NULL_TREE;
2915 }
2916
2917
2918 /* Return the last statement in basic block BB.  */
2919
2920 tree
2921 last_stmt (basic_block bb)
2922 {
2923   block_stmt_iterator b = bsi_last (bb);
2924   return !bsi_end_p (b) ? bsi_stmt (b) : NULL_TREE;
2925 }
2926
2927
2928 /* Return a pointer to the last statement in block BB.  */
2929
2930 tree *
2931 last_stmt_ptr (basic_block bb)
2932 {
2933   block_stmt_iterator last = bsi_last (bb);
2934   return !bsi_end_p (last) ? bsi_stmt_ptr (last) : NULL;
2935 }
2936
2937
2938 /* Return the last statement of an otherwise empty block.  Return NULL
2939    if the block is totally empty, or if it contains more than one
2940    statement.  */
2941
2942 tree
2943 last_and_only_stmt (basic_block bb)
2944 {
2945   block_stmt_iterator i = bsi_last (bb);
2946   tree last, prev;
2947
2948   if (bsi_end_p (i))
2949     return NULL_TREE;
2950
2951   last = bsi_stmt (i);
2952   bsi_prev (&i);
2953   if (bsi_end_p (i))
2954     return last;
2955
2956   /* Empty statements should no longer appear in the instruction stream.
2957      Everything that might have appeared before should be deleted by
2958      remove_useless_stmts, and the optimizers should just bsi_remove
2959      instead of smashing with build_empty_stmt.
2960
2961      Thus the only thing that should appear here in a block containing
2962      one executable statement is a label.  */
2963   prev = bsi_stmt (i);
2964   if (TREE_CODE (prev) == LABEL_EXPR)
2965     return last;
2966   else
2967     return NULL_TREE;
2968 }
2969
2970
2971 /* Mark BB as the basic block holding statement T.  */
2972
2973 void
2974 set_bb_for_stmt (tree t, basic_block bb)
2975 {
2976   if (TREE_CODE (t) == PHI_NODE)
2977     PHI_BB (t) = bb;
2978   else if (TREE_CODE (t) == STATEMENT_LIST)
2979     {
2980       tree_stmt_iterator i;
2981       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
2982         set_bb_for_stmt (tsi_stmt (i), bb);
2983     }
2984   else
2985     {
2986       stmt_ann_t ann = get_stmt_ann (t);
2987       ann->bb = bb;
2988
2989       /* If the statement is a label, add the label to block-to-labels map
2990          so that we can speed up edge creation for GOTO_EXPRs.  */
2991       if (TREE_CODE (t) == LABEL_EXPR)
2992         {
2993           int uid;
2994
2995           t = LABEL_EXPR_LABEL (t);
2996           uid = LABEL_DECL_UID (t);
2997           if (uid == -1)
2998             {
2999               LABEL_DECL_UID (t) = uid = cfun->last_label_uid++;
3000               if (VARRAY_SIZE (label_to_block_map) <= (unsigned) uid)
3001                 VARRAY_GROW (label_to_block_map, 3 * uid / 2);
3002             }
3003           else
3004             /* We're moving an existing label.  Make sure that we've
3005                 removed it from the old block.  */
3006             gcc_assert (!bb || !VARRAY_BB (label_to_block_map, uid));
3007           VARRAY_BB (label_to_block_map, uid) = bb;
3008         }
3009     }
3010 }
3011
3012 /* Finds iterator for STMT.  */
3013
3014 extern block_stmt_iterator
3015 bsi_for_stmt (tree stmt)
3016 {
3017   block_stmt_iterator bsi;
3018
3019   for (bsi = bsi_start (bb_for_stmt (stmt)); !bsi_end_p (bsi); bsi_next (&bsi))
3020     if (bsi_stmt (bsi) == stmt)
3021       return bsi;
3022
3023   gcc_unreachable ();
3024 }
3025
3026 /* Mark statement T as modified, and update it.  */
3027 static inline void
3028 update_modified_stmts (tree t)
3029 {
3030   if (TREE_CODE (t) == STATEMENT_LIST)
3031     {
3032       tree_stmt_iterator i;
3033       tree stmt;
3034       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3035         {
3036           stmt = tsi_stmt (i);
3037           update_stmt_if_modified (stmt);
3038         }
3039     }
3040   else
3041     update_stmt_if_modified (t);
3042 }
3043
3044 /* Insert statement (or statement list) T before the statement
3045    pointed-to by iterator I.  M specifies how to update iterator I
3046    after insertion (see enum bsi_iterator_update).  */
3047
3048 void
3049 bsi_insert_before (block_stmt_iterator *i, tree t, enum bsi_iterator_update m)
3050 {
3051   set_bb_for_stmt (t, i->bb);
3052   update_modified_stmts (t);
3053   tsi_link_before (&i->tsi, t, m);
3054 }
3055
3056
3057 /* Insert statement (or statement list) T after the statement
3058    pointed-to by iterator I.  M specifies how to update iterator I
3059    after insertion (see enum bsi_iterator_update).  */
3060
3061 void
3062 bsi_insert_after (block_stmt_iterator *i, tree t, enum bsi_iterator_update m)
3063 {
3064   set_bb_for_stmt (t, i->bb);
3065   update_modified_stmts (t);
3066   tsi_link_after (&i->tsi, t, m);
3067 }
3068
3069
3070 /* Remove the statement pointed to by iterator I.  The iterator is updated
3071    to the next statement.  */
3072
3073 void
3074 bsi_remove (block_stmt_iterator *i)
3075 {
3076   tree t = bsi_stmt (*i);
3077   set_bb_for_stmt (t, NULL);
3078   delink_stmt_imm_use (t);
3079   tsi_delink (&i->tsi);
3080   mark_stmt_modified (t);
3081 }
3082
3083
3084 /* Move the statement at FROM so it comes right after the statement at TO.  */
3085
3086 void 
3087 bsi_move_after (block_stmt_iterator *from, block_stmt_iterator *to)
3088 {
3089   tree stmt = bsi_stmt (*from);
3090   bsi_remove (from);
3091   bsi_insert_after (to, stmt, BSI_SAME_STMT);
3092
3093
3094
3095 /* Move the statement at FROM so it comes right before the statement at TO.  */
3096
3097 void 
3098 bsi_move_before (block_stmt_iterator *from, block_stmt_iterator *to)
3099 {
3100   tree stmt = bsi_stmt (*from);
3101   bsi_remove (from);
3102   bsi_insert_before (to, stmt, BSI_SAME_STMT);
3103 }
3104
3105
3106 /* Move the statement at FROM to the end of basic block BB.  */
3107
3108 void
3109 bsi_move_to_bb_end (block_stmt_iterator *from, basic_block bb)
3110 {
3111   block_stmt_iterator last = bsi_last (bb);
3112   
3113   /* Have to check bsi_end_p because it could be an empty block.  */
3114   if (!bsi_end_p (last) && is_ctrl_stmt (bsi_stmt (last)))
3115     bsi_move_before (from, &last);
3116   else
3117     bsi_move_after (from, &last);
3118 }
3119
3120
3121 /* Replace the contents of the statement pointed to by iterator BSI
3122    with STMT.  If PRESERVE_EH_INFO is true, the exception handling
3123    information of the original statement is preserved.  */
3124
3125 void
3126 bsi_replace (const block_stmt_iterator *bsi, tree stmt, bool preserve_eh_info)
3127 {
3128   int eh_region;
3129   tree orig_stmt = bsi_stmt (*bsi);
3130
3131   SET_EXPR_LOCUS (stmt, EXPR_LOCUS (orig_stmt));
3132   set_bb_for_stmt (stmt, bsi->bb);
3133
3134   /* Preserve EH region information from the original statement, if
3135      requested by the caller.  */
3136   if (preserve_eh_info)
3137     {
3138       eh_region = lookup_stmt_eh_region (orig_stmt);
3139       if (eh_region >= 0)
3140         add_stmt_to_eh_region (stmt, eh_region);
3141     }
3142
3143   *bsi_stmt_ptr (*bsi) = stmt;
3144   mark_stmt_modified (stmt);
3145   update_modified_stmts (stmt);
3146 }
3147
3148
3149 /* Insert the statement pointed-to by BSI into edge E.  Every attempt
3150    is made to place the statement in an existing basic block, but
3151    sometimes that isn't possible.  When it isn't possible, the edge is
3152    split and the statement is added to the new block.
3153
3154    In all cases, the returned *BSI points to the correct location.  The
3155    return value is true if insertion should be done after the location,
3156    or false if it should be done before the location.  If new basic block
3157    has to be created, it is stored in *NEW_BB.  */
3158
3159 static bool
3160 tree_find_edge_insert_loc (edge e, block_stmt_iterator *bsi,
3161                            basic_block *new_bb)
3162 {
3163   basic_block dest, src;
3164   tree tmp;
3165
3166   dest = e->dest;
3167  restart:
3168
3169   /* If the destination has one predecessor which has no PHI nodes,
3170      insert there.  Except for the exit block. 
3171
3172      The requirement for no PHI nodes could be relaxed.  Basically we
3173      would have to examine the PHIs to prove that none of them used
3174      the value set by the statement we want to insert on E.  That
3175      hardly seems worth the effort.  */
3176   if (single_pred_p (dest)
3177       && ! phi_nodes (dest)
3178       && dest != EXIT_BLOCK_PTR)
3179     {
3180       *bsi = bsi_start (dest);
3181       if (bsi_end_p (*bsi))
3182         return true;
3183
3184       /* Make sure we insert after any leading labels.  */
3185       tmp = bsi_stmt (*bsi);
3186       while (TREE_CODE (tmp) == LABEL_EXPR)
3187         {
3188           bsi_next (bsi);
3189           if (bsi_end_p (*bsi))
3190             break;
3191           tmp = bsi_stmt (*bsi);
3192         }
3193
3194       if (bsi_end_p (*bsi))
3195         {
3196           *bsi = bsi_last (dest);
3197           return true;
3198         }
3199       else
3200         return false;
3201     }
3202
3203   /* If the source has one successor, the edge is not abnormal and
3204      the last statement does not end a basic block, insert there.
3205      Except for the entry block.  */
3206   src = e->src;
3207   if ((e->flags & EDGE_ABNORMAL) == 0
3208       && single_succ_p (src)
3209       && src != ENTRY_BLOCK_PTR)
3210     {
3211       *bsi = bsi_last (src);
3212       if (bsi_end_p (*bsi))
3213         return true;
3214
3215       tmp = bsi_stmt (*bsi);
3216       if (!stmt_ends_bb_p (tmp))
3217         return true;
3218
3219       /* Insert code just before returning the value.  We may need to decompose
3220          the return in the case it contains non-trivial operand.  */
3221       if (TREE_CODE (tmp) == RETURN_EXPR)
3222         {
3223           tree op = TREE_OPERAND (tmp, 0);
3224           if (!is_gimple_val (op))
3225             {
3226               gcc_assert (TREE_CODE (op) == MODIFY_EXPR);
3227               bsi_insert_before (bsi, op, BSI_NEW_STMT);
3228               TREE_OPERAND (tmp, 0) = TREE_OPERAND (op, 0);
3229             }
3230           bsi_prev (bsi);
3231           return true;
3232         }
3233     }
3234
3235   /* Otherwise, create a new basic block, and split this edge.  */
3236   dest = split_edge (e);
3237   if (new_bb)
3238     *new_bb = dest;
3239   e = single_pred_edge (dest);
3240   goto restart;
3241 }
3242
3243
3244 /* This routine will commit all pending edge insertions, creating any new
3245    basic blocks which are necessary.  */
3246
3247 void
3248 bsi_commit_edge_inserts (void)
3249 {
3250   basic_block bb;
3251   edge e;
3252   edge_iterator ei;
3253
3254   bsi_commit_one_edge_insert (single_succ_edge (ENTRY_BLOCK_PTR), NULL);
3255
3256   FOR_EACH_BB (bb)
3257     FOR_EACH_EDGE (e, ei, bb->succs)
3258       bsi_commit_one_edge_insert (e, NULL);
3259 }
3260
3261
3262 /* Commit insertions pending at edge E. If a new block is created, set NEW_BB
3263    to this block, otherwise set it to NULL.  */
3264
3265 void
3266 bsi_commit_one_edge_insert (edge e, basic_block *new_bb)
3267 {
3268   if (new_bb)
3269     *new_bb = NULL;
3270   if (PENDING_STMT (e))
3271     {
3272       block_stmt_iterator bsi;
3273       tree stmt = PENDING_STMT (e);
3274
3275       PENDING_STMT (e) = NULL_TREE;
3276
3277       if (tree_find_edge_insert_loc (e, &bsi, new_bb))
3278         bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
3279       else
3280         bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
3281     }
3282 }
3283
3284
3285 /* Add STMT to the pending list of edge E.  No actual insertion is
3286    made until a call to bsi_commit_edge_inserts () is made.  */
3287
3288 void
3289 bsi_insert_on_edge (edge e, tree stmt)
3290 {
3291   append_to_statement_list (stmt, &PENDING_STMT (e));
3292 }
3293
3294 /* Similar to bsi_insert_on_edge+bsi_commit_edge_inserts.  If a new
3295    block has to be created, it is returned.  */
3296
3297 basic_block
3298 bsi_insert_on_edge_immediate (edge e, tree stmt)
3299 {
3300   block_stmt_iterator bsi;
3301   basic_block new_bb = NULL;
3302
3303   gcc_assert (!PENDING_STMT (e));
3304
3305   if (tree_find_edge_insert_loc (e, &bsi, &new_bb))
3306     bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
3307   else
3308     bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
3309
3310   return new_bb;
3311 }
3312
3313 /*---------------------------------------------------------------------------
3314              Tree specific functions for CFG manipulation
3315 ---------------------------------------------------------------------------*/
3316
3317 /* Reinstall those PHI arguments queued in OLD_EDGE to NEW_EDGE.  */
3318
3319 static void
3320 reinstall_phi_args (edge new_edge, edge old_edge)
3321 {
3322   tree var, phi;
3323
3324   if (!PENDING_STMT (old_edge))
3325     return;
3326   
3327   for (var = PENDING_STMT (old_edge), phi = phi_nodes (new_edge->dest);
3328        var && phi;
3329        var = TREE_CHAIN (var), phi = PHI_CHAIN (phi))
3330     {
3331       tree result = TREE_PURPOSE (var);
3332       tree arg = TREE_VALUE (var);
3333
3334       gcc_assert (result == PHI_RESULT (phi));
3335
3336       add_phi_arg (phi, arg, new_edge);
3337     }
3338
3339   PENDING_STMT (old_edge) = NULL;
3340 }
3341
3342 /* Split a (typically critical) edge EDGE_IN.  Return the new block.
3343    Abort on abnormal edges.  */
3344
3345 static basic_block
3346 tree_split_edge (edge edge_in)
3347 {
3348   basic_block new_bb, after_bb, dest, src;
3349   edge new_edge, e;
3350
3351   /* Abnormal edges cannot be split.  */
3352   gcc_assert (!(edge_in->flags & EDGE_ABNORMAL));
3353
3354   src = edge_in->src;
3355   dest = edge_in->dest;
3356
3357   /* Place the new block in the block list.  Try to keep the new block
3358      near its "logical" location.  This is of most help to humans looking
3359      at debugging dumps.  */
3360   if (dest->prev_bb && find_edge (dest->prev_bb, dest))
3361     after_bb = edge_in->src;
3362   else
3363     after_bb = dest->prev_bb;
3364
3365   new_bb = create_empty_bb (after_bb);
3366   new_bb->frequency = EDGE_FREQUENCY (edge_in);
3367   new_bb->count = edge_in->count;
3368   new_edge = make_edge (new_bb, dest, EDGE_FALLTHRU);
3369   new_edge->probability = REG_BR_PROB_BASE;
3370   new_edge->count = edge_in->count;
3371
3372   e = redirect_edge_and_branch (edge_in, new_bb);
3373   gcc_assert (e);
3374   reinstall_phi_args (new_edge, e);
3375
3376   return new_bb;
3377 }
3378
3379
3380 /* Return true when BB has label LABEL in it.  */
3381
3382 static bool
3383 has_label_p (basic_block bb, tree label)
3384 {
3385   block_stmt_iterator bsi;
3386
3387   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3388     {
3389       tree stmt = bsi_stmt (bsi);
3390
3391       if (TREE_CODE (stmt) != LABEL_EXPR)
3392         return false;
3393       if (LABEL_EXPR_LABEL (stmt) == label)
3394         return true;
3395     }
3396   return false;
3397 }
3398
3399
3400 /* Callback for walk_tree, check that all elements with address taken are
3401    properly noticed as such.  The DATA is an int* that is 1 if TP was seen
3402    inside a PHI node.  */
3403
3404 static tree
3405 verify_expr (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3406 {
3407   tree t = *tp, x;
3408   bool in_phi = (data != NULL);
3409
3410   if (TYPE_P (t))
3411     *walk_subtrees = 0;
3412   
3413   /* Check operand N for being valid GIMPLE and give error MSG if not. 
3414      We check for constants explicitly since they are not considered
3415      gimple invariants if they overflowed.  */
3416 #define CHECK_OP(N, MSG) \
3417   do { if (!CONSTANT_CLASS_P (TREE_OPERAND (t, N))              \
3418          && !is_gimple_val (TREE_OPERAND (t, N)))               \
3419        { error (MSG); return TREE_OPERAND (t, N); }} while (0)
3420
3421   switch (TREE_CODE (t))
3422     {
3423     case SSA_NAME:
3424       if (SSA_NAME_IN_FREE_LIST (t))
3425         {
3426           error ("SSA name in freelist but still referenced");
3427           return *tp;
3428         }
3429       break;
3430
3431     case MODIFY_EXPR:
3432       x = TREE_OPERAND (t, 0);
3433       if (TREE_CODE (x) == BIT_FIELD_REF
3434           && is_gimple_reg (TREE_OPERAND (x, 0)))
3435         {
3436           error ("GIMPLE register modified with BIT_FIELD_REF");
3437           return t;
3438         }
3439       break;
3440
3441     case ADDR_EXPR:
3442       /* ??? tree-ssa-alias.c may have overlooked dead PHI nodes, missing
3443          dead PHIs that take the address of something.  But if the PHI
3444          result is dead, the fact that it takes the address of anything
3445          is irrelevant.  Because we can not tell from here if a PHI result
3446          is dead, we just skip this check for PHIs altogether.  This means
3447          we may be missing "valid" checks, but what can you do?
3448          This was PR19217.  */
3449       if (in_phi)
3450         break;
3451
3452       /* Skip any references (they will be checked when we recurse down the
3453          tree) and ensure that any variable used as a prefix is marked
3454          addressable.  */
3455       for (x = TREE_OPERAND (t, 0);
3456            handled_component_p (x);
3457            x = TREE_OPERAND (x, 0))
3458         ;
3459
3460       if (TREE_CODE (x) != VAR_DECL && TREE_CODE (x) != PARM_DECL)
3461         return NULL;
3462       if (!TREE_ADDRESSABLE (x))
3463         {
3464           error ("address taken, but ADDRESSABLE bit not set");
3465           return x;
3466         }
3467       break;
3468
3469     case COND_EXPR:
3470       x = COND_EXPR_COND (t);
3471       if (TREE_CODE (TREE_TYPE (x)) != BOOLEAN_TYPE)
3472         {
3473           error ("non-boolean used in condition");
3474           return x;
3475         }
3476       break;
3477
3478     case NOP_EXPR:
3479     case CONVERT_EXPR:
3480     case FIX_TRUNC_EXPR:
3481     case FIX_CEIL_EXPR:
3482     case FIX_FLOOR_EXPR:
3483     case FIX_ROUND_EXPR:
3484     case FLOAT_EXPR:
3485     case NEGATE_EXPR:
3486     case ABS_EXPR:
3487     case BIT_NOT_EXPR:
3488     case NON_LVALUE_EXPR:
3489     case TRUTH_NOT_EXPR:
3490       CHECK_OP (0, "Invalid operand to unary operator");
3491       break;
3492
3493     case REALPART_EXPR:
3494     case IMAGPART_EXPR:
3495     case COMPONENT_REF:
3496     case ARRAY_REF:
3497     case ARRAY_RANGE_REF:
3498     case BIT_FIELD_REF:
3499     case VIEW_CONVERT_EXPR:
3500       /* We have a nest of references.  Verify that each of the operands
3501          that determine where to reference is either a constant or a variable,
3502          verify that the base is valid, and then show we've already checked
3503          the subtrees.  */
3504       while (handled_component_p (t))
3505         {
3506           if (TREE_CODE (t) == COMPONENT_REF && TREE_OPERAND (t, 2))
3507             CHECK_OP (2, "Invalid COMPONENT_REF offset operator");
3508           else if (TREE_CODE (t) == ARRAY_REF
3509                    || TREE_CODE (t) == ARRAY_RANGE_REF)
3510             {
3511               CHECK_OP (1, "Invalid array index.");
3512               if (TREE_OPERAND (t, 2))
3513                 CHECK_OP (2, "Invalid array lower bound.");
3514               if (TREE_OPERAND (t, 3))
3515                 CHECK_OP (3, "Invalid array stride.");
3516             }
3517           else if (TREE_CODE (t) == BIT_FIELD_REF)
3518             {
3519               CHECK_OP (1, "Invalid operand to BIT_FIELD_REF");
3520               CHECK_OP (2, "Invalid operand to BIT_FIELD_REF");
3521             }
3522
3523           t = TREE_OPERAND (t, 0);
3524         }
3525
3526       if (!CONSTANT_CLASS_P (t) && !is_gimple_lvalue (t))
3527         {
3528           error ("Invalid reference prefix.");
3529           return t;
3530         }
3531       *walk_subtrees = 0;
3532       break;
3533
3534     case LT_EXPR:
3535     case LE_EXPR:
3536     case GT_EXPR:
3537     case GE_EXPR:
3538     case EQ_EXPR:
3539     case NE_EXPR:
3540     case UNORDERED_EXPR:
3541     case ORDERED_EXPR:
3542     case UNLT_EXPR:
3543     case UNLE_EXPR:
3544     case UNGT_EXPR:
3545     case UNGE_EXPR:
3546     case UNEQ_EXPR:
3547     case LTGT_EXPR:
3548     case PLUS_EXPR:
3549     case MINUS_EXPR:
3550     case MULT_EXPR:
3551     case TRUNC_DIV_EXPR:
3552     case CEIL_DIV_EXPR:
3553     case FLOOR_DIV_EXPR:
3554     case ROUND_DIV_EXPR:
3555     case TRUNC_MOD_EXPR:
3556     case CEIL_MOD_EXPR:
3557     case FLOOR_MOD_EXPR:
3558     case ROUND_MOD_EXPR:
3559     case RDIV_EXPR:
3560     case EXACT_DIV_EXPR:
3561     case MIN_EXPR:
3562     case MAX_EXPR:
3563     case LSHIFT_EXPR:
3564     case RSHIFT_EXPR:
3565     case LROTATE_EXPR:
3566     case RROTATE_EXPR:
3567     case BIT_IOR_EXPR:
3568     case BIT_XOR_EXPR:
3569     case BIT_AND_EXPR:
3570       CHECK_OP (0, "Invalid operand to binary operator");
3571       CHECK_OP (1, "Invalid operand to binary operator");
3572       break;
3573
3574     default:
3575       break;
3576     }
3577   return NULL;
3578
3579 #undef CHECK_OP
3580 }
3581
3582
3583 /* Verify STMT, return true if STMT is not in GIMPLE form.
3584    TODO: Implement type checking.  */
3585
3586 static bool
3587 verify_stmt (tree stmt, bool last_in_block)
3588 {
3589   tree addr;
3590
3591   if (!is_gimple_stmt (stmt))
3592     {
3593       error ("Is not a valid GIMPLE statement.");
3594       goto fail;
3595     }
3596
3597   addr = walk_tree (&stmt, verify_expr, NULL, NULL);
3598   if (addr)
3599     {
3600       debug_generic_stmt (addr);
3601       return true;
3602     }
3603
3604   /* If the statement is marked as part of an EH region, then it is
3605      expected that the statement could throw.  Verify that when we
3606      have optimizations that simplify statements such that we prove
3607      that they cannot throw, that we update other data structures
3608      to match.  */
3609   if (lookup_stmt_eh_region (stmt) >= 0)
3610     {
3611       if (!tree_could_throw_p (stmt))
3612         {
3613           error ("Statement marked for throw, but doesn%'t.");
3614           goto fail;
3615         }
3616       if (!last_in_block && tree_can_throw_internal (stmt))
3617         {
3618           error ("Statement marked for throw in middle of block.");
3619           goto fail;
3620         }
3621     }
3622
3623   return false;
3624
3625  fail:
3626   debug_generic_stmt (stmt);
3627   return true;
3628 }
3629
3630
3631 /* Return true when the T can be shared.  */
3632
3633 static bool
3634 tree_node_can_be_shared (tree t)
3635 {
3636   if (IS_TYPE_OR_DECL_P (t)
3637       /* We check for constants explicitly since they are not considered
3638          gimple invariants if they overflowed.  */
3639       || CONSTANT_CLASS_P (t)
3640       || is_gimple_min_invariant (t)
3641       || TREE_CODE (t) == SSA_NAME
3642       || t == error_mark_node)
3643     return true;
3644
3645   if (TREE_CODE (t) == CASE_LABEL_EXPR)
3646     return true;
3647
3648   while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
3649           /* We check for constants explicitly since they are not considered
3650              gimple invariants if they overflowed.  */
3651           && (CONSTANT_CLASS_P (TREE_OPERAND (t, 1))
3652               || is_gimple_min_invariant (TREE_OPERAND (t, 1))))
3653          || (TREE_CODE (t) == COMPONENT_REF
3654              || TREE_CODE (t) == REALPART_EXPR
3655              || TREE_CODE (t) == IMAGPART_EXPR))
3656     t = TREE_OPERAND (t, 0);
3657
3658   if (DECL_P (t))
3659     return true;
3660
3661   return false;
3662 }
3663
3664
3665 /* Called via walk_trees.  Verify tree sharing.  */
3666
3667 static tree
3668 verify_node_sharing (tree * tp, int *walk_subtrees, void *data)
3669 {
3670   htab_t htab = (htab_t) data;
3671   void **slot;
3672
3673   if (tree_node_can_be_shared (*tp))
3674     {
3675       *walk_subtrees = false;
3676       return NULL;
3677     }
3678
3679   slot = htab_find_slot (htab, *tp, INSERT);
3680   if (*slot)
3681     return *slot;
3682   *slot = *tp;
3683
3684   return NULL;
3685 }
3686
3687
3688 /* Verify the GIMPLE statement chain.  */
3689
3690 void
3691 verify_stmts (void)
3692 {
3693   basic_block bb;
3694   block_stmt_iterator bsi;
3695   bool err = false;
3696   htab_t htab;
3697   tree addr;
3698
3699   timevar_push (TV_TREE_STMT_VERIFY);
3700   htab = htab_create (37, htab_hash_pointer, htab_eq_pointer, NULL);
3701
3702   FOR_EACH_BB (bb)
3703     {
3704       tree phi;
3705       int i;
3706
3707       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
3708         {
3709           int phi_num_args = PHI_NUM_ARGS (phi);
3710
3711           if (bb_for_stmt (phi) != bb)
3712             {
3713               error ("bb_for_stmt (phi) is set to a wrong basic block\n");
3714               err |= true;
3715             }
3716
3717           for (i = 0; i < phi_num_args; i++)
3718             {
3719               tree t = PHI_ARG_DEF (phi, i);
3720               tree addr;
3721
3722               /* Addressable variables do have SSA_NAMEs but they
3723                  are not considered gimple values.  */
3724               if (TREE_CODE (t) != SSA_NAME
3725                   && TREE_CODE (t) != FUNCTION_DECL
3726                   && !is_gimple_val (t))
3727                 {
3728                   error ("PHI def is not a GIMPLE value");
3729                   debug_generic_stmt (phi);
3730                   debug_generic_stmt (t);
3731                   err |= true;
3732                 }
3733
3734               addr = walk_tree (&t, verify_expr, (void *) 1, NULL);
3735               if (addr)
3736                 {
3737                   debug_generic_stmt (addr);
3738                   err |= true;
3739                 }
3740
3741               addr = walk_tree (&t, verify_node_sharing, htab, NULL);
3742               if (addr)
3743                 {
3744                   error ("Incorrect sharing of tree nodes");
3745                   debug_generic_stmt (phi);
3746                   debug_generic_stmt (addr);
3747                   err |= true;
3748                 }
3749             }
3750         }
3751
3752       for (bsi = bsi_start (bb); !bsi_end_p (bsi); )
3753         {
3754           tree stmt = bsi_stmt (bsi);
3755
3756           if (bb_for_stmt (stmt) != bb)
3757             {
3758               error ("bb_for_stmt (stmt) is set to a wrong basic block\n");
3759               err |= true;
3760             }
3761
3762           bsi_next (&bsi);
3763           err |= verify_stmt (stmt, bsi_end_p (bsi));
3764           addr = walk_tree (&stmt, verify_node_sharing, htab, NULL);
3765           if (addr)
3766             {
3767               error ("Incorrect sharing of tree nodes");
3768               debug_generic_stmt (stmt);
3769               debug_generic_stmt (addr);
3770               err |= true;
3771             }
3772         }
3773     }
3774
3775   if (err)
3776     internal_error ("verify_stmts failed.");
3777
3778   htab_delete (htab);
3779   timevar_pop (TV_TREE_STMT_VERIFY);
3780 }
3781
3782
3783 /* Verifies that the flow information is OK.  */
3784
3785 static int
3786 tree_verify_flow_info (void)
3787 {
3788   int err = 0;
3789   basic_block bb;
3790   block_stmt_iterator bsi;
3791   tree stmt;
3792   edge e;
3793   edge_iterator ei;
3794
3795   if (ENTRY_BLOCK_PTR->stmt_list)
3796     {
3797       error ("ENTRY_BLOCK has a statement list associated with it\n");
3798       err = 1;
3799     }
3800
3801   if (EXIT_BLOCK_PTR->stmt_list)
3802     {
3803       error ("EXIT_BLOCK has a statement list associated with it\n");
3804       err = 1;
3805     }
3806
3807   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
3808     if (e->flags & EDGE_FALLTHRU)
3809       {
3810         error ("Fallthru to exit from bb %d\n", e->src->index);
3811         err = 1;
3812       }
3813
3814   FOR_EACH_BB (bb)
3815     {
3816       bool found_ctrl_stmt = false;
3817
3818       stmt = NULL_TREE;
3819
3820       /* Skip labels on the start of basic block.  */
3821       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3822         {
3823           tree prev_stmt = stmt;
3824
3825           stmt = bsi_stmt (bsi);
3826
3827           if (TREE_CODE (stmt) != LABEL_EXPR)
3828             break;
3829
3830           if (prev_stmt && DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
3831             {
3832               error ("Nonlocal label %s is not first "
3833                      "in a sequence of labels in bb %d",
3834                      IDENTIFIER_POINTER (DECL_NAME (LABEL_EXPR_LABEL (stmt))),
3835                      bb->index);
3836               err = 1;
3837             }
3838
3839           if (label_to_block (LABEL_EXPR_LABEL (stmt)) != bb)
3840             {
3841               error ("Label %s to block does not match in bb %d\n",
3842                      IDENTIFIER_POINTER (DECL_NAME (LABEL_EXPR_LABEL (stmt))),
3843                      bb->index);
3844               err = 1;
3845             }
3846
3847           if (decl_function_context (LABEL_EXPR_LABEL (stmt))
3848               != current_function_decl)
3849             {
3850               error ("Label %s has incorrect context in bb %d\n",
3851                      IDENTIFIER_POINTER (DECL_NAME (LABEL_EXPR_LABEL (stmt))),
3852                      bb->index);
3853               err = 1;
3854             }
3855         }
3856
3857       /* Verify that body of basic block BB is free of control flow.  */
3858       for (; !bsi_end_p (bsi); bsi_next (&bsi))
3859         {
3860           tree stmt = bsi_stmt (bsi);
3861
3862           if (found_ctrl_stmt)
3863             {
3864               error ("Control flow in the middle of basic block %d\n",
3865                      bb->index);
3866               err = 1;
3867             }
3868
3869           if (stmt_ends_bb_p (stmt))
3870             found_ctrl_stmt = true;
3871
3872           if (TREE_CODE (stmt) == LABEL_EXPR)
3873             {
3874               error ("Label %s in the middle of basic block %d\n",
3875                      IDENTIFIER_POINTER (DECL_NAME (stmt)),
3876                      bb->index);
3877               err = 1;
3878             }
3879         }
3880       bsi = bsi_last (bb);
3881       if (bsi_end_p (bsi))
3882         continue;
3883
3884       stmt = bsi_stmt (bsi);
3885
3886       if (is_ctrl_stmt (stmt))
3887         {
3888           FOR_EACH_EDGE (e, ei, bb->succs)
3889             if (e->flags & EDGE_FALLTHRU)
3890               {
3891                 error ("Fallthru edge after a control statement in bb %d \n",
3892                        bb->index);
3893                 err = 1;
3894               }
3895         }
3896
3897       switch (TREE_CODE (stmt))
3898         {
3899         case COND_EXPR:
3900           {
3901             edge true_edge;
3902             edge false_edge;
3903             if (TREE_CODE (COND_EXPR_THEN (stmt)) != GOTO_EXPR
3904                 || TREE_CODE (COND_EXPR_ELSE (stmt)) != GOTO_EXPR)
3905               {
3906                 error ("Structured COND_EXPR at the end of bb %d\n", bb->index);
3907                 err = 1;
3908               }
3909
3910             extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
3911
3912             if (!true_edge || !false_edge
3913                 || !(true_edge->flags & EDGE_TRUE_VALUE)
3914                 || !(false_edge->flags & EDGE_FALSE_VALUE)
3915                 || (true_edge->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL))
3916                 || (false_edge->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL))
3917                 || EDGE_COUNT (bb->succs) >= 3)
3918               {
3919                 error ("Wrong outgoing edge flags at end of bb %d\n",
3920                        bb->index);
3921                 err = 1;
3922               }
3923
3924             if (!has_label_p (true_edge->dest,
3925                               GOTO_DESTINATION (COND_EXPR_THEN (stmt))))
3926               {
3927                 error ("%<then%> label does not match edge at end of bb %d\n",
3928                        bb->index);
3929                 err = 1;
3930               }
3931
3932             if (!has_label_p (false_edge->dest,
3933                               GOTO_DESTINATION (COND_EXPR_ELSE (stmt))))
3934               {
3935                 error ("%<else%> label does not match edge at end of bb %d\n",
3936                        bb->index);
3937                 err = 1;
3938               }
3939           }
3940           break;
3941
3942         case GOTO_EXPR:
3943           if (simple_goto_p (stmt))
3944             {
3945               error ("Explicit goto at end of bb %d\n", bb->index);
3946               err = 1;
3947             }
3948           else
3949             {
3950               /* FIXME.  We should double check that the labels in the 
3951                  destination blocks have their address taken.  */
3952               FOR_EACH_EDGE (e, ei, bb->succs)
3953                 if ((e->flags & (EDGE_FALLTHRU | EDGE_TRUE_VALUE
3954                                  | EDGE_FALSE_VALUE))
3955                     || !(e->flags & EDGE_ABNORMAL))
3956                   {
3957                     error ("Wrong outgoing edge flags at end of bb %d\n",
3958                            bb->index);
3959                     err = 1;
3960                   }
3961             }
3962           break;
3963
3964         case RETURN_EXPR:
3965           if (!single_succ_p (bb)
3966               || (single_succ_edge (bb)->flags
3967                   & (EDGE_FALLTHRU | EDGE_ABNORMAL
3968                      | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
3969             {
3970               error ("Wrong outgoing edge flags at end of bb %d\n", bb->index);
3971               err = 1;
3972             }
3973           if (single_succ (bb) != EXIT_BLOCK_PTR)
3974             {
3975               error ("Return edge does not point to exit in bb %d\n",
3976                      bb->index);
3977               err = 1;
3978             }
3979           break;
3980
3981         case SWITCH_EXPR:
3982           {
3983             tree prev;
3984             edge e;
3985             size_t i, n;
3986             tree vec;
3987
3988             vec = SWITCH_LABELS (stmt);
3989             n = TREE_VEC_LENGTH (vec);
3990
3991             /* Mark all the destination basic blocks.  */
3992             for (i = 0; i < n; ++i)
3993               {
3994                 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
3995                 basic_block label_bb = label_to_block (lab);
3996
3997                 gcc_assert (!label_bb->aux || label_bb->aux == (void *)1);
3998                 label_bb->aux = (void *)1;
3999               }
4000
4001             /* Verify that the case labels are sorted.  */
4002             prev = TREE_VEC_ELT (vec, 0);
4003             for (i = 1; i < n - 1; ++i)
4004               {
4005                 tree c = TREE_VEC_ELT (vec, i);
4006                 if (! CASE_LOW (c))
4007                   {
4008                     error ("Found default case not at end of case vector");
4009                     err = 1;
4010                     continue;
4011                   }
4012                 if (! tree_int_cst_lt (CASE_LOW (prev), CASE_LOW (c)))
4013                   {
4014                     error ("Case labels not sorted:\n ");
4015                     print_generic_expr (stderr, prev, 0);
4016                     fprintf (stderr," is greater than ");
4017                     print_generic_expr (stderr, c, 0);
4018                     fprintf (stderr," but comes before it.\n");
4019                     err = 1;
4020                   }
4021                 prev = c;
4022               }
4023             if (CASE_LOW (TREE_VEC_ELT (vec, n - 1)))
4024               {
4025                 error ("No default case found at end of case vector");
4026                 err = 1;
4027               }
4028
4029             FOR_EACH_EDGE (e, ei, bb->succs)
4030               {
4031                 if (!e->dest->aux)
4032                   {
4033                     error ("Extra outgoing edge %d->%d\n",
4034                            bb->index, e->dest->index);
4035                     err = 1;
4036                   }
4037                 e->dest->aux = (void *)2;
4038                 if ((e->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL
4039                                  | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
4040                   {
4041                     error ("Wrong outgoing edge flags at end of bb %d\n",
4042                            bb->index);
4043                     err = 1;
4044                   }
4045               }
4046
4047             /* Check that we have all of them.  */
4048             for (i = 0; i < n; ++i)
4049               {
4050                 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
4051                 basic_block label_bb = label_to_block (lab);
4052
4053                 if (label_bb->aux != (void *)2)
4054                   {
4055                     error ("Missing edge %i->%i",
4056                            bb->index, label_bb->index);
4057                     err = 1;
4058                   }
4059               }
4060
4061             FOR_EACH_EDGE (e, ei, bb->succs)
4062               e->dest->aux = (void *)0;
4063           }
4064
4065         default: ;
4066         }
4067     }
4068
4069   if (dom_computed[CDI_DOMINATORS] >= DOM_NO_FAST_QUERY)
4070     verify_dominators (CDI_DOMINATORS);
4071
4072   return err;
4073 }
4074
4075
4076 /* Updates phi nodes after creating a forwarder block joined
4077    by edge FALLTHRU.  */
4078
4079 static void
4080 tree_make_forwarder_block (edge fallthru)
4081 {
4082   edge e;
4083   edge_iterator ei;
4084   basic_block dummy, bb;
4085   tree phi, new_phi, var;
4086
4087   dummy = fallthru->src;
4088   bb = fallthru->dest;
4089
4090   if (single_pred_p (bb))
4091     return;
4092
4093   /* If we redirected a branch we must create new phi nodes at the
4094      start of BB.  */
4095   for (phi = phi_nodes (dummy); phi; phi = PHI_CHAIN (phi))
4096     {
4097       var = PHI_RESULT (phi);
4098       new_phi = create_phi_node (var, bb);
4099       SSA_NAME_DEF_STMT (var) = new_phi;
4100       SET_PHI_RESULT (phi, make_ssa_name (SSA_NAME_VAR (var), phi));
4101       add_phi_arg (new_phi, PHI_RESULT (phi), fallthru);
4102     }
4103
4104   /* Ensure that the PHI node chain is in the same order.  */
4105   set_phi_nodes (bb, phi_reverse (phi_nodes (bb)));
4106
4107   /* Add the arguments we have stored on edges.  */
4108   FOR_EACH_EDGE (e, ei, bb->preds)
4109     {
4110       if (e == fallthru)
4111         continue;
4112
4113       flush_pending_stmts (e);
4114     }
4115 }
4116
4117
4118 /* Return true if basic block BB does nothing except pass control
4119    flow to another block and that we can safely insert a label at
4120    the start of the successor block.
4121
4122    As a precondition, we require that BB be not equal to
4123    ENTRY_BLOCK_PTR.  */
4124
4125 static bool
4126 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
4127 {
4128   block_stmt_iterator bsi;
4129
4130   /* BB must have a single outgoing edge.  */
4131   if (single_succ_p (bb) != 1
4132       /* If PHI_WANTED is false, BB must not have any PHI nodes.
4133          Otherwise, BB must have PHI nodes.  */
4134       || (phi_nodes (bb) != NULL_TREE) != phi_wanted
4135       /* BB may not be a predecessor of EXIT_BLOCK_PTR.  */
4136       || single_succ (bb) == EXIT_BLOCK_PTR
4137       /* Nor should this be an infinite loop.  */
4138       || single_succ (bb) == bb
4139       /* BB may not have an abnormal outgoing edge.  */
4140       || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
4141     return false; 
4142
4143 #if ENABLE_CHECKING
4144   gcc_assert (bb != ENTRY_BLOCK_PTR);
4145 #endif
4146
4147   /* Now walk through the statements backward.  We can ignore labels,
4148      anything else means this is not a forwarder block.  */
4149   for (bsi = bsi_last (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4150     {
4151       tree stmt = bsi_stmt (bsi);
4152  
4153       switch (TREE_CODE (stmt))
4154         {
4155         case LABEL_EXPR:
4156           if (DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
4157             return false;
4158           break;
4159
4160         default:
4161           return false;
4162         }
4163     }
4164
4165   if (find_edge (ENTRY_BLOCK_PTR, bb))
4166     return false;
4167
4168   if (current_loops)
4169     { 
4170       basic_block dest;
4171       /* Protect loop latches, headers and preheaders.  */
4172       if (bb->loop_father->header == bb)
4173         return false;
4174       dest = EDGE_SUCC (bb, 0)->dest;
4175  
4176       if (dest->loop_father->header == dest)
4177         return false;
4178     }
4179
4180   return true;
4181 }
4182
4183 /* Return true if BB has at least one abnormal incoming edge.  */
4184
4185 static inline bool
4186 has_abnormal_incoming_edge_p (basic_block bb)
4187 {
4188   edge e;
4189   edge_iterator ei;
4190
4191   FOR_EACH_EDGE (e, ei, bb->preds)
4192     if (e->flags & EDGE_ABNORMAL)
4193       return true;
4194
4195   return false;
4196 }
4197
4198 /* Removes forwarder block BB.  Returns false if this failed.  If a new
4199    forwarder block is created due to redirection of edges, it is
4200    stored to worklist.  */
4201
4202 static bool
4203 remove_forwarder_block (basic_block bb, basic_block **worklist)
4204 {
4205   edge succ = single_succ_edge (bb), e, s;
4206   basic_block dest = succ->dest;
4207   tree label;
4208   tree phi;
4209   edge_iterator ei;
4210   block_stmt_iterator bsi, bsi_to;
4211   bool seen_abnormal_edge = false;
4212
4213   /* We check for infinite loops already in tree_forwarder_block_p.
4214      However it may happen that the infinite loop is created
4215      afterwards due to removal of forwarders.  */
4216   if (dest == bb)
4217     return false;
4218
4219   /* If the destination block consists of a nonlocal label, do not merge
4220      it.  */
4221   label = first_stmt (dest);
4222   if (label
4223       && TREE_CODE (label) == LABEL_EXPR
4224       && DECL_NONLOCAL (LABEL_EXPR_LABEL (label)))
4225     return false;
4226
4227   /* If there is an abnormal edge to basic block BB, but not into
4228      dest, problems might occur during removal of the phi node at out
4229      of ssa due to overlapping live ranges of registers.
4230
4231      If there is an abnormal edge in DEST, the problems would occur
4232      anyway since cleanup_dead_labels would then merge the labels for
4233      two different eh regions, and rest of exception handling code
4234      does not like it.
4235      
4236      So if there is an abnormal edge to BB, proceed only if there is
4237      no abnormal edge to DEST and there are no phi nodes in DEST.  */
4238   if (has_abnormal_incoming_edge_p (bb))
4239     {
4240       seen_abnormal_edge = true;
4241
4242       if (has_abnormal_incoming_edge_p (dest)
4243           || phi_nodes (dest) != NULL_TREE)
4244         return false;
4245     }
4246
4247   /* If there are phi nodes in DEST, and some of the blocks that are
4248      predecessors of BB are also predecessors of DEST, check that the
4249      phi node arguments match.  */
4250   if (phi_nodes (dest))
4251     {
4252       FOR_EACH_EDGE (e, ei, bb->preds)
4253         {
4254           s = find_edge (e->src, dest);
4255           if (!s)
4256             continue;
4257
4258           if (!phi_alternatives_equal (dest, succ, s))
4259             return false;
4260         }
4261     }
4262
4263   /* Redirect the edges.  */
4264   for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4265     {
4266       if (e->flags & EDGE_ABNORMAL)
4267         {
4268           /* If there is an abnormal edge, redirect it anyway, and
4269              move the labels to the new block to make it legal.  */
4270           s = redirect_edge_succ_nodup (e, dest);
4271         }
4272       else
4273         s = redirect_edge_and_branch (e, dest);
4274
4275       if (s == e)
4276         {
4277           /* Create arguments for the phi nodes, since the edge was not
4278              here before.  */
4279           for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
4280             add_phi_arg (phi, PHI_ARG_DEF (phi, succ->dest_idx), s);
4281         }
4282       else
4283         {
4284           /* The source basic block might become a forwarder.  We know
4285              that it was not a forwarder before, since it used to have
4286              at least two outgoing edges, so we may just add it to
4287              worklist.  */
4288           if (tree_forwarder_block_p (s->src, false))
4289             *(*worklist)++ = s->src;
4290         }
4291     }
4292
4293   if (seen_abnormal_edge)
4294     {
4295       /* Move the labels to the new block, so that the redirection of
4296          the abnormal edges works.  */
4297
4298       bsi_to = bsi_start (dest);
4299       for (bsi = bsi_start (bb); !bsi_end_p (bsi); )
4300         {
4301           label = bsi_stmt (bsi);
4302           gcc_assert (TREE_CODE (label) == LABEL_EXPR);
4303           bsi_remove (&bsi);
4304           bsi_insert_before (&bsi_to, label, BSI_CONTINUE_LINKING);
4305         }
4306     }
4307
4308   /* Update the dominators.  */
4309   if (dom_info_available_p (CDI_DOMINATORS))
4310     {
4311       basic_block dom, dombb, domdest;
4312
4313       dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
4314       domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
4315       if (domdest == bb)
4316         {
4317           /* Shortcut to avoid calling (relatively expensive)
4318              nearest_common_dominator unless necessary.  */
4319           dom = dombb;
4320         }
4321       else
4322         dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
4323
4324       set_immediate_dominator (CDI_DOMINATORS, dest, dom);
4325     }
4326
4327   /* And kill the forwarder block.  */
4328   delete_basic_block (bb);
4329
4330   return true;
4331 }
4332
4333 /* Removes forwarder blocks.  */
4334
4335 static bool
4336 cleanup_forwarder_blocks (void)
4337 {
4338   basic_block bb;
4339   bool changed = false;
4340   basic_block *worklist = xmalloc (sizeof (basic_block) * n_basic_blocks);
4341   basic_block *current = worklist;
4342
4343   FOR_EACH_BB (bb)
4344     {
4345       if (tree_forwarder_block_p (bb, false))
4346         *current++ = bb;
4347     }
4348
4349   while (current != worklist)
4350     {
4351       bb = *--current;
4352       changed |= remove_forwarder_block (bb, &current);
4353     }
4354
4355   free (worklist);
4356   return changed;
4357 }
4358
4359 /* Merge the PHI nodes at BB into those at BB's sole successor.  */
4360
4361 static void
4362 remove_forwarder_block_with_phi (basic_block bb)
4363 {
4364   edge succ = single_succ_edge (bb);
4365   basic_block dest = succ->dest;
4366   tree label;
4367   basic_block dombb, domdest, dom;
4368
4369   /* We check for infinite loops already in tree_forwarder_block_p.
4370      However it may happen that the infinite loop is created
4371      afterwards due to removal of forwarders.  */
4372   if (dest == bb)
4373     return;
4374
4375   /* If the destination block consists of a nonlocal label, do not
4376      merge it.  */
4377   label = first_stmt (dest);
4378   if (label
4379       && TREE_CODE (label) == LABEL_EXPR
4380       && DECL_NONLOCAL (LABEL_EXPR_LABEL (label)))
4381     return;
4382
4383   /* Redirect each incoming edge to BB to DEST.  */
4384   while (EDGE_COUNT (bb->preds) > 0)
4385     {
4386       edge e = EDGE_PRED (bb, 0), s;
4387       tree phi;
4388
4389       s = find_edge (e->src, dest);
4390       if (s)
4391         {
4392           /* We already have an edge S from E->src to DEST.  If S and
4393              E->dest's sole successor edge have the same PHI arguments
4394              at DEST, redirect S to DEST.  */
4395           if (phi_alternatives_equal (dest, s, succ))
4396             {
4397               e = redirect_edge_and_branch (e, dest);
4398               PENDING_STMT (e) = NULL_TREE;
4399               continue;
4400             }
4401
4402           /* PHI arguments are different.  Create a forwarder block by
4403              splitting E so that we can merge PHI arguments on E to
4404              DEST.  */
4405           e = single_succ_edge (split_edge (e));
4406         }
4407
4408       s = redirect_edge_and_branch (e, dest);
4409
4410       /* redirect_edge_and_branch must not create a new edge.  */
4411       gcc_assert (s == e);
4412
4413       /* Add to the PHI nodes at DEST each PHI argument removed at the
4414          destination of E.  */
4415       for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
4416         {
4417           tree def = PHI_ARG_DEF (phi, succ->dest_idx);
4418
4419           if (TREE_CODE (def) == SSA_NAME)
4420             {
4421               tree var;
4422
4423               /* If DEF is one of the results of PHI nodes removed during
4424                  redirection, replace it with the PHI argument that used
4425                  to be on E.  */
4426               for (var = PENDING_STMT (e); var; var = TREE_CHAIN (var))
4427                 {
4428                   tree old_arg = TREE_PURPOSE (var);
4429                   tree new_arg = TREE_VALUE (var);
4430
4431                   if (def == old_arg)
4432                     {
4433                       def = new_arg;
4434                       break;
4435                     }
4436                 }
4437             }
4438
4439           add_phi_arg (phi, def, s);
4440         }
4441
4442       PENDING_STMT (e) = NULL;
4443     }
4444
4445   /* Update the dominators.  */
4446   dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
4447   domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
4448   if (domdest == bb)
4449     {
4450       /* Shortcut to avoid calling (relatively expensive)
4451          nearest_common_dominator unless necessary.  */
4452       dom = dombb;
4453     }
4454   else
4455     dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
4456
4457   set_immediate_dominator (CDI_DOMINATORS, dest, dom);
4458   
4459   /* Remove BB since all of BB's incoming edges have been redirected
4460      to DEST.  */
4461   delete_basic_block (bb);
4462 }
4463
4464 /* This pass merges PHI nodes if one feeds into another.  For example,
4465    suppose we have the following:
4466
4467   goto <bb 9> (<L9>);
4468
4469 <L8>:;
4470   tem_17 = foo ();
4471
4472   # tem_6 = PHI <tem_17(8), tem_23(7)>;
4473 <L9>:;
4474
4475   # tem_3 = PHI <tem_6(9), tem_2(5)>;
4476 <L10>:;
4477
4478   Then we merge the first PHI node into the second one like so:
4479
4480   goto <bb 9> (<L10>);
4481
4482 <L8>:;
4483   tem_17 = foo ();
4484
4485   # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
4486 <L10>:;
4487 */
4488
4489 static void
4490 merge_phi_nodes (void)
4491 {
4492   basic_block *worklist = xmalloc (sizeof (basic_block) * n_basic_blocks);
4493   basic_block *current = worklist;
4494   basic_block bb;
4495
4496   calculate_dominance_info (CDI_DOMINATORS);
4497
4498   /* Find all PHI nodes that we may be able to merge.  */
4499   FOR_EACH_BB (bb)
4500     {
4501       basic_block dest;
4502
4503       /* Look for a forwarder block with PHI nodes.  */
4504       if (!tree_forwarder_block_p (bb, true))
4505         continue;
4506
4507       dest = single_succ (bb);
4508
4509       /* We have to feed into another basic block with PHI
4510          nodes.  */
4511       if (!phi_nodes (dest)
4512           /* We don't want to deal with a basic block with
4513              abnormal edges.  */
4514           || has_abnormal_incoming_edge_p (bb))
4515         continue;
4516
4517       if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
4518         {
4519           /* If BB does not dominate DEST, then the PHI nodes at
4520              DEST must be the only users of the results of the PHI
4521              nodes at BB.  */
4522           *current++ = bb;
4523         }
4524     }
4525
4526   /* Now let's drain WORKLIST.  */
4527   while (current != worklist)
4528     {
4529       bb = *--current;
4530       remove_forwarder_block_with_phi (bb);
4531     }
4532
4533   free (worklist);
4534 }
4535
4536 static bool
4537 gate_merge_phi (void)
4538 {
4539   return 1;
4540 }
4541
4542 struct tree_opt_pass pass_merge_phi = {
4543   "mergephi",                   /* name */
4544   gate_merge_phi,               /* gate */
4545   merge_phi_nodes,              /* execute */
4546   NULL,                         /* sub */
4547   NULL,                         /* next */
4548   0,                            /* static_pass_number */
4549   TV_TREE_MERGE_PHI,            /* tv_id */
4550   PROP_cfg | PROP_ssa,          /* properties_required */
4551   0,                            /* properties_provided */
4552   0,                            /* properties_destroyed */
4553   0,                            /* todo_flags_start */
4554   TODO_dump_func | TODO_ggc_collect     /* todo_flags_finish */
4555   | TODO_verify_ssa,
4556   0                             /* letter */
4557 };
4558
4559 /* Return a non-special label in the head of basic block BLOCK.
4560    Create one if it doesn't exist.  */
4561
4562 tree
4563 tree_block_label (basic_block bb)
4564 {
4565   block_stmt_iterator i, s = bsi_start (bb);
4566   bool first = true;
4567   tree label, stmt;
4568
4569   for (i = s; !bsi_end_p (i); first = false, bsi_next (&i))
4570     {
4571       stmt = bsi_stmt (i);
4572       if (TREE_CODE (stmt) != LABEL_EXPR)
4573         break;
4574       label = LABEL_EXPR_LABEL (stmt);
4575       if (!DECL_NONLOCAL (label))
4576         {
4577           if (!first)
4578             bsi_move_before (&i, &s);
4579           return label;
4580         }
4581     }
4582
4583   label = create_artificial_label ();
4584   stmt = build1 (LABEL_EXPR, void_type_node, label);
4585   bsi_insert_before (&s, stmt, BSI_NEW_STMT);
4586   return label;
4587 }
4588
4589
4590 /* Attempt to perform edge redirection by replacing a possibly complex
4591    jump instruction by a goto or by removing the jump completely.
4592    This can apply only if all edges now point to the same block.  The
4593    parameters and return values are equivalent to
4594    redirect_edge_and_branch.  */
4595
4596 static edge
4597 tree_try_redirect_by_replacing_jump (edge e, basic_block target)
4598 {
4599   basic_block src = e->src;
4600   block_stmt_iterator b;
4601   tree stmt;
4602
4603   /* We can replace or remove a complex jump only when we have exactly
4604      two edges.  */
4605   if (EDGE_COUNT (src->succs) != 2
4606       /* Verify that all targets will be TARGET.  Specifically, the
4607          edge that is not E must also go to TARGET.  */
4608       || EDGE_SUCC (src, EDGE_SUCC (src, 0) == e)->dest != target)
4609     return NULL;
4610
4611   b = bsi_last (src);
4612   if (bsi_end_p (b))
4613     return NULL;
4614   stmt = bsi_stmt (b);
4615
4616   if (TREE_CODE (stmt) == COND_EXPR
4617       || TREE_CODE (stmt) == SWITCH_EXPR)
4618     {
4619       bsi_remove (&b);
4620       e = ssa_redirect_edge (e, target);
4621       e->flags = EDGE_FALLTHRU;
4622       return e;
4623     }
4624
4625   return NULL;
4626 }
4627
4628
4629 /* Redirect E to DEST.  Return NULL on failure.  Otherwise, return the
4630    edge representing the redirected branch.  */
4631
4632 static edge
4633 tree_redirect_edge_and_branch (edge e, basic_block dest)
4634 {
4635   basic_block bb = e->src;
4636   block_stmt_iterator bsi;
4637   edge ret;
4638   tree label, stmt;
4639
4640   if (e->flags & (EDGE_ABNORMAL_CALL | EDGE_EH))
4641     return NULL;
4642
4643   if (e->src != ENTRY_BLOCK_PTR 
4644       && (ret = tree_try_redirect_by_replacing_jump (e, dest)))
4645     return ret;
4646
4647   if (e->dest == dest)
4648     return NULL;
4649
4650   label = tree_block_label (dest);
4651
4652   bsi = bsi_last (bb);
4653   stmt = bsi_end_p (bsi) ? NULL : bsi_stmt (bsi);
4654
4655   switch (stmt ? TREE_CODE (stmt) : ERROR_MARK)
4656     {
4657     case COND_EXPR:
4658       stmt = (e->flags & EDGE_TRUE_VALUE
4659               ? COND_EXPR_THEN (stmt)
4660               : COND_EXPR_ELSE (stmt));
4661       GOTO_DESTINATION (stmt) = label;
4662       break;
4663
4664     case GOTO_EXPR:
4665       /* No non-abnormal edges should lead from a non-simple goto, and
4666          simple ones should be represented implicitly.  */
4667       gcc_unreachable ();
4668
4669     case SWITCH_EXPR:
4670       {
4671         tree cases = get_cases_for_edge (e, stmt);
4672
4673         /* If we have a list of cases associated with E, then use it
4674            as it's a lot faster than walking the entire case vector.  */
4675         if (cases)
4676           {
4677             edge e2 = find_edge (e->src, dest);
4678             tree last, first;
4679
4680             first = cases;
4681             while (cases)
4682               {
4683                 last = cases;
4684                 CASE_LABEL (cases) = label;
4685                 cases = TREE_CHAIN (cases);
4686               }
4687
4688             /* If there was already an edge in the CFG, then we need
4689                to move all the cases associated with E to E2.  */
4690             if (e2)
4691               {
4692                 tree cases2 = get_cases_for_edge (e2, stmt);
4693
4694                 TREE_CHAIN (last) = TREE_CHAIN (cases2);
4695                 TREE_CHAIN (cases2) = first;
4696               }
4697           }
4698         else
4699           {
4700             tree vec = SWITCH_LABELS (stmt);
4701             size_t i, n = TREE_VEC_LENGTH (vec);
4702
4703             for (i = 0; i < n; i++)
4704               {
4705                 tree elt = TREE_VEC_ELT (vec, i);
4706
4707                 if (label_to_block (CASE_LABEL (elt)) == e->dest)
4708                   CASE_LABEL (elt) = label;
4709               }
4710           }
4711
4712         break;
4713       }
4714
4715     case RETURN_EXPR:
4716       bsi_remove (&bsi);
4717       e->flags |= EDGE_FALLTHRU;
4718       break;
4719
4720     default:
4721       /* Otherwise it must be a fallthru edge, and we don't need to
4722          do anything besides redirecting it.  */
4723       gcc_assert (e->flags & EDGE_FALLTHRU);
4724       break;
4725     }
4726
4727   /* Update/insert PHI nodes as necessary.  */
4728
4729   /* Now update the edges in the CFG.  */
4730   e = ssa_redirect_edge (e, dest);
4731
4732   return e;
4733 }
4734
4735
4736 /* Simple wrapper, as we can always redirect fallthru edges.  */
4737
4738 static basic_block
4739 tree_redirect_edge_and_branch_force (edge e, basic_block dest)
4740 {
4741   e = tree_redirect_edge_and_branch (e, dest);
4742   gcc_assert (e);
4743
4744   return NULL;
4745 }
4746
4747
4748 /* Splits basic block BB after statement STMT (but at least after the
4749    labels).  If STMT is NULL, BB is split just after the labels.  */
4750
4751 static basic_block
4752 tree_split_block (basic_block bb, void *stmt)
4753 {
4754   block_stmt_iterator bsi, bsi_tgt;
4755   tree act;
4756   basic_block new_bb;
4757   edge e;
4758   edge_iterator ei;
4759
4760   new_bb = create_empty_bb (bb);
4761
4762   /* Redirect the outgoing edges.  */
4763   new_bb->succs = bb->succs;
4764   bb->succs = NULL;
4765   FOR_EACH_EDGE (e, ei, new_bb->succs)
4766     e->src = new_bb;
4767
4768   if (stmt && TREE_CODE ((tree) stmt) == LABEL_EXPR)
4769     stmt = NULL;
4770
4771   /* Move everything from BSI to the new basic block.  */
4772   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4773     {
4774       act = bsi_stmt (bsi);
4775       if (TREE_CODE (act) == LABEL_EXPR)
4776         continue;
4777
4778       if (!stmt)
4779         break;
4780
4781       if (stmt == act)
4782         {
4783           bsi_next (&bsi);
4784           break;
4785         }
4786     }
4787
4788   bsi_tgt = bsi_start (new_bb);
4789   while (!bsi_end_p (bsi))
4790     {
4791       act = bsi_stmt (bsi);
4792       bsi_remove (&bsi);
4793       bsi_insert_after (&bsi_tgt, act, BSI_NEW_STMT);
4794     }
4795
4796   return new_bb;
4797 }
4798
4799
4800 /* Moves basic block BB after block AFTER.  */
4801
4802 static bool
4803 tree_move_block_after (basic_block bb, basic_block after)
4804 {
4805   if (bb->prev_bb == after)
4806     return true;
4807
4808   unlink_block (bb);
4809   link_block (bb, after);
4810
4811   return true;
4812 }
4813
4814
4815 /* Return true if basic_block can be duplicated.  */
4816
4817 static bool
4818 tree_can_duplicate_bb_p (basic_block bb ATTRIBUTE_UNUSED)
4819 {
4820   return true;
4821 }
4822
4823 /* Create a duplicate of the basic block BB.  NOTE: This does not
4824    preserve SSA form.  */
4825
4826 static basic_block
4827 tree_duplicate_bb (basic_block bb)
4828 {
4829   basic_block new_bb;
4830   block_stmt_iterator bsi, bsi_tgt;
4831   tree phi, val;
4832   ssa_op_iter op_iter;
4833
4834   new_bb = create_empty_bb (EXIT_BLOCK_PTR->prev_bb);
4835
4836   /* First copy the phi nodes.  We do not copy phi node arguments here,
4837      since the edges are not ready yet.  Keep the chain of phi nodes in
4838      the same order, so that we can add them later.  */
4839   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
4840     {
4841       mark_for_rewrite (PHI_RESULT (phi));
4842       create_phi_node (PHI_RESULT (phi), new_bb);
4843     }
4844   set_phi_nodes (new_bb, phi_reverse (phi_nodes (new_bb)));
4845
4846   bsi_tgt = bsi_start (new_bb);
4847   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4848     {
4849       tree stmt = bsi_stmt (bsi);
4850       tree copy;
4851
4852       if (TREE_CODE (stmt) == LABEL_EXPR)
4853         continue;
4854
4855       /* Record the definitions.  */
4856       get_stmt_operands (stmt);
4857
4858       FOR_EACH_SSA_TREE_OPERAND (val, stmt, op_iter, SSA_OP_ALL_DEFS)
4859         mark_for_rewrite (val);
4860
4861       copy = unshare_expr (stmt);
4862
4863       /* Copy also the virtual operands.  */
4864       get_stmt_ann (copy);
4865       copy_virtual_operands (copy, stmt);
4866       
4867       bsi_insert_after (&bsi_tgt, copy, BSI_NEW_STMT);
4868     }
4869
4870   return new_bb;
4871 }
4872
4873 /* Basic block BB_COPY was created by code duplication.  Add phi node
4874    arguments for edges going out of BB_COPY.  The blocks that were
4875    duplicated have rbi->duplicated set to one.  */
4876
4877 void
4878 add_phi_args_after_copy_bb (basic_block bb_copy)
4879 {
4880   basic_block bb, dest;
4881   edge e, e_copy;
4882   edge_iterator ei;
4883   tree phi, phi_copy, phi_next, def;
4884       
4885   bb = bb_copy->rbi->original;
4886
4887   FOR_EACH_EDGE (e_copy, ei, bb_copy->succs)
4888     {
4889       if (!phi_nodes (e_copy->dest))
4890         continue;
4891
4892       if (e_copy->dest->rbi->duplicated)
4893         dest = e_copy->dest->rbi->original;
4894       else
4895         dest = e_copy->dest;
4896
4897       e = find_edge (bb, dest);
4898       if (!e)
4899         {
4900           /* During loop unrolling the target of the latch edge is copied.
4901              In this case we are not looking for edge to dest, but to
4902              duplicated block whose original was dest.  */
4903           FOR_EACH_EDGE (e, ei, bb->succs)
4904             if (e->dest->rbi->duplicated
4905                 && e->dest->rbi->original == dest)
4906               break;
4907
4908           gcc_assert (e != NULL);
4909         }
4910
4911       for (phi = phi_nodes (e->dest), phi_copy = phi_nodes (e_copy->dest);
4912            phi;
4913            phi = phi_next, phi_copy = PHI_CHAIN (phi_copy))
4914         {
4915           phi_next = PHI_CHAIN (phi);
4916
4917           gcc_assert (PHI_RESULT (phi) == PHI_RESULT (phi_copy));
4918           def = PHI_ARG_DEF_FROM_EDGE (phi, e);
4919           add_phi_arg (phi_copy, def, e_copy);
4920         }
4921     }
4922 }
4923
4924 /* Blocks in REGION_COPY array of length N_REGION were created by
4925    duplication of basic blocks.  Add phi node arguments for edges
4926    going from these blocks.  */
4927
4928 void
4929 add_phi_args_after_copy (basic_block *region_copy, unsigned n_region)
4930 {
4931   unsigned i;
4932
4933   for (i = 0; i < n_region; i++)
4934     region_copy[i]->rbi->duplicated = 1;
4935
4936   for (i = 0; i < n_region; i++)
4937     add_phi_args_after_copy_bb (region_copy[i]);
4938
4939   for (i = 0; i < n_region; i++)
4940     region_copy[i]->rbi->duplicated = 0;
4941 }
4942
4943 /* Maps the old ssa name FROM_NAME to TO_NAME.  */
4944
4945 struct ssa_name_map_entry
4946 {
4947   tree from_name;
4948   tree to_name;
4949 };
4950
4951 /* Hash function for ssa_name_map_entry.  */
4952
4953 static hashval_t
4954 ssa_name_map_entry_hash (const void *entry)
4955 {
4956   const struct ssa_name_map_entry *en = entry;
4957   return SSA_NAME_VERSION (en->from_name);
4958 }
4959
4960 /* Equality function for ssa_name_map_entry.  */
4961
4962 static int
4963 ssa_name_map_entry_eq (const void *in_table, const void *ssa_name)
4964 {
4965   const struct ssa_name_map_entry *en = in_table;
4966
4967   return en->from_name == ssa_name;
4968 }
4969
4970 /* Allocate duplicates of ssa names in list DEFINITIONS and store the mapping
4971    to MAP.  */
4972
4973 void
4974 allocate_ssa_names (bitmap definitions, htab_t *map)
4975 {
4976   tree name;
4977   struct ssa_name_map_entry *entry;
4978   PTR *slot;
4979   unsigned ver;
4980   bitmap_iterator bi;
4981
4982   if (!*map)
4983     *map = htab_create (10, ssa_name_map_entry_hash,
4984                         ssa_name_map_entry_eq, free);
4985   EXECUTE_IF_SET_IN_BITMAP (definitions, 0, ver, bi)
4986     {
4987       name = ssa_name (ver);
4988       slot = htab_find_slot_with_hash (*map, name, SSA_NAME_VERSION (name),
4989                                        INSERT);
4990       if (*slot)
4991         entry = *slot;
4992       else
4993         {
4994           entry = xmalloc (sizeof (struct ssa_name_map_entry));
4995           entry->from_name = name;
4996           *slot = entry;
4997         }
4998       entry->to_name = duplicate_ssa_name (name, SSA_NAME_DEF_STMT (name));
4999     }
5000 }
5001
5002 /* Rewrite the definition DEF in statement STMT to new ssa name as specified
5003    by the mapping MAP.  */
5004
5005 static void
5006 rewrite_to_new_ssa_names_def (def_operand_p def, tree stmt, htab_t map)
5007 {
5008   tree name = DEF_FROM_PTR (def);
5009   struct ssa_name_map_entry *entry;
5010
5011   gcc_assert (TREE_CODE (name) == SSA_NAME);
5012
5013   entry = htab_find_with_hash (map, name, SSA_NAME_VERSION (name));
5014   if (!entry)
5015     return;
5016
5017   SET_DEF (def, entry->to_name);
5018   SSA_NAME_DEF_STMT (entry->to_name) = stmt;
5019 }
5020
5021 /* Rewrite the USE to new ssa name as specified by the mapping MAP.  */
5022
5023 static void
5024 rewrite_to_new_ssa_names_use (use_operand_p use, htab_t map)
5025 {
5026   tree name = USE_FROM_PTR (use);
5027   struct ssa_name_map_entry *entry;
5028
5029   if (TREE_CODE (name) != SSA_NAME)
5030     return;
5031
5032   entry = htab_find_with_hash (map, name, SSA_NAME_VERSION (name));
5033   if (!entry)
5034     return;
5035
5036   SET_USE (use, entry->to_name);
5037 }
5038
5039 /* Rewrite the ssa names in basic block BB to new ones as specified by the
5040    mapping MAP.  */
5041
5042 void
5043 rewrite_to_new_ssa_names_bb (basic_block bb, htab_t map)
5044 {
5045   unsigned i;
5046   edge e;
5047   edge_iterator ei;
5048   tree phi, stmt;
5049   block_stmt_iterator bsi;
5050   use_optype uses;
5051   vuse_optype vuses;
5052   def_optype defs;
5053   v_may_def_optype v_may_defs;
5054   v_must_def_optype v_must_defs;
5055   stmt_ann_t ann;
5056
5057   FOR_EACH_EDGE (e, ei, bb->preds)
5058     if (e->flags & EDGE_ABNORMAL)
5059       break;
5060
5061   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
5062     {
5063       rewrite_to_new_ssa_names_def (PHI_RESULT_PTR (phi), phi, map);
5064       if (e)
5065         SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)) = 1;
5066     }
5067
5068   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
5069     {
5070       stmt = bsi_stmt (bsi);
5071       get_stmt_operands (stmt);
5072       ann = stmt_ann (stmt);
5073
5074       uses = USE_OPS (ann);
5075       for (i = 0; i < NUM_USES (uses); i++)
5076         rewrite_to_new_ssa_names_use (USE_OP_PTR (uses, i), map);
5077
5078       defs = DEF_OPS (ann);
5079       for (i = 0; i < NUM_DEFS (defs); i++)
5080         rewrite_to_new_ssa_names_def (DEF_OP_PTR (defs, i), stmt, map);
5081
5082       vuses = VUSE_OPS (ann);
5083       for (i = 0; i < NUM_VUSES (vuses); i++)
5084         rewrite_to_new_ssa_names_use (VUSE_OP_PTR (vuses, i), map);
5085
5086       v_may_defs = V_MAY_DEF_OPS (ann);
5087       for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
5088         {
5089           rewrite_to_new_ssa_names_use
5090                   (V_MAY_DEF_OP_PTR (v_may_defs, i), map);
5091           rewrite_to_new_ssa_names_def
5092                   (V_MAY_DEF_RESULT_PTR (v_may_defs, i), stmt, map);
5093         }
5094
5095       v_must_defs = V_MUST_DEF_OPS (ann);
5096       for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
5097         {
5098           rewrite_to_new_ssa_names_def
5099             (V_MUST_DEF_RESULT_PTR (v_must_defs, i), stmt, map);
5100           rewrite_to_new_ssa_names_use
5101             (V_MUST_DEF_KILL_PTR (v_must_defs, i),  map);
5102         }
5103     }
5104
5105   FOR_EACH_EDGE (e, ei, bb->succs)
5106     for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
5107       {
5108         rewrite_to_new_ssa_names_use
5109                 (PHI_ARG_DEF_PTR_FROM_EDGE (phi, e), map);
5110
5111         if (e->flags & EDGE_ABNORMAL)
5112           {
5113             tree op = PHI_ARG_DEF_FROM_EDGE (phi, e);
5114             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op) = 1;
5115           }
5116       }
5117 }
5118
5119 /* Rewrite the ssa names in N_REGION blocks REGION to the new ones as specified
5120    by the mapping MAP.  */
5121
5122 void
5123 rewrite_to_new_ssa_names (basic_block *region, unsigned n_region, htab_t map)
5124 {
5125   unsigned r;
5126
5127   for (r = 0; r < n_region; r++)
5128     rewrite_to_new_ssa_names_bb (region[r], map);
5129 }
5130
5131 /* Duplicates a REGION (set of N_REGION basic blocks) with just a single
5132    important exit edge EXIT.  By important we mean that no SSA name defined
5133    inside region is live over the other exit edges of the region.  All entry
5134    edges to the region must go to ENTRY->dest.  The edge ENTRY is redirected
5135    to the duplicate of the region.  SSA form, dominance and loop information
5136    is updated.  The new basic blocks are stored to REGION_COPY in the same
5137    order as they had in REGION, provided that REGION_COPY is not NULL.
5138    The function returns false if it is unable to copy the region,
5139    true otherwise.  */
5140
5141 bool
5142 tree_duplicate_sese_region (edge entry, edge exit,
5143                             basic_block *region, unsigned n_region,
5144                             basic_block *region_copy)
5145 {
5146   unsigned i, n_doms, ver;
5147   bool free_region_copy = false, copying_header = false;
5148   struct loop *loop = entry->dest->loop_father;
5149   edge exit_copy;
5150   bitmap definitions;
5151   tree phi;
5152   basic_block *doms;
5153   htab_t ssa_name_map = NULL;
5154   edge redirected;
5155   bitmap_iterator bi;
5156
5157   if (!can_copy_bbs_p (region, n_region))
5158     return false;
5159
5160   /* Some sanity checking.  Note that we do not check for all possible
5161      missuses of the functions.  I.e. if you ask to copy something weird,
5162      it will work, but the state of structures probably will not be
5163      correct.  */
5164
5165   for (i = 0; i < n_region; i++)
5166     {
5167       /* We do not handle subloops, i.e. all the blocks must belong to the
5168          same loop.  */
5169       if (region[i]->loop_father != loop)
5170         return false;
5171
5172       if (region[i] != entry->dest
5173           && region[i] == loop->header)
5174         return false;
5175     }
5176
5177   loop->copy = loop;
5178
5179   /* In case the function is used for loop header copying (which is the primary
5180      use), ensure that EXIT and its copy will be new latch and entry edges.  */
5181   if (loop->header == entry->dest)
5182     {
5183       copying_header = true;
5184       loop->copy = loop->outer;
5185
5186       if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src))
5187         return false;
5188
5189       for (i = 0; i < n_region; i++)
5190         if (region[i] != exit->src
5191             && dominated_by_p (CDI_DOMINATORS, region[i], exit->src))
5192           return false;
5193     }
5194
5195   if (!region_copy)
5196     {
5197       region_copy = xmalloc (sizeof (basic_block) * n_region);
5198       free_region_copy = true;
5199     }
5200
5201   gcc_assert (!any_marked_for_rewrite_p ());
5202
5203   /* Record blocks outside the region that are duplicated by something
5204      inside.  */
5205   doms = xmalloc (sizeof (basic_block) * n_basic_blocks);
5206   n_doms = get_dominated_by_region (CDI_DOMINATORS, region, n_region, doms);
5207
5208   copy_bbs (region, n_region, region_copy, &exit, 1, &exit_copy, loop);
5209   definitions = marked_ssa_names ();
5210
5211   if (copying_header)
5212     {
5213       loop->header = exit->dest;
5214       loop->latch = exit->src;
5215     }
5216
5217   /* Redirect the entry and add the phi node arguments.  */
5218   redirected = redirect_edge_and_branch (entry, entry->dest->rbi->copy);
5219   gcc_assert (redirected != NULL);
5220   flush_pending_stmts (entry);
5221
5222   /* Concerning updating of dominators:  We must recount dominators
5223      for entry block and its copy.  Anything that is outside of the region, but
5224      was dominated by something inside needs recounting as well.  */
5225   set_immediate_dominator (CDI_DOMINATORS, entry->dest, entry->src);
5226   doms[n_doms++] = entry->dest->rbi->original;
5227   iterate_fix_dominators (CDI_DOMINATORS, doms, n_doms);
5228   free (doms);
5229
5230   /* Add the other phi node arguments.  */
5231   add_phi_args_after_copy (region_copy, n_region);
5232
5233   /* Add phi nodes for definitions at exit.  TODO -- once we have immediate
5234      uses, it should be possible to emit phi nodes just for definitions that
5235      are used outside region.  */
5236   EXECUTE_IF_SET_IN_BITMAP (definitions, 0, ver, bi)
5237     {
5238       tree name = ssa_name (ver);
5239
5240       phi = create_phi_node (name, exit->dest);
5241       add_phi_arg (phi, name, exit);
5242       add_phi_arg (phi, name, exit_copy);
5243
5244       SSA_NAME_DEF_STMT (name) = phi;
5245     }
5246
5247   /* And create new definitions inside region and its copy.  TODO -- once we
5248      have immediate uses, it might be better to leave definitions in region
5249      unchanged, create new ssa names for phi nodes on exit, and rewrite
5250      the uses, to avoid changing the copied region.  */
5251   allocate_ssa_names (definitions, &ssa_name_map);
5252   rewrite_to_new_ssa_names (region, n_region, ssa_name_map);
5253   allocate_ssa_names (definitions, &ssa_name_map);
5254   rewrite_to_new_ssa_names (region_copy, n_region, ssa_name_map);
5255   htab_delete (ssa_name_map);
5256
5257   if (free_region_copy)
5258     free (region_copy);
5259
5260   unmark_all_for_rewrite ();
5261   BITMAP_FREE (definitions);
5262
5263   return true;
5264 }
5265
5266 /* Dump FUNCTION_DECL FN to file FILE using FLAGS (see TDF_* in tree.h)  */
5267
5268 void
5269 dump_function_to_file (tree fn, FILE *file, int flags)
5270 {
5271   tree arg, vars, var;
5272   bool ignore_topmost_bind = false, any_var = false;
5273   basic_block bb;
5274   tree chain;
5275
5276   fprintf (file, "%s (", lang_hooks.decl_printable_name (fn, 2));
5277
5278   arg = DECL_ARGUMENTS (fn);
5279   while (arg)
5280     {
5281       print_generic_expr (file, arg, dump_flags);
5282       if (TREE_CHAIN (arg))
5283         fprintf (file, ", ");
5284       arg = TREE_CHAIN (arg);
5285     }
5286   fprintf (file, ")\n");
5287
5288   if (flags & TDF_RAW)
5289     {
5290       dump_node (fn, TDF_SLIM | flags, file);
5291       return;
5292     }
5293
5294   /* When GIMPLE is lowered, the variables are no longer available in
5295      BIND_EXPRs, so display them separately.  */
5296   if (cfun && cfun->unexpanded_var_list)
5297     {
5298       ignore_topmost_bind = true;
5299
5300       fprintf (file, "{\n");
5301       for (vars = cfun->unexpanded_var_list; vars; vars = TREE_CHAIN (vars))
5302         {
5303           var = TREE_VALUE (vars);
5304
5305           print_generic_decl (file, var, flags);
5306           fprintf (file, "\n");
5307
5308           any_var = true;
5309         }
5310     }
5311
5312   if (basic_block_info)
5313     {
5314       /* Make a CFG based dump.  */
5315       check_bb_profile (ENTRY_BLOCK_PTR, file);
5316       if (!ignore_topmost_bind)
5317         fprintf (file, "{\n");
5318
5319       if (any_var && n_basic_blocks)
5320         fprintf (file, "\n");
5321
5322       FOR_EACH_BB (bb)
5323         dump_generic_bb (file, bb, 2, flags);
5324         
5325       fprintf (file, "}\n");
5326       check_bb_profile (EXIT_BLOCK_PTR, file);
5327     }
5328   else
5329     {
5330       int indent;
5331
5332       /* Make a tree based dump.  */
5333       chain = DECL_SAVED_TREE (fn);
5334
5335       if (TREE_CODE (chain) == BIND_EXPR)
5336         {
5337           if (ignore_topmost_bind)
5338             {
5339               chain = BIND_EXPR_BODY (chain);
5340               indent = 2;
5341             }
5342           else
5343             indent = 0;
5344         }
5345       else
5346         {
5347           if (!ignore_topmost_bind)
5348             fprintf (file, "{\n");
5349           indent = 2;
5350         }
5351
5352       if (any_var)
5353         fprintf (file, "\n");
5354
5355       print_generic_stmt_indented (file, chain, flags, indent);
5356       if (ignore_topmost_bind)
5357         fprintf (file, "}\n");
5358     }
5359
5360   fprintf (file, "\n\n");
5361 }
5362
5363
5364 /* Pretty print of the loops intermediate representation.  */
5365 static void print_loop (FILE *, struct loop *, int);
5366 static void print_pred_bbs (FILE *, basic_block bb);
5367 static void print_succ_bbs (FILE *, basic_block bb);
5368
5369
5370 /* Print the predecessors indexes of edge E on FILE.  */
5371
5372 static void
5373 print_pred_bbs (FILE *file, basic_block bb)
5374 {
5375   edge e;
5376   edge_iterator ei;
5377
5378   FOR_EACH_EDGE (e, ei, bb->preds)
5379     fprintf (file, "bb_%d", e->src->index);
5380 }
5381
5382
5383 /* Print the successors indexes of edge E on FILE.  */
5384
5385 static void
5386 print_succ_bbs (FILE *file, basic_block bb)
5387 {
5388   edge e;
5389   edge_iterator ei;
5390
5391   FOR_EACH_EDGE (e, ei, bb->succs)
5392     fprintf (file, "bb_%d", e->src->index);
5393 }
5394
5395
5396 /* Pretty print LOOP on FILE, indented INDENT spaces.  */
5397
5398 static void
5399 print_loop (FILE *file, struct loop *loop, int indent)
5400 {
5401   char *s_indent;
5402   basic_block bb;
5403   
5404   if (loop == NULL)
5405     return;
5406
5407   s_indent = (char *) alloca ((size_t) indent + 1);
5408   memset ((void *) s_indent, ' ', (size_t) indent);
5409   s_indent[indent] = '\0';
5410
5411   /* Print the loop's header.  */
5412   fprintf (file, "%sloop_%d\n", s_indent, loop->num);
5413   
5414   /* Print the loop's body.  */
5415   fprintf (file, "%s{\n", s_indent);
5416   FOR_EACH_BB (bb)
5417     if (bb->loop_father == loop)
5418       {
5419         /* Print the basic_block's header.  */
5420         fprintf (file, "%s  bb_%d (preds = {", s_indent, bb->index);
5421         print_pred_bbs (file, bb);
5422         fprintf (file, "}, succs = {");
5423         print_succ_bbs (file, bb);
5424         fprintf (file, "})\n");
5425         
5426         /* Print the basic_block's body.  */
5427         fprintf (file, "%s  {\n", s_indent);
5428         tree_dump_bb (bb, file, indent + 4);
5429         fprintf (file, "%s  }\n", s_indent);
5430       }
5431   
5432   print_loop (file, loop->inner, indent + 2);
5433   fprintf (file, "%s}\n", s_indent);
5434   print_loop (file, loop->next, indent);
5435 }
5436
5437
5438 /* Follow a CFG edge from the entry point of the program, and on entry
5439    of a loop, pretty print the loop structure on FILE.  */
5440
5441 void 
5442 print_loop_ir (FILE *file)
5443 {
5444   basic_block bb;
5445   
5446   bb = BASIC_BLOCK (0);
5447   if (bb && bb->loop_father)
5448     print_loop (file, bb->loop_father, 0);
5449 }
5450
5451
5452 /* Debugging loops structure at tree level.  */
5453
5454 void 
5455 debug_loop_ir (void)
5456 {
5457   print_loop_ir (stderr);
5458 }
5459
5460
5461 /* Return true if BB ends with a call, possibly followed by some
5462    instructions that must stay with the call.  Return false,
5463    otherwise.  */
5464
5465 static bool
5466 tree_block_ends_with_call_p (basic_block bb)
5467 {
5468   block_stmt_iterator bsi = bsi_last (bb);
5469   return get_call_expr_in (bsi_stmt (bsi)) != NULL;
5470 }
5471
5472
5473 /* Return true if BB ends with a conditional branch.  Return false,
5474    otherwise.  */
5475
5476 static bool
5477 tree_block_ends_with_condjump_p (basic_block bb)
5478 {
5479   tree stmt = tsi_stmt (bsi_last (bb).tsi);
5480   return (TREE_CODE (stmt) == COND_EXPR);
5481 }
5482
5483
5484 /* Return true if we need to add fake edge to exit at statement T.
5485    Helper function for tree_flow_call_edges_add.  */
5486
5487 static bool
5488 need_fake_edge_p (tree t)
5489 {
5490   tree call;
5491
5492   /* NORETURN and LONGJMP calls already have an edge to exit.
5493      CONST and PURE calls do not need one.
5494      We don't currently check for CONST and PURE here, although
5495      it would be a good idea, because those attributes are
5496      figured out from the RTL in mark_constant_function, and
5497      the counter incrementation code from -fprofile-arcs
5498      leads to different results from -fbranch-probabilities.  */
5499   call = get_call_expr_in (t);
5500   if (call
5501       && !(call_expr_flags (call) & ECF_NORETURN))
5502     return true;
5503
5504   if (TREE_CODE (t) == ASM_EXPR
5505        && (ASM_VOLATILE_P (t) || ASM_INPUT_P (t)))
5506     return true;
5507
5508   return false;
5509 }
5510
5511
5512 /* Add fake edges to the function exit for any non constant and non
5513    noreturn calls, volatile inline assembly in the bitmap of blocks
5514    specified by BLOCKS or to the whole CFG if BLOCKS is zero.  Return
5515    the number of blocks that were split.
5516
5517    The goal is to expose cases in which entering a basic block does
5518    not imply that all subsequent instructions must be executed.  */
5519
5520 static int
5521 tree_flow_call_edges_add (sbitmap blocks)
5522 {
5523   int i;
5524   int blocks_split = 0;
5525   int last_bb = last_basic_block;
5526   bool check_last_block = false;
5527
5528   if (n_basic_blocks == 0)
5529     return 0;
5530
5531   if (! blocks)
5532     check_last_block = true;
5533   else
5534     check_last_block = TEST_BIT (blocks, EXIT_BLOCK_PTR->prev_bb->index);
5535
5536   /* In the last basic block, before epilogue generation, there will be
5537      a fallthru edge to EXIT.  Special care is required if the last insn
5538      of the last basic block is a call because make_edge folds duplicate
5539      edges, which would result in the fallthru edge also being marked
5540      fake, which would result in the fallthru edge being removed by
5541      remove_fake_edges, which would result in an invalid CFG.
5542
5543      Moreover, we can't elide the outgoing fake edge, since the block
5544      profiler needs to take this into account in order to solve the minimal
5545      spanning tree in the case that the call doesn't return.
5546
5547      Handle this by adding a dummy instruction in a new last basic block.  */
5548   if (check_last_block)
5549     {
5550       basic_block bb = EXIT_BLOCK_PTR->prev_bb;
5551       block_stmt_iterator bsi = bsi_last (bb);
5552       tree t = NULL_TREE;
5553       if (!bsi_end_p (bsi))
5554         t = bsi_stmt (bsi);
5555
5556       if (need_fake_edge_p (t))
5557         {
5558           edge e;
5559
5560           e = find_edge (bb, EXIT_BLOCK_PTR);
5561           if (e)
5562             {
5563               bsi_insert_on_edge (e, build_empty_stmt ());
5564               bsi_commit_edge_inserts ();
5565             }
5566         }
5567     }
5568
5569   /* Now add fake edges to the function exit for any non constant
5570      calls since there is no way that we can determine if they will
5571      return or not...  */
5572   for (i = 0; i < last_bb; i++)
5573     {
5574       basic_block bb = BASIC_BLOCK (i);
5575       block_stmt_iterator bsi;
5576       tree stmt, last_stmt;
5577
5578       if (!bb)
5579         continue;
5580
5581       if (blocks && !TEST_BIT (blocks, i))
5582         continue;
5583
5584       bsi = bsi_last (bb);
5585       if (!bsi_end_p (bsi))
5586         {
5587           last_stmt = bsi_stmt (bsi);
5588           do
5589             {
5590               stmt = bsi_stmt (bsi);
5591               if (need_fake_edge_p (stmt))
5592                 {
5593                   edge e;
5594                   /* The handling above of the final block before the
5595                      epilogue should be enough to verify that there is
5596                      no edge to the exit block in CFG already.
5597                      Calling make_edge in such case would cause us to
5598                      mark that edge as fake and remove it later.  */
5599 #ifdef ENABLE_CHECKING
5600                   if (stmt == last_stmt)
5601                     {
5602                       e = find_edge (bb, EXIT_BLOCK_PTR);
5603                       gcc_assert (e == NULL);
5604                     }
5605 #endif
5606
5607                   /* Note that the following may create a new basic block
5608                      and renumber the existing basic blocks.  */
5609                   if (stmt != last_stmt)
5610                     {
5611                       e = split_block (bb, stmt);
5612                       if (e)
5613                         blocks_split++;
5614                     }
5615                   make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
5616                 }
5617               bsi_prev (&bsi);
5618             }
5619           while (!bsi_end_p (bsi));
5620         }
5621     }
5622
5623   if (blocks_split)
5624     verify_flow_info ();
5625
5626   return blocks_split;
5627 }
5628
5629 bool
5630 tree_purge_dead_eh_edges (basic_block bb)
5631 {
5632   bool changed = false;
5633   edge e;
5634   edge_iterator ei;
5635   tree stmt = last_stmt (bb);
5636
5637   if (stmt && tree_can_throw_internal (stmt))
5638     return false;
5639
5640   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
5641     {
5642       if (e->flags & EDGE_EH)
5643         {
5644           remove_edge (e);
5645           changed = true;
5646         }
5647       else
5648         ei_next (&ei);
5649     }
5650
5651   /* Removal of dead EH edges might change dominators of not
5652      just immediate successors.  E.g. when bb1 is changed so that
5653      it no longer can throw and bb1->bb3 and bb1->bb4 are dead
5654      eh edges purged by this function in:
5655            0
5656           / \
5657          v   v
5658          1-->2
5659         / \  |
5660        v   v |
5661        3-->4 |
5662         \    v
5663          --->5
5664              |
5665              -
5666      idom(bb5) must be recomputed.  For now just free the dominance
5667      info.  */
5668   if (changed)
5669     free_dominance_info (CDI_DOMINATORS);
5670
5671   return changed;
5672 }
5673
5674 bool
5675 tree_purge_all_dead_eh_edges (bitmap blocks)
5676 {
5677   bool changed = false;
5678   unsigned i;
5679   bitmap_iterator bi;
5680
5681   EXECUTE_IF_SET_IN_BITMAP (blocks, 0, i, bi)
5682     {
5683       changed |= tree_purge_dead_eh_edges (BASIC_BLOCK (i));
5684     }
5685
5686   return changed;
5687 }
5688
5689 /* This function is called whenever a new edge is created or
5690    redirected.  */
5691
5692 static void
5693 tree_execute_on_growing_pred (edge e)
5694 {
5695   basic_block bb = e->dest;
5696
5697   if (phi_nodes (bb))
5698     reserve_phi_args_for_new_edge (bb);
5699 }
5700
5701 /* This function is called immediately before edge E is removed from
5702    the edge vector E->dest->preds.  */
5703
5704 static void
5705 tree_execute_on_shrinking_pred (edge e)
5706 {
5707   if (phi_nodes (e->dest))
5708     remove_phi_args (e);
5709 }
5710
5711 /*---------------------------------------------------------------------------
5712   Helper functions for Loop versioning
5713   ---------------------------------------------------------------------------*/
5714
5715 /* Adjust phi nodes for 'first' basic block.  'second' basic block is a copy
5716    of 'first'. Both of them are dominated by 'new_head' basic block. When
5717    'new_head' was created by 'second's incoming edge it received phi arguments
5718    on the edge by split_edge(). Later, additional edge 'e' was created to
5719    connect 'new_head' and 'first'. Now this routine adds phi args on this 
5720    additional edge 'e' that new_head to second edge received as part of edge 
5721    splitting.
5722 */
5723
5724 static void
5725 tree_lv_adjust_loop_header_phi (basic_block first, basic_block second,
5726                                 basic_block new_head, edge e)
5727 {
5728   tree phi1, phi2;
5729
5730   /* Browse all 'second' basic block phi nodes and add phi args to
5731      edge 'e' for 'first' head. PHI args are always in correct order.  */
5732
5733   for (phi2 = phi_nodes (second), phi1 = phi_nodes (first); 
5734        phi2 && phi1; 
5735        phi2 = PHI_CHAIN (phi2),  phi1 = PHI_CHAIN (phi1))
5736     {
5737       edge e2 = find_edge (new_head, second);
5738
5739       if (e2)
5740         {
5741           tree def = PHI_ARG_DEF (phi2, e2->dest_idx);
5742           add_phi_arg (phi1, def, e);
5743         }
5744     }
5745 }
5746
5747 /* Adds a if else statement to COND_BB with condition COND_EXPR.  
5748    SECOND_HEAD is the destination of the THEN and FIRST_HEAD is 
5749    the destination of the ELSE part.  */
5750 static void
5751 tree_lv_add_condition_to_bb (basic_block first_head, basic_block second_head,
5752                             basic_block cond_bb, void *cond_e)
5753 {
5754   block_stmt_iterator bsi;
5755   tree goto1 = NULL_TREE;
5756   tree goto2 = NULL_TREE;
5757   tree new_cond_expr = NULL_TREE;
5758   tree cond_expr = (tree) cond_e;
5759   edge e0;
5760
5761   /* Build new conditional expr */
5762   goto1 = build1 (GOTO_EXPR, void_type_node, tree_block_label (first_head));
5763   goto2 = build1 (GOTO_EXPR, void_type_node, tree_block_label (second_head));
5764   new_cond_expr = build3 (COND_EXPR, void_type_node, cond_expr, goto1, goto2);
5765
5766   /* Add new cond in cond_bb.  */ 
5767   bsi = bsi_start (cond_bb); 
5768   bsi_insert_after (&bsi, new_cond_expr, BSI_NEW_STMT);
5769   /* Adjust edges appropriately to connect new head with first head
5770      as well as second head.  */
5771   e0 = single_succ_edge (cond_bb);
5772   e0->flags &= ~EDGE_FALLTHRU;
5773   e0->flags |= EDGE_FALSE_VALUE;
5774 }
5775
5776 struct cfg_hooks tree_cfg_hooks = {
5777   "tree",
5778   tree_verify_flow_info,
5779   tree_dump_bb,                 /* dump_bb  */
5780   create_bb,                    /* create_basic_block  */
5781   tree_redirect_edge_and_branch,/* redirect_edge_and_branch  */
5782   tree_redirect_edge_and_branch_force,/* redirect_edge_and_branch_force  */
5783   remove_bb,                    /* delete_basic_block  */
5784   tree_split_block,             /* split_block  */
5785   tree_move_block_after,        /* move_block_after  */
5786   tree_can_merge_blocks_p,      /* can_merge_blocks_p  */
5787   tree_merge_blocks,            /* merge_blocks  */
5788   tree_predict_edge,            /* predict_edge  */
5789   tree_predicted_by_p,          /* predicted_by_p  */
5790   tree_can_duplicate_bb_p,      /* can_duplicate_block_p  */
5791   tree_duplicate_bb,            /* duplicate_block  */
5792   tree_split_edge,              /* split_edge  */
5793   tree_make_forwarder_block,    /* make_forward_block  */
5794   NULL,                         /* tidy_fallthru_edge  */
5795   tree_block_ends_with_call_p,  /* block_ends_with_call_p */
5796   tree_block_ends_with_condjump_p, /* block_ends_with_condjump_p */
5797   tree_flow_call_edges_add,     /* flow_call_edges_add */
5798   tree_execute_on_growing_pred, /* execute_on_growing_pred */
5799   tree_execute_on_shrinking_pred, /* execute_on_shrinking_pred */
5800   tree_duplicate_loop_to_header_edge, /* duplicate loop for trees */
5801   tree_lv_add_condition_to_bb, /* lv_add_condition_to_bb */
5802   tree_lv_adjust_loop_header_phi, /* lv_adjust_loop_header_phi*/
5803   extract_true_false_edges_from_block, /* extract_cond_bb_edges */
5804   flush_pending_stmts           /* flush_pending_stmts */  
5805 };
5806
5807
5808 /* Split all critical edges.  */
5809
5810 static void
5811 split_critical_edges (void)
5812 {
5813   basic_block bb;
5814   edge e;
5815   edge_iterator ei;
5816
5817   /* split_edge can redirect edges out of SWITCH_EXPRs, which can get
5818      expensive.  So we want to enable recording of edge to CASE_LABEL_EXPR
5819      mappings around the calls to split_edge.  */
5820   start_recording_case_labels ();
5821   FOR_ALL_BB (bb)
5822     {
5823       FOR_EACH_EDGE (e, ei, bb->succs)
5824         if (EDGE_CRITICAL_P (e) && !(e->flags & EDGE_ABNORMAL))
5825           {
5826             split_edge (e);
5827           }
5828     }
5829   end_recording_case_labels ();
5830 }
5831
5832 struct tree_opt_pass pass_split_crit_edges = 
5833 {
5834   "crited",                          /* name */
5835   NULL,                          /* gate */
5836   split_critical_edges,          /* execute */
5837   NULL,                          /* sub */
5838   NULL,                          /* next */
5839   0,                             /* static_pass_number */
5840   TV_TREE_SPLIT_EDGES,           /* tv_id */
5841   PROP_cfg,                      /* properties required */
5842   PROP_no_crit_edges,            /* properties_provided */
5843   0,                             /* properties_destroyed */
5844   0,                             /* todo_flags_start */
5845   TODO_dump_func,                /* todo_flags_finish */
5846   0                              /* letter */
5847 };
5848
5849 \f
5850 /* Return EXP if it is a valid GIMPLE rvalue, else gimplify it into
5851    a temporary, make sure and register it to be renamed if necessary,
5852    and finally return the temporary.  Put the statements to compute
5853    EXP before the current statement in BSI.  */
5854
5855 tree
5856 gimplify_val (block_stmt_iterator *bsi, tree type, tree exp)
5857 {
5858   tree t, new_stmt, orig_stmt;
5859
5860   if (is_gimple_val (exp))
5861     return exp;
5862
5863   t = make_rename_temp (type, NULL);
5864   new_stmt = build (MODIFY_EXPR, type, t, exp);
5865
5866   orig_stmt = bsi_stmt (*bsi);
5867   SET_EXPR_LOCUS (new_stmt, EXPR_LOCUS (orig_stmt));
5868   TREE_BLOCK (new_stmt) = TREE_BLOCK (orig_stmt);
5869
5870   bsi_insert_before (bsi, new_stmt, BSI_SAME_STMT);
5871
5872   return t;
5873 }
5874
5875 /* Build a ternary operation and gimplify it.  Emit code before BSI.
5876    Return the gimple_val holding the result.  */
5877
5878 tree
5879 gimplify_build3 (block_stmt_iterator *bsi, enum tree_code code,
5880                  tree type, tree a, tree b, tree c)
5881 {
5882   tree ret;
5883
5884   ret = fold (build3 (code, type, a, b, c));
5885   STRIP_NOPS (ret);
5886
5887   return gimplify_val (bsi, type, ret);
5888 }
5889
5890 /* Build a binary operation and gimplify it.  Emit code before BSI.
5891    Return the gimple_val holding the result.  */
5892
5893 tree
5894 gimplify_build2 (block_stmt_iterator *bsi, enum tree_code code,
5895                  tree type, tree a, tree b)
5896 {
5897   tree ret;
5898
5899   ret = fold (build2 (code, type, a, b));
5900   STRIP_NOPS (ret);
5901
5902   return gimplify_val (bsi, type, ret);
5903 }
5904
5905 /* Build a unary operation and gimplify it.  Emit code before BSI.
5906    Return the gimple_val holding the result.  */
5907
5908 tree
5909 gimplify_build1 (block_stmt_iterator *bsi, enum tree_code code, tree type,
5910                  tree a)
5911 {
5912   tree ret;
5913
5914   ret = fold (build1 (code, type, a));
5915   STRIP_NOPS (ret);
5916
5917   return gimplify_val (bsi, type, ret);
5918 }
5919
5920
5921 \f
5922 /* Emit return warnings.  */
5923
5924 static void
5925 execute_warn_function_return (void)
5926 {
5927 #ifdef USE_MAPPED_LOCATION
5928   source_location location;
5929 #else
5930   location_t *locus;
5931 #endif
5932   tree last;
5933   edge e;
5934   edge_iterator ei;
5935
5936   if (warn_missing_noreturn
5937       && !TREE_THIS_VOLATILE (cfun->decl)
5938       && EDGE_COUNT (EXIT_BLOCK_PTR->preds) == 0
5939       && !lang_hooks.function.missing_noreturn_ok_p (cfun->decl))
5940     warning ("%Jfunction might be possible candidate for "
5941              "attribute %<noreturn%>",
5942              cfun->decl);
5943
5944   /* If we have a path to EXIT, then we do return.  */
5945   if (TREE_THIS_VOLATILE (cfun->decl)
5946       && EDGE_COUNT (EXIT_BLOCK_PTR->preds) > 0)
5947     {
5948 #ifdef USE_MAPPED_LOCATION
5949       location = UNKNOWN_LOCATION;
5950 #else
5951       locus = NULL;
5952 #endif
5953       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
5954         {
5955           last = last_stmt (e->src);
5956           if (TREE_CODE (last) == RETURN_EXPR
5957 #ifdef USE_MAPPED_LOCATION
5958               && (location = EXPR_LOCATION (last)) != UNKNOWN_LOCATION)
5959 #else
5960               && (locus = EXPR_LOCUS (last)) != NULL)
5961 #endif
5962             break;
5963         }
5964 #ifdef USE_MAPPED_LOCATION
5965       if (location == UNKNOWN_LOCATION)
5966         location = cfun->function_end_locus;
5967       warning ("%H%<noreturn%> function does return", &location);
5968 #else
5969       if (!locus)
5970         locus = &cfun->function_end_locus;
5971       warning ("%H%<noreturn%> function does return", locus);
5972 #endif
5973     }
5974
5975   /* If we see "return;" in some basic block, then we do reach the end
5976      without returning a value.  */
5977   else if (warn_return_type
5978            && !TREE_NO_WARNING (cfun->decl)
5979            && EDGE_COUNT (EXIT_BLOCK_PTR->preds) > 0
5980            && !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (cfun->decl))))
5981     {
5982       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
5983         {
5984           tree last = last_stmt (e->src);
5985           if (TREE_CODE (last) == RETURN_EXPR
5986               && TREE_OPERAND (last, 0) == NULL)
5987             {
5988 #ifdef USE_MAPPED_LOCATION
5989               location = EXPR_LOCATION (last);
5990               if (location == UNKNOWN_LOCATION)
5991                   location = cfun->function_end_locus;
5992               warning ("%Hcontrol reaches end of non-void function", &location);
5993 #else
5994               locus = EXPR_LOCUS (last);
5995               if (!locus)
5996                 locus = &cfun->function_end_locus;
5997               warning ("%Hcontrol reaches end of non-void function", locus);
5998 #endif
5999               TREE_NO_WARNING (cfun->decl) = 1;
6000               break;
6001             }
6002         }
6003     }
6004 }
6005
6006
6007 /* Given a basic block B which ends with a conditional and has
6008    precisely two successors, determine which of the edges is taken if
6009    the conditional is true and which is taken if the conditional is
6010    false.  Set TRUE_EDGE and FALSE_EDGE appropriately.  */
6011
6012 void
6013 extract_true_false_edges_from_block (basic_block b,
6014                                      edge *true_edge,
6015                                      edge *false_edge)
6016 {
6017   edge e = EDGE_SUCC (b, 0);
6018
6019   if (e->flags & EDGE_TRUE_VALUE)
6020     {
6021       *true_edge = e;
6022       *false_edge = EDGE_SUCC (b, 1);
6023     }
6024   else
6025     {
6026       *false_edge = e;
6027       *true_edge = EDGE_SUCC (b, 1);
6028     }
6029 }
6030
6031 struct tree_opt_pass pass_warn_function_return =
6032 {
6033   NULL,                                 /* name */
6034   NULL,                                 /* gate */
6035   execute_warn_function_return,         /* execute */
6036   NULL,                                 /* sub */
6037   NULL,                                 /* next */
6038   0,                                    /* static_pass_number */
6039   0,                                    /* tv_id */
6040   PROP_cfg,                             /* properties_required */
6041   0,                                    /* properties_provided */
6042   0,                                    /* properties_destroyed */
6043   0,                                    /* todo_flags_start */
6044   0,                                    /* todo_flags_finish */
6045   0                                     /* letter */
6046 };
6047
6048 #include "gt-tree-cfg.h"