OSDN Git Service

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