OSDN Git Service

* config/i386/sse.md (xop_pmacsww, xop_pmacssww, xop_pmacsdd,
[pf3gnuchains/gcc-fork.git] / gcc / tree-eh.c
1 /* Exception handling semantics and decomposition for trees.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, 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 COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "flags.h"
29 #include "function.h"
30 #include "except.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
33 #include "tree-inline.h"
34 #include "tree-iterator.h"
35 #include "tree-pass.h"
36 #include "timevar.h"
37 #include "langhooks.h"
38 #include "ggc.h"
39 #include "toplev.h"
40 #include "gimple.h"
41 #include "target.h"
42
43 /* In some instances a tree and a gimple need to be stored in a same table,
44    i.e. in hash tables. This is a structure to do this. */
45 typedef union {tree *tp; tree t; gimple g;} treemple;
46
47 /* Nonzero if we are using EH to handle cleanups.  */
48 static int using_eh_for_cleanups_p = 0;
49
50 void
51 using_eh_for_cleanups (void)
52 {
53   using_eh_for_cleanups_p = 1;
54 }
55
56 /* Misc functions used in this file.  */
57
58 /* Compare and hash for any structure which begins with a canonical
59    pointer.  Assumes all pointers are interchangeable, which is sort
60    of already assumed by gcc elsewhere IIRC.  */
61
62 static int
63 struct_ptr_eq (const void *a, const void *b)
64 {
65   const void * const * x = (const void * const *) a;
66   const void * const * y = (const void * const *) b;
67   return *x == *y;
68 }
69
70 static hashval_t
71 struct_ptr_hash (const void *a)
72 {
73   const void * const * x = (const void * const *) a;
74   return (size_t)*x >> 4;
75 }
76
77
78 /* Remember and lookup EH landing pad data for arbitrary statements.
79    Really this means any statement that could_throw_p.  We could
80    stuff this information into the stmt_ann data structure, but:
81
82    (1) We absolutely rely on this information being kept until
83    we get to rtl.  Once we're done with lowering here, if we lose
84    the information there's no way to recover it!
85
86    (2) There are many more statements that *cannot* throw as
87    compared to those that can.  We should be saving some amount
88    of space by only allocating memory for those that can throw.  */
89
90 /* Add statement T in function IFUN to landing pad NUM.  */
91
92 void
93 add_stmt_to_eh_lp_fn (struct function *ifun, gimple t, int num)
94 {
95   struct throw_stmt_node *n;
96   void **slot;
97
98   gcc_assert (num != 0);
99
100   n = GGC_NEW (struct throw_stmt_node);
101   n->stmt = t;
102   n->lp_nr = num;
103
104   if (!get_eh_throw_stmt_table (ifun))
105     set_eh_throw_stmt_table (ifun, htab_create_ggc (31, struct_ptr_hash,
106                                                     struct_ptr_eq,
107                                                     ggc_free));
108
109   slot = htab_find_slot (get_eh_throw_stmt_table (ifun), n, INSERT);
110   gcc_assert (!*slot);
111   *slot = n;
112 }
113
114 /* Add statement T in the current function (cfun) to EH landing pad NUM.  */
115
116 void
117 add_stmt_to_eh_lp (gimple t, int num)
118 {
119   add_stmt_to_eh_lp_fn (cfun, t, num);
120 }
121
122 /* Add statement T to the single EH landing pad in REGION.  */
123
124 static void
125 record_stmt_eh_region (eh_region region, gimple t)
126 {
127   if (region == NULL)
128     return;
129   if (region->type == ERT_MUST_NOT_THROW)
130     add_stmt_to_eh_lp_fn (cfun, t, -region->index);
131   else
132     {
133       eh_landing_pad lp = region->landing_pads;
134       if (lp == NULL)
135         lp = gen_eh_landing_pad (region);
136       else
137         gcc_assert (lp->next_lp == NULL);
138       add_stmt_to_eh_lp_fn (cfun, t, lp->index);
139     }
140 }
141
142
143 /* Remove statement T in function IFUN from its EH landing pad.  */
144
145 bool
146 remove_stmt_from_eh_lp_fn (struct function *ifun, gimple t)
147 {
148   struct throw_stmt_node dummy;
149   void **slot;
150
151   if (!get_eh_throw_stmt_table (ifun))
152     return false;
153
154   dummy.stmt = t;
155   slot = htab_find_slot (get_eh_throw_stmt_table (ifun), &dummy,
156                         NO_INSERT);
157   if (slot)
158     {
159       htab_clear_slot (get_eh_throw_stmt_table (ifun), slot);
160       return true;
161     }
162   else
163     return false;
164 }
165
166
167 /* Remove statement T in the current function (cfun) from its
168    EH landing pad.  */
169
170 bool
171 remove_stmt_from_eh_lp (gimple t)
172 {
173   return remove_stmt_from_eh_lp_fn (cfun, t);
174 }
175
176 /* Determine if statement T is inside an EH region in function IFUN.
177    Positive numbers indicate a landing pad index; negative numbers
178    indicate a MUST_NOT_THROW region index; zero indicates that the
179    statement is not recorded in the region table.  */
180
181 int
182 lookup_stmt_eh_lp_fn (struct function *ifun, gimple t)
183 {
184   struct throw_stmt_node *p, n;
185
186   if (ifun->eh->throw_stmt_table == NULL)
187     return 0;
188
189   n.stmt = t;
190   p = (struct throw_stmt_node *) htab_find (ifun->eh->throw_stmt_table, &n);
191   return p ? p->lp_nr : 0;
192 }
193
194 /* Likewise, but always use the current function.  */
195
196 int
197 lookup_stmt_eh_lp (gimple t)
198 {
199   /* We can get called from initialized data when -fnon-call-exceptions
200      is on; prevent crash.  */
201   if (!cfun)
202     return 0;
203   return lookup_stmt_eh_lp_fn (cfun, t);
204 }
205
206 /* Likewise, but reference a tree expression instead.  */
207
208 int
209 lookup_expr_eh_lp (tree t)
210 {
211   if (cfun && cfun->eh->throw_stmt_table && t && EXPR_P (t))
212     {
213       tree_ann_common_t ann = tree_common_ann (t);
214       if (ann)
215         return ann->lp_nr;
216     }
217   return 0;
218 }
219
220
221 /* First pass of EH node decomposition.  Build up a tree of GIMPLE_TRY_FINALLY
222    nodes and LABEL_DECL nodes.  We will use this during the second phase to
223    determine if a goto leaves the body of a TRY_FINALLY_EXPR node.  */
224
225 struct finally_tree_node
226 {
227   /* When storing a GIMPLE_TRY, we have to record a gimple.  However
228      when deciding whether a GOTO to a certain LABEL_DECL (which is a
229      tree) leaves the TRY block, its necessary to record a tree in
230      this field.  Thus a treemple is used. */
231   treemple child;
232   gimple parent;
233 };
234
235 /* Note that this table is *not* marked GTY.  It is short-lived.  */
236 static htab_t finally_tree;
237
238 static void
239 record_in_finally_tree (treemple child, gimple parent)
240 {
241   struct finally_tree_node *n;
242   void **slot;
243
244   n = XNEW (struct finally_tree_node);
245   n->child = child;
246   n->parent = parent;
247
248   slot = htab_find_slot (finally_tree, n, INSERT);
249   gcc_assert (!*slot);
250   *slot = n;
251 }
252
253 static void
254 collect_finally_tree (gimple stmt, gimple region);
255
256 /* Go through the gimple sequence.  Works with collect_finally_tree to
257    record all GIMPLE_LABEL and GIMPLE_TRY statements. */
258
259 static void
260 collect_finally_tree_1 (gimple_seq seq, gimple region)
261 {
262   gimple_stmt_iterator gsi;
263
264   for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
265     collect_finally_tree (gsi_stmt (gsi), region);
266 }
267
268 static void
269 collect_finally_tree (gimple stmt, gimple region)
270 {
271   treemple temp;
272
273   switch (gimple_code (stmt))
274     {
275     case GIMPLE_LABEL:
276       temp.t = gimple_label_label (stmt);
277       record_in_finally_tree (temp, region);
278       break;
279
280     case GIMPLE_TRY:
281       if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
282         {
283           temp.g = stmt;
284           record_in_finally_tree (temp, region);
285           collect_finally_tree_1 (gimple_try_eval (stmt), stmt);
286           collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
287         }
288       else if (gimple_try_kind (stmt) == GIMPLE_TRY_CATCH)
289         {
290           collect_finally_tree_1 (gimple_try_eval (stmt), region);
291           collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
292         }
293       break;
294
295     case GIMPLE_CATCH:
296       collect_finally_tree_1 (gimple_catch_handler (stmt), region);
297       break;
298
299     case GIMPLE_EH_FILTER:
300       collect_finally_tree_1 (gimple_eh_filter_failure (stmt), region);
301       break;
302
303     default:
304       /* A type, a decl, or some kind of statement that we're not
305          interested in.  Don't walk them.  */
306       break;
307     }
308 }
309
310
311 /* Use the finally tree to determine if a jump from START to TARGET
312    would leave the try_finally node that START lives in.  */
313
314 static bool
315 outside_finally_tree (treemple start, gimple target)
316 {
317   struct finally_tree_node n, *p;
318
319   do
320     {
321       n.child = start;
322       p = (struct finally_tree_node *) htab_find (finally_tree, &n);
323       if (!p)
324         return true;
325       start.g = p->parent;
326     }
327   while (start.g != target);
328
329   return false;
330 }
331
332 /* Second pass of EH node decomposition.  Actually transform the GIMPLE_TRY
333    nodes into a set of gotos, magic labels, and eh regions.
334    The eh region creation is straight-forward, but frobbing all the gotos
335    and such into shape isn't.  */
336
337 /* The sequence into which we record all EH stuff.  This will be 
338    placed at the end of the function when we're all done.  */
339 static gimple_seq eh_seq;
340
341 /* Record whether an EH region contains something that can throw,
342    indexed by EH region number.  */
343 static bitmap eh_region_may_contain_throw_map;
344
345 /* The GOTO_QUEUE is is an array of GIMPLE_GOTO and GIMPLE_RETURN
346    statements that are seen to escape this GIMPLE_TRY_FINALLY node.
347    The idea is to record a gimple statement for everything except for
348    the conditionals, which get their labels recorded. Since labels are
349    of type 'tree', we need this node to store both gimple and tree
350    objects.  REPL_STMT is the sequence used to replace the goto/return
351    statement.  CONT_STMT is used to store the statement that allows
352    the return/goto to jump to the original destination. */
353
354 struct goto_queue_node
355 {
356   treemple stmt;
357   gimple_seq repl_stmt;
358   gimple cont_stmt;
359   int index;
360   /* This is used when index >= 0 to indicate that stmt is a label (as
361      opposed to a goto stmt).  */
362   int is_label;
363 };
364
365 /* State of the world while lowering.  */
366
367 struct leh_state
368 {
369   /* What's "current" while constructing the eh region tree.  These
370      correspond to variables of the same name in cfun->eh, which we
371      don't have easy access to.  */
372   eh_region cur_region;
373
374   /* What's "current" for the purposes of __builtin_eh_pointer.  For
375      a CATCH, this is the associated TRY.  For an EH_FILTER, this is
376      the associated ALLOWED_EXCEPTIONS, etc.  */
377   eh_region ehp_region;
378
379   /* Processing of TRY_FINALLY requires a bit more state.  This is
380      split out into a separate structure so that we don't have to
381      copy so much when processing other nodes.  */
382   struct leh_tf_state *tf;
383 };
384
385 struct leh_tf_state
386 {
387   /* Pointer to the GIMPLE_TRY_FINALLY node under discussion.  The
388      try_finally_expr is the original GIMPLE_TRY_FINALLY.  We need to retain
389      this so that outside_finally_tree can reliably reference the tree used
390      in the collect_finally_tree data structures.  */
391   gimple try_finally_expr;
392   gimple top_p;
393
394   /* While lowering a top_p usually it is expanded into multiple statements,
395      thus we need the following field to store them. */
396   gimple_seq top_p_seq;
397
398   /* The state outside this try_finally node.  */
399   struct leh_state *outer;
400
401   /* The exception region created for it.  */
402   eh_region region;
403
404   /* The goto queue.  */
405   struct goto_queue_node *goto_queue;
406   size_t goto_queue_size;
407   size_t goto_queue_active;
408
409   /* Pointer map to help in searching goto_queue when it is large.  */
410   struct pointer_map_t *goto_queue_map;
411
412   /* The set of unique labels seen as entries in the goto queue.  */
413   VEC(tree,heap) *dest_array;
414
415   /* A label to be added at the end of the completed transformed
416      sequence.  It will be set if may_fallthru was true *at one time*,
417      though subsequent transformations may have cleared that flag.  */
418   tree fallthru_label;
419
420   /* True if it is possible to fall out the bottom of the try block.
421      Cleared if the fallthru is converted to a goto.  */
422   bool may_fallthru;
423
424   /* True if any entry in goto_queue is a GIMPLE_RETURN.  */
425   bool may_return;
426
427   /* True if the finally block can receive an exception edge.
428      Cleared if the exception case is handled by code duplication.  */
429   bool may_throw;
430 };
431
432 static gimple_seq lower_eh_must_not_throw (struct leh_state *, gimple);
433
434 /* Search for STMT in the goto queue.  Return the replacement,
435    or null if the statement isn't in the queue.  */
436
437 #define LARGE_GOTO_QUEUE 20
438
439 static void lower_eh_constructs_1 (struct leh_state *state, gimple_seq seq);
440
441 static gimple_seq
442 find_goto_replacement (struct leh_tf_state *tf, treemple stmt)
443 {
444   unsigned int i;
445   void **slot;
446
447   if (tf->goto_queue_active < LARGE_GOTO_QUEUE)
448     {
449       for (i = 0; i < tf->goto_queue_active; i++)
450         if ( tf->goto_queue[i].stmt.g == stmt.g)
451           return tf->goto_queue[i].repl_stmt;
452       return NULL;
453     }
454
455   /* If we have a large number of entries in the goto_queue, create a
456      pointer map and use that for searching.  */
457
458   if (!tf->goto_queue_map)
459     {
460       tf->goto_queue_map = pointer_map_create ();
461       for (i = 0; i < tf->goto_queue_active; i++)
462         {
463           slot = pointer_map_insert (tf->goto_queue_map,
464                                      tf->goto_queue[i].stmt.g);
465           gcc_assert (*slot == NULL);
466           *slot = &tf->goto_queue[i];
467         }
468     }
469
470   slot = pointer_map_contains (tf->goto_queue_map, stmt.g);
471   if (slot != NULL)
472     return (((struct goto_queue_node *) *slot)->repl_stmt);
473
474   return NULL;
475 }
476
477 /* A subroutine of replace_goto_queue_1.  Handles the sub-clauses of a
478    lowered GIMPLE_COND.  If, by chance, the replacement is a simple goto,
479    then we can just splat it in, otherwise we add the new stmts immediately
480    after the GIMPLE_COND and redirect.  */
481
482 static void
483 replace_goto_queue_cond_clause (tree *tp, struct leh_tf_state *tf,
484                                 gimple_stmt_iterator *gsi)
485 {
486   tree label;
487   gimple_seq new_seq;
488   treemple temp;
489   location_t loc = gimple_location (gsi_stmt (*gsi));
490
491   temp.tp = tp;
492   new_seq = find_goto_replacement (tf, temp);
493   if (!new_seq)
494     return;
495
496   if (gimple_seq_singleton_p (new_seq)
497       && gimple_code (gimple_seq_first_stmt (new_seq)) == GIMPLE_GOTO)
498     {
499       *tp = gimple_goto_dest (gimple_seq_first_stmt (new_seq));
500       return;
501     }
502
503   label = create_artificial_label (loc);
504   /* Set the new label for the GIMPLE_COND */
505   *tp = label;
506
507   gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
508   gsi_insert_seq_after (gsi, gimple_seq_copy (new_seq), GSI_CONTINUE_LINKING);
509 }
510
511 /* The real work of replace_goto_queue.  Returns with TSI updated to
512    point to the next statement.  */
513
514 static void replace_goto_queue_stmt_list (gimple_seq, struct leh_tf_state *);
515
516 static void
517 replace_goto_queue_1 (gimple stmt, struct leh_tf_state *tf,
518                       gimple_stmt_iterator *gsi)
519 {
520   gimple_seq seq;
521   treemple temp;
522   temp.g = NULL;
523
524   switch (gimple_code (stmt))
525     {
526     case GIMPLE_GOTO:
527     case GIMPLE_RETURN:
528       temp.g = stmt;
529       seq = find_goto_replacement (tf, temp);
530       if (seq)
531         {
532           gsi_insert_seq_before (gsi, gimple_seq_copy (seq), GSI_SAME_STMT);
533           gsi_remove (gsi, false);
534           return;
535         }
536       break;
537
538     case GIMPLE_COND:
539       replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 2), tf, gsi);
540       replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 3), tf, gsi);
541       break;
542
543     case GIMPLE_TRY:
544       replace_goto_queue_stmt_list (gimple_try_eval (stmt), tf);
545       replace_goto_queue_stmt_list (gimple_try_cleanup (stmt), tf);
546       break;
547     case GIMPLE_CATCH:
548       replace_goto_queue_stmt_list (gimple_catch_handler (stmt), tf);
549       break;
550     case GIMPLE_EH_FILTER:
551       replace_goto_queue_stmt_list (gimple_eh_filter_failure (stmt), tf);
552       break;
553
554     default:
555       /* These won't have gotos in them.  */
556       break;
557     }
558
559   gsi_next (gsi);
560 }
561
562 /* A subroutine of replace_goto_queue.  Handles GIMPLE_SEQ.  */
563
564 static void
565 replace_goto_queue_stmt_list (gimple_seq seq, struct leh_tf_state *tf)
566 {
567   gimple_stmt_iterator gsi = gsi_start (seq);
568
569   while (!gsi_end_p (gsi))
570     replace_goto_queue_1 (gsi_stmt (gsi), tf, &gsi);
571 }
572
573 /* Replace all goto queue members.  */
574
575 static void
576 replace_goto_queue (struct leh_tf_state *tf)
577 {
578   if (tf->goto_queue_active == 0)
579     return;
580   replace_goto_queue_stmt_list (tf->top_p_seq, tf);
581 }
582
583 /* Add a new record to the goto queue contained in TF. NEW_STMT is the
584    data to be added, IS_LABEL indicates whether NEW_STMT is a label or
585    a gimple return. */
586
587 static void
588 record_in_goto_queue (struct leh_tf_state *tf,
589                       treemple new_stmt,
590                       int index,
591                       bool is_label)
592 {
593   size_t active, size;
594   struct goto_queue_node *q;
595
596   gcc_assert (!tf->goto_queue_map);
597
598   active = tf->goto_queue_active;
599   size = tf->goto_queue_size;
600   if (active >= size)
601     {
602       size = (size ? size * 2 : 32);
603       tf->goto_queue_size = size;
604       tf->goto_queue
605          = XRESIZEVEC (struct goto_queue_node, tf->goto_queue, size);
606     }
607
608   q = &tf->goto_queue[active];
609   tf->goto_queue_active = active + 1;
610
611   memset (q, 0, sizeof (*q));
612   q->stmt = new_stmt;
613   q->index = index;
614   q->is_label = is_label;
615 }
616
617 /* Record the LABEL label in the goto queue contained in TF.
618    TF is not null.  */
619
620 static void
621 record_in_goto_queue_label (struct leh_tf_state *tf, treemple stmt, tree label)
622 {
623   int index;
624   treemple temp, new_stmt;
625
626   if (!label)
627     return;
628
629   /* Computed and non-local gotos do not get processed.  Given
630      their nature we can neither tell whether we've escaped the
631      finally block nor redirect them if we knew.  */
632   if (TREE_CODE (label) != LABEL_DECL)
633     return;
634
635   /* No need to record gotos that don't leave the try block.  */
636   temp.t = label;
637   if (!outside_finally_tree (temp, tf->try_finally_expr))
638     return;
639
640   if (! tf->dest_array)
641     {
642       tf->dest_array = VEC_alloc (tree, heap, 10);
643       VEC_quick_push (tree, tf->dest_array, label);
644       index = 0;
645     }
646   else
647     {
648       int n = VEC_length (tree, tf->dest_array);
649       for (index = 0; index < n; ++index)
650         if (VEC_index (tree, tf->dest_array, index) == label)
651           break;
652       if (index == n)
653         VEC_safe_push (tree, heap, tf->dest_array, label);
654     }
655
656   /* In the case of a GOTO we want to record the destination label,
657      since with a GIMPLE_COND we have an easy access to the then/else
658      labels. */
659   new_stmt = stmt;
660   record_in_goto_queue (tf, new_stmt, index, true);
661
662 }
663
664 /* For any GIMPLE_GOTO or GIMPLE_RETURN, decide whether it leaves a try_finally
665    node, and if so record that fact in the goto queue associated with that
666    try_finally node.  */
667
668 static void
669 maybe_record_in_goto_queue (struct leh_state *state, gimple stmt)
670 {
671   struct leh_tf_state *tf = state->tf;
672   treemple new_stmt;
673
674   if (!tf)
675     return;
676
677   switch (gimple_code (stmt))
678     {
679     case GIMPLE_COND:
680       new_stmt.tp = gimple_op_ptr (stmt, 2);
681       record_in_goto_queue_label (tf, new_stmt, gimple_cond_true_label (stmt));
682       new_stmt.tp = gimple_op_ptr (stmt, 3);
683       record_in_goto_queue_label (tf, new_stmt, gimple_cond_false_label (stmt));
684       break;
685     case GIMPLE_GOTO:
686       new_stmt.g = stmt;
687       record_in_goto_queue_label (tf, new_stmt, gimple_goto_dest (stmt));
688       break;
689
690     case GIMPLE_RETURN:
691       tf->may_return = true;
692       new_stmt.g = stmt;
693       record_in_goto_queue (tf, new_stmt, -1, false);
694       break;
695
696     default:
697       gcc_unreachable ();
698     }
699 }
700
701
702 #ifdef ENABLE_CHECKING
703 /* We do not process GIMPLE_SWITCHes for now.  As long as the original source
704    was in fact structured, and we've not yet done jump threading, then none
705    of the labels will leave outer GIMPLE_TRY_FINALLY nodes. Verify this.  */
706
707 static void
708 verify_norecord_switch_expr (struct leh_state *state, gimple switch_expr)
709 {
710   struct leh_tf_state *tf = state->tf;
711   size_t i, n;
712
713   if (!tf)
714     return;
715
716   n = gimple_switch_num_labels (switch_expr);
717
718   for (i = 0; i < n; ++i)
719     {
720       treemple temp;
721       tree lab = CASE_LABEL (gimple_switch_label (switch_expr, i));
722       temp.t = lab;
723       gcc_assert (!outside_finally_tree (temp, tf->try_finally_expr));
724     }
725 }
726 #else
727 #define verify_norecord_switch_expr(state, switch_expr)
728 #endif
729
730 /* Redirect a RETURN_EXPR pointed to by STMT_P to FINLAB.  Place in CONT_P
731    whatever is needed to finish the return.  If MOD is non-null, insert it
732    before the new branch.  RETURN_VALUE_P is a cache containing a temporary
733    variable to be used in manipulating the value returned from the function.  */
734
735 static void
736 do_return_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
737                        tree *return_value_p)
738 {
739   tree ret_expr;
740   gimple x;
741
742   /* In the case of a return, the queue node must be a gimple statement. */
743   gcc_assert (!q->is_label);
744
745   ret_expr = gimple_return_retval (q->stmt.g);
746
747   if (ret_expr)
748     {
749       if (!*return_value_p)
750         *return_value_p = ret_expr;
751       else
752         gcc_assert (*return_value_p == ret_expr);
753       q->cont_stmt = q->stmt.g;
754       /* The nasty part about redirecting the return value is that the
755          return value itself is to be computed before the FINALLY block
756          is executed.  e.g.
757
758                 int x;
759                 int foo (void)
760                 {
761                   x = 0;
762                   try {
763                     return x;
764                   } finally {
765                     x++;
766                   }
767                 }
768
769           should return 0, not 1.  Arrange for this to happen by copying
770           computed the return value into a local temporary.  This also
771           allows us to redirect multiple return statements through the
772           same destination block; whether this is a net win or not really
773           depends, I guess, but it does make generation of the switch in
774           lower_try_finally_switch easier.  */
775
776       if (TREE_CODE (ret_expr) == RESULT_DECL)
777         {
778           if (!*return_value_p)
779             *return_value_p = ret_expr;
780           else
781             gcc_assert (*return_value_p == ret_expr);
782           q->cont_stmt = q->stmt.g;
783         }
784       else
785           gcc_unreachable ();
786     }
787   else
788       /* If we don't return a value, all return statements are the same.  */
789       q->cont_stmt = q->stmt.g;
790
791   if (!q->repl_stmt)
792     q->repl_stmt = gimple_seq_alloc ();
793
794   if (mod)
795     gimple_seq_add_seq (&q->repl_stmt, mod);
796
797   x = gimple_build_goto (finlab);
798   gimple_seq_add_stmt (&q->repl_stmt, x);
799 }
800
801 /* Similar, but easier, for GIMPLE_GOTO.  */
802
803 static void
804 do_goto_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
805                      struct leh_tf_state *tf)
806 {
807   gimple x;
808
809   gcc_assert (q->is_label);
810   if (!q->repl_stmt)
811     q->repl_stmt = gimple_seq_alloc ();
812
813   q->cont_stmt = gimple_build_goto (VEC_index (tree, tf->dest_array, q->index));
814
815   if (mod)
816     gimple_seq_add_seq (&q->repl_stmt, mod);
817
818   x = gimple_build_goto (finlab);
819   gimple_seq_add_stmt (&q->repl_stmt, x);
820 }
821
822 /* Emit a standard landing pad sequence into SEQ for REGION.  */
823
824 static void
825 emit_post_landing_pad (gimple_seq *seq, eh_region region)
826 {
827   eh_landing_pad lp = region->landing_pads;
828   gimple x;
829
830   if (lp == NULL)
831     lp = gen_eh_landing_pad (region);
832
833   lp->post_landing_pad = create_artificial_label (UNKNOWN_LOCATION);
834   EH_LANDING_PAD_NR (lp->post_landing_pad) = lp->index;
835
836   x = gimple_build_label (lp->post_landing_pad);
837   gimple_seq_add_stmt (seq, x);
838 }
839
840 /* Emit a RESX statement into SEQ for REGION.  */
841
842 static void
843 emit_resx (gimple_seq *seq, eh_region region)
844 {
845   gimple x = gimple_build_resx (region->index);
846   gimple_seq_add_stmt (seq, x);
847   if (region->outer)
848     record_stmt_eh_region (region->outer, x);
849 }
850
851 /* Emit an EH_DISPATCH statement into SEQ for REGION.  */
852
853 static void
854 emit_eh_dispatch (gimple_seq *seq, eh_region region)
855 {
856   gimple x = gimple_build_eh_dispatch (region->index);
857   gimple_seq_add_stmt (seq, x);
858 }
859
860 /* Note that the current EH region may contain a throw, or a
861    call to a function which itself may contain a throw.  */
862
863 static void
864 note_eh_region_may_contain_throw (eh_region region)
865 {
866   while (!bitmap_bit_p (eh_region_may_contain_throw_map, region->index))
867     {
868       bitmap_set_bit (eh_region_may_contain_throw_map, region->index);
869       region = region->outer;
870       if (region == NULL)
871         break;
872     }
873 }
874
875 /* Check if REGION has been marked as containing a throw.  If REGION is
876    NULL, this predicate is false.  */
877
878 static inline bool
879 eh_region_may_contain_throw (eh_region r)
880 {
881   return r && bitmap_bit_p (eh_region_may_contain_throw_map, r->index);
882 }
883
884 /* We want to transform
885         try { body; } catch { stuff; }
886    to
887         normal_seqence:
888           body;
889           over:
890         eh_seqence:
891           landing_pad:
892           stuff;
893           goto over;
894
895    TP is a GIMPLE_TRY node.  REGION is the region whose post_landing_pad
896    should be placed before the second operand, or NULL.  OVER is
897    an existing label that should be put at the exit, or NULL.  */
898
899 static gimple_seq
900 frob_into_branch_around (gimple tp, eh_region region, tree over)
901 {
902   gimple x;
903   gimple_seq cleanup, result;
904   location_t loc = gimple_location (tp);
905
906   cleanup = gimple_try_cleanup (tp);
907   result = gimple_try_eval (tp);
908
909   if (region)
910     emit_post_landing_pad (&eh_seq, region);
911
912   if (gimple_seq_may_fallthru (cleanup))
913     {
914       if (!over)
915         over = create_artificial_label (loc);
916       x = gimple_build_goto (over);
917       gimple_seq_add_stmt (&cleanup, x);
918     }
919   gimple_seq_add_seq (&eh_seq, cleanup);
920
921   if (over)
922     {
923       x = gimple_build_label (over);
924       gimple_seq_add_stmt (&result, x);
925     }
926   return result;
927 }
928
929 /* A subroutine of lower_try_finally.  Duplicate the tree rooted at T.
930    Make sure to record all new labels found.  */
931
932 static gimple_seq
933 lower_try_finally_dup_block (gimple_seq seq, struct leh_state *outer_state)
934 {
935   gimple region = NULL;
936   gimple_seq new_seq;
937
938   new_seq = copy_gimple_seq_and_replace_locals (seq);
939
940   if (outer_state->tf)
941     region = outer_state->tf->try_finally_expr;
942   collect_finally_tree_1 (new_seq, region);
943
944   return new_seq;
945 }
946
947 /* A subroutine of lower_try_finally.  Create a fallthru label for
948    the given try_finally state.  The only tricky bit here is that
949    we have to make sure to record the label in our outer context.  */
950
951 static tree
952 lower_try_finally_fallthru_label (struct leh_tf_state *tf)
953 {
954   tree label = tf->fallthru_label;
955   treemple temp;
956
957   if (!label)
958     {
959       label = create_artificial_label (gimple_location (tf->try_finally_expr));
960       tf->fallthru_label = label;
961       if (tf->outer->tf)
962         {
963           temp.t = label;
964           record_in_finally_tree (temp, tf->outer->tf->try_finally_expr);
965         }
966     }
967   return label;
968 }
969
970 /* A subroutine of lower_try_finally.  If lang_protect_cleanup_actions
971    returns non-null, then the language requires that the exception path out
972    of a try_finally be treated specially.  To wit: the code within the
973    finally block may not itself throw an exception.  We have two choices here.
974    First we can duplicate the finally block and wrap it in a must_not_throw
975    region.  Second, we can generate code like
976
977         try {
978           finally_block;
979         } catch {
980           if (fintmp == eh_edge)
981             protect_cleanup_actions;
982         }
983
984    where "fintmp" is the temporary used in the switch statement generation
985    alternative considered below.  For the nonce, we always choose the first
986    option.
987
988    THIS_STATE may be null if this is a try-cleanup, not a try-finally.  */
989
990 static void
991 honor_protect_cleanup_actions (struct leh_state *outer_state,
992                                struct leh_state *this_state,
993                                struct leh_tf_state *tf)
994 {
995   tree protect_cleanup_actions;
996   gimple_stmt_iterator gsi;
997   bool finally_may_fallthru;
998   gimple_seq finally;
999   gimple x;
1000
1001   /* First check for nothing to do.  */
1002   if (lang_protect_cleanup_actions == NULL)
1003     return;
1004   protect_cleanup_actions = lang_protect_cleanup_actions ();
1005   if (protect_cleanup_actions == NULL)
1006     return;
1007
1008   finally = gimple_try_cleanup (tf->top_p);
1009   finally_may_fallthru = gimple_seq_may_fallthru (finally);
1010
1011   /* Duplicate the FINALLY block.  Only need to do this for try-finally,
1012      and not for cleanups.  */
1013   if (this_state)
1014     finally = lower_try_finally_dup_block (finally, outer_state);
1015
1016   /* If this cleanup consists of a TRY_CATCH_EXPR with TRY_CATCH_IS_CLEANUP
1017      set, the handler of the TRY_CATCH_EXPR is another cleanup which ought
1018      to be in an enclosing scope, but needs to be implemented at this level
1019      to avoid a nesting violation (see wrap_temporary_cleanups in
1020      cp/decl.c).  Since it's logically at an outer level, we should call
1021      terminate before we get to it, so strip it away before adding the
1022      MUST_NOT_THROW filter.  */
1023   gsi = gsi_start (finally);
1024   x = gsi_stmt (gsi);
1025   if (gimple_code (x) == GIMPLE_TRY
1026       && gimple_try_kind (x) == GIMPLE_TRY_CATCH
1027       && gimple_try_catch_is_cleanup (x))
1028     {
1029       gsi_insert_seq_before (&gsi, gimple_try_eval (x), GSI_SAME_STMT);
1030       gsi_remove (&gsi, false);
1031     }
1032
1033   /* Wrap the block with protect_cleanup_actions as the action.  */
1034   x = gimple_build_eh_must_not_throw (protect_cleanup_actions);
1035   x = gimple_build_try (finally, gimple_seq_alloc_with_stmt (x),
1036                         GIMPLE_TRY_CATCH);
1037   finally = lower_eh_must_not_throw (outer_state, x);
1038
1039   /* Drop all of this into the exception sequence.  */
1040   emit_post_landing_pad (&eh_seq, tf->region);
1041   gimple_seq_add_seq (&eh_seq, finally);
1042   if (finally_may_fallthru)
1043     emit_resx (&eh_seq, tf->region);
1044
1045   /* Having now been handled, EH isn't to be considered with
1046      the rest of the outgoing edges.  */
1047   tf->may_throw = false;
1048 }
1049
1050 /* A subroutine of lower_try_finally.  We have determined that there is
1051    no fallthru edge out of the finally block.  This means that there is
1052    no outgoing edge corresponding to any incoming edge.  Restructure the
1053    try_finally node for this special case.  */
1054
1055 static void
1056 lower_try_finally_nofallthru (struct leh_state *state,
1057                               struct leh_tf_state *tf)
1058 {
1059   tree lab, return_val;
1060   gimple x;
1061   gimple_seq finally;
1062   struct goto_queue_node *q, *qe;
1063
1064   lab = create_artificial_label (gimple_location (tf->try_finally_expr));
1065
1066   /* We expect that tf->top_p is a GIMPLE_TRY. */
1067   finally = gimple_try_cleanup (tf->top_p);
1068   tf->top_p_seq = gimple_try_eval (tf->top_p);
1069
1070   x = gimple_build_label (lab);
1071   gimple_seq_add_stmt (&tf->top_p_seq, x);
1072
1073   return_val = NULL;
1074   q = tf->goto_queue;
1075   qe = q + tf->goto_queue_active;
1076   for (; q < qe; ++q)
1077     if (q->index < 0)
1078       do_return_redirection (q, lab, NULL, &return_val);
1079     else
1080       do_goto_redirection (q, lab, NULL, tf);
1081
1082   replace_goto_queue (tf);
1083
1084   lower_eh_constructs_1 (state, finally);
1085   gimple_seq_add_seq (&tf->top_p_seq, finally);
1086
1087   if (tf->may_throw)
1088     {
1089       emit_post_landing_pad (&eh_seq, tf->region);
1090
1091       x = gimple_build_goto (lab);
1092       gimple_seq_add_stmt (&eh_seq, x);
1093     }
1094 }
1095
1096 /* A subroutine of lower_try_finally.  We have determined that there is
1097    exactly one destination of the finally block.  Restructure the
1098    try_finally node for this special case.  */
1099
1100 static void
1101 lower_try_finally_onedest (struct leh_state *state, struct leh_tf_state *tf)
1102 {
1103   struct goto_queue_node *q, *qe;
1104   gimple x;
1105   gimple_seq finally;
1106   tree finally_label;
1107   location_t loc = gimple_location (tf->try_finally_expr);
1108
1109   finally = gimple_try_cleanup (tf->top_p);
1110   tf->top_p_seq = gimple_try_eval (tf->top_p);
1111
1112   lower_eh_constructs_1 (state, finally);
1113
1114   if (tf->may_throw)
1115     {
1116       /* Only reachable via the exception edge.  Add the given label to
1117          the head of the FINALLY block.  Append a RESX at the end.  */
1118       emit_post_landing_pad (&eh_seq, tf->region);
1119       gimple_seq_add_seq (&eh_seq, finally);
1120       emit_resx (&eh_seq, tf->region);
1121       return;
1122     }
1123
1124   if (tf->may_fallthru)
1125     {
1126       /* Only reachable via the fallthru edge.  Do nothing but let
1127          the two blocks run together; we'll fall out the bottom.  */
1128       gimple_seq_add_seq (&tf->top_p_seq, finally);
1129       return;
1130     }
1131
1132   finally_label = create_artificial_label (loc);
1133   x = gimple_build_label (finally_label);
1134   gimple_seq_add_stmt (&tf->top_p_seq, x);
1135
1136   gimple_seq_add_seq (&tf->top_p_seq, finally);
1137
1138   q = tf->goto_queue;
1139   qe = q + tf->goto_queue_active;
1140
1141   if (tf->may_return)
1142     {
1143       /* Reachable by return expressions only.  Redirect them.  */
1144       tree return_val = NULL;
1145       for (; q < qe; ++q)
1146         do_return_redirection (q, finally_label, NULL, &return_val);
1147       replace_goto_queue (tf);
1148     }
1149   else
1150     {
1151       /* Reachable by goto expressions only.  Redirect them.  */
1152       for (; q < qe; ++q)
1153         do_goto_redirection (q, finally_label, NULL, tf);
1154       replace_goto_queue (tf);
1155
1156       if (VEC_index (tree, tf->dest_array, 0) == tf->fallthru_label)
1157         {
1158           /* Reachable by goto to fallthru label only.  Redirect it
1159              to the new label (already created, sadly), and do not
1160              emit the final branch out, or the fallthru label.  */
1161           tf->fallthru_label = NULL;
1162           return;
1163         }
1164     }
1165
1166   /* Place the original return/goto to the original destination
1167      immediately after the finally block. */
1168   x = tf->goto_queue[0].cont_stmt;
1169   gimple_seq_add_stmt (&tf->top_p_seq, x);
1170   maybe_record_in_goto_queue (state, x);
1171 }
1172
1173 /* A subroutine of lower_try_finally.  There are multiple edges incoming
1174    and outgoing from the finally block.  Implement this by duplicating the
1175    finally block for every destination.  */
1176
1177 static void
1178 lower_try_finally_copy (struct leh_state *state, struct leh_tf_state *tf)
1179 {
1180   gimple_seq finally;
1181   gimple_seq new_stmt;
1182   gimple_seq seq;
1183   gimple x;
1184   tree tmp;
1185   location_t tf_loc = gimple_location (tf->try_finally_expr);
1186
1187   finally = gimple_try_cleanup (tf->top_p);
1188   tf->top_p_seq = gimple_try_eval (tf->top_p);
1189   new_stmt = NULL;
1190
1191   if (tf->may_fallthru)
1192     {
1193       seq = lower_try_finally_dup_block (finally, state);
1194       lower_eh_constructs_1 (state, seq);
1195       gimple_seq_add_seq (&new_stmt, seq);
1196
1197       tmp = lower_try_finally_fallthru_label (tf);
1198       x = gimple_build_goto (tmp);
1199       gimple_seq_add_stmt (&new_stmt, x);
1200     }
1201
1202   if (tf->may_throw)
1203     {
1204       seq = lower_try_finally_dup_block (finally, state);
1205       lower_eh_constructs_1 (state, seq);
1206
1207       emit_post_landing_pad (&eh_seq, tf->region);
1208       gimple_seq_add_seq (&eh_seq, seq);
1209       emit_resx (&eh_seq, tf->region);
1210     }
1211
1212   if (tf->goto_queue)
1213     {
1214       struct goto_queue_node *q, *qe;
1215       tree return_val = NULL;
1216       int return_index, index;
1217       struct labels_s
1218       {
1219         struct goto_queue_node *q;
1220         tree label;
1221       } *labels;
1222
1223       return_index = VEC_length (tree, tf->dest_array);
1224       labels = XCNEWVEC (struct labels_s, return_index + 1);
1225
1226       q = tf->goto_queue;
1227       qe = q + tf->goto_queue_active;
1228       for (; q < qe; q++)
1229         {
1230           index = q->index < 0 ? return_index : q->index;
1231
1232           if (!labels[index].q)
1233             labels[index].q = q;
1234         }
1235
1236       for (index = 0; index < return_index + 1; index++)
1237         {
1238           tree lab;
1239
1240           q = labels[index].q;
1241           if (! q)
1242             continue;
1243
1244           lab = labels[index].label
1245             = create_artificial_label (tf_loc);
1246
1247           if (index == return_index)
1248             do_return_redirection (q, lab, NULL, &return_val);
1249           else
1250             do_goto_redirection (q, lab, NULL, tf);
1251
1252           x = gimple_build_label (lab);
1253           gimple_seq_add_stmt (&new_stmt, x);
1254
1255           seq = lower_try_finally_dup_block (finally, state);
1256           lower_eh_constructs_1 (state, seq);
1257           gimple_seq_add_seq (&new_stmt, seq);
1258
1259           gimple_seq_add_stmt (&new_stmt, q->cont_stmt);
1260           maybe_record_in_goto_queue (state, q->cont_stmt);
1261         }
1262
1263       for (q = tf->goto_queue; q < qe; q++)
1264         {
1265           tree lab;
1266
1267           index = q->index < 0 ? return_index : q->index;
1268
1269           if (labels[index].q == q)
1270             continue;
1271
1272           lab = labels[index].label;
1273
1274           if (index == return_index)
1275             do_return_redirection (q, lab, NULL, &return_val);
1276           else
1277             do_goto_redirection (q, lab, NULL, tf);
1278         }
1279
1280       replace_goto_queue (tf);
1281       free (labels);
1282     }
1283
1284   /* Need to link new stmts after running replace_goto_queue due
1285      to not wanting to process the same goto stmts twice.  */
1286   gimple_seq_add_seq (&tf->top_p_seq, new_stmt);
1287 }
1288
1289 /* A subroutine of lower_try_finally.  There are multiple edges incoming
1290    and outgoing from the finally block.  Implement this by instrumenting
1291    each incoming edge and creating a switch statement at the end of the
1292    finally block that branches to the appropriate destination.  */
1293
1294 static void
1295 lower_try_finally_switch (struct leh_state *state, struct leh_tf_state *tf)
1296 {
1297   struct goto_queue_node *q, *qe;
1298   tree return_val = NULL;
1299   tree finally_tmp, finally_label;
1300   int return_index, eh_index, fallthru_index;
1301   int nlabels, ndests, j, last_case_index;
1302   tree last_case;
1303   VEC (tree,heap) *case_label_vec;
1304   gimple_seq switch_body;
1305   gimple x;
1306   tree tmp;
1307   gimple switch_stmt;
1308   gimple_seq finally;
1309   struct pointer_map_t *cont_map = NULL;
1310   /* The location of the TRY_FINALLY stmt.  */
1311   location_t tf_loc = gimple_location (tf->try_finally_expr);
1312   /* The location of the finally block.  */
1313   location_t finally_loc;
1314
1315   switch_body = gimple_seq_alloc ();
1316
1317   /* Mash the TRY block to the head of the chain.  */
1318   finally = gimple_try_cleanup (tf->top_p);
1319   tf->top_p_seq = gimple_try_eval (tf->top_p);
1320
1321   /* The location of the finally is either the last stmt in the finally
1322      block or the location of the TRY_FINALLY itself.  */
1323   finally_loc = gimple_seq_last_stmt (tf->top_p_seq) != NULL ?
1324     gimple_location (gimple_seq_last_stmt (tf->top_p_seq))
1325     : tf_loc;
1326
1327   /* Lower the finally block itself.  */
1328   lower_eh_constructs_1 (state, finally);
1329
1330   /* Prepare for switch statement generation.  */
1331   nlabels = VEC_length (tree, tf->dest_array);
1332   return_index = nlabels;
1333   eh_index = return_index + tf->may_return;
1334   fallthru_index = eh_index + tf->may_throw;
1335   ndests = fallthru_index + tf->may_fallthru;
1336
1337   finally_tmp = create_tmp_var (integer_type_node, "finally_tmp");
1338   finally_label = create_artificial_label (finally_loc);
1339
1340   /* We use VEC_quick_push on case_label_vec throughout this function,
1341      since we know the size in advance and allocate precisely as muce
1342      space as needed.  */
1343   case_label_vec = VEC_alloc (tree, heap, ndests);
1344   last_case = NULL;
1345   last_case_index = 0;
1346
1347   /* Begin inserting code for getting to the finally block.  Things
1348      are done in this order to correspond to the sequence the code is
1349      layed out.  */
1350
1351   if (tf->may_fallthru)
1352     {
1353       x = gimple_build_assign (finally_tmp,
1354                                build_int_cst (NULL, fallthru_index));
1355       gimple_seq_add_stmt (&tf->top_p_seq, x);
1356
1357       last_case = build3 (CASE_LABEL_EXPR, void_type_node,
1358                           build_int_cst (NULL, fallthru_index),
1359                           NULL, create_artificial_label (tf_loc));
1360       VEC_quick_push (tree, case_label_vec, last_case);
1361       last_case_index++;
1362
1363       x = gimple_build_label (CASE_LABEL (last_case));
1364       gimple_seq_add_stmt (&switch_body, x);
1365
1366       tmp = lower_try_finally_fallthru_label (tf);
1367       x = gimple_build_goto (tmp);
1368       gimple_seq_add_stmt (&switch_body, x);
1369     }
1370
1371   if (tf->may_throw)
1372     {
1373       emit_post_landing_pad (&eh_seq, tf->region);
1374
1375       x = gimple_build_assign (finally_tmp,
1376                                build_int_cst (NULL, eh_index));
1377       gimple_seq_add_stmt (&eh_seq, x);
1378
1379       x = gimple_build_goto (finally_label);
1380       gimple_seq_add_stmt (&eh_seq, x);
1381
1382       last_case = build3 (CASE_LABEL_EXPR, void_type_node,
1383                           build_int_cst (NULL, eh_index),
1384                           NULL, create_artificial_label (tf_loc));
1385       VEC_quick_push (tree, case_label_vec, last_case);
1386       last_case_index++;
1387
1388       x = gimple_build_label (CASE_LABEL (last_case));
1389       gimple_seq_add_stmt (&eh_seq, x);
1390       emit_resx (&eh_seq, tf->region);
1391     }
1392
1393   x = gimple_build_label (finally_label);
1394   gimple_seq_add_stmt (&tf->top_p_seq, x);
1395
1396   gimple_seq_add_seq (&tf->top_p_seq, finally);
1397
1398   /* Redirect each incoming goto edge.  */
1399   q = tf->goto_queue;
1400   qe = q + tf->goto_queue_active;
1401   j = last_case_index + tf->may_return;
1402   /* Prepare the assignments to finally_tmp that are executed upon the
1403      entrance through a particular edge. */
1404   for (; q < qe; ++q)
1405     {
1406       gimple_seq mod;
1407       int switch_id;
1408       unsigned int case_index;
1409
1410       mod = gimple_seq_alloc ();
1411
1412       if (q->index < 0)
1413         {
1414           x = gimple_build_assign (finally_tmp,
1415                                    build_int_cst (NULL, return_index));
1416           gimple_seq_add_stmt (&mod, x);
1417           do_return_redirection (q, finally_label, mod, &return_val);
1418           switch_id = return_index;
1419         }
1420       else
1421         {
1422           x = gimple_build_assign (finally_tmp,
1423                                    build_int_cst (NULL, q->index));
1424           gimple_seq_add_stmt (&mod, x);
1425           do_goto_redirection (q, finally_label, mod, tf);
1426           switch_id = q->index;
1427         }
1428
1429       case_index = j + q->index;
1430       if (VEC_length (tree, case_label_vec) <= case_index
1431           || !VEC_index (tree, case_label_vec, case_index))
1432         {
1433           tree case_lab;
1434           void **slot;
1435           case_lab = build3 (CASE_LABEL_EXPR, void_type_node,
1436                              build_int_cst (NULL, switch_id),
1437                              NULL, NULL);
1438           /* We store the cont_stmt in the pointer map, so that we can recover
1439              it in the loop below.  We don't create the new label while
1440              walking the goto_queue because pointers don't offer a stable
1441              order.  */
1442           if (!cont_map)
1443             cont_map = pointer_map_create ();
1444           slot = pointer_map_insert (cont_map, case_lab);
1445           *slot = q->cont_stmt;
1446           VEC_quick_push (tree, case_label_vec, case_lab);
1447         }
1448     }
1449   for (j = last_case_index; j < last_case_index + nlabels; j++)
1450     {
1451       tree label;
1452       gimple cont_stmt;
1453       void **slot;
1454
1455       last_case = VEC_index (tree, case_label_vec, j);
1456
1457       gcc_assert (last_case);
1458       gcc_assert (cont_map);
1459
1460       slot = pointer_map_contains (cont_map, last_case);
1461       /* As the comment above suggests, CASE_LABEL (last_case) was just a
1462          placeholder, it does not store an actual label, yet. */
1463       gcc_assert (slot);
1464       cont_stmt = *(gimple *) slot;
1465
1466       label = create_artificial_label (tf_loc);
1467       CASE_LABEL (last_case) = label;
1468
1469       x = gimple_build_label (label);
1470       gimple_seq_add_stmt (&switch_body, x);
1471       gimple_seq_add_stmt (&switch_body, cont_stmt);
1472       maybe_record_in_goto_queue (state, cont_stmt);
1473     }
1474   if (cont_map)
1475     pointer_map_destroy (cont_map);
1476
1477   replace_goto_queue (tf);
1478
1479   /* Make sure that the last case is the default label, as one is required.
1480      Then sort the labels, which is also required in GIMPLE.  */
1481   CASE_LOW (last_case) = NULL;
1482   sort_case_labels (case_label_vec);
1483
1484   /* Build the switch statement, setting last_case to be the default
1485      label.  */
1486   switch_stmt = gimple_build_switch_vec (finally_tmp, last_case,
1487                                          case_label_vec);
1488   gimple_set_location (switch_stmt, finally_loc);
1489
1490   /* Need to link SWITCH_STMT after running replace_goto_queue
1491      due to not wanting to process the same goto stmts twice.  */
1492   gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1493   gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1494 }
1495
1496 /* Decide whether or not we are going to duplicate the finally block.
1497    There are several considerations.
1498
1499    First, if this is Java, then the finally block contains code
1500    written by the user.  It has line numbers associated with it,
1501    so duplicating the block means it's difficult to set a breakpoint.
1502    Since controlling code generation via -g is verboten, we simply
1503    never duplicate code without optimization.
1504
1505    Second, we'd like to prevent egregious code growth.  One way to
1506    do this is to estimate the size of the finally block, multiply
1507    that by the number of copies we'd need to make, and compare against
1508    the estimate of the size of the switch machinery we'd have to add.  */
1509
1510 static bool
1511 decide_copy_try_finally (int ndests, gimple_seq finally)
1512 {
1513   int f_estimate, sw_estimate;
1514
1515   if (!optimize)
1516     return false;
1517
1518   /* Finally estimate N times, plus N gotos.  */
1519   f_estimate = count_insns_seq (finally, &eni_size_weights);
1520   f_estimate = (f_estimate + 1) * ndests;
1521
1522   /* Switch statement (cost 10), N variable assignments, N gotos.  */
1523   sw_estimate = 10 + 2 * ndests;
1524
1525   /* Optimize for size clearly wants our best guess.  */
1526   if (optimize_function_for_size_p (cfun))
1527     return f_estimate < sw_estimate;
1528
1529   /* ??? These numbers are completely made up so far.  */
1530   if (optimize > 1)
1531     return f_estimate < 100 || f_estimate < sw_estimate * 2;
1532   else
1533     return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1534 }
1535
1536
1537 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY_FINALLY nodes
1538    to a sequence of labels and blocks, plus the exception region trees
1539    that record all the magic.  This is complicated by the need to
1540    arrange for the FINALLY block to be executed on all exits.  */
1541
1542 static gimple_seq
1543 lower_try_finally (struct leh_state *state, gimple tp)
1544 {
1545   struct leh_tf_state this_tf;
1546   struct leh_state this_state;
1547   int ndests;
1548
1549   /* Process the try block.  */
1550
1551   memset (&this_tf, 0, sizeof (this_tf));
1552   this_tf.try_finally_expr = tp;
1553   this_tf.top_p = tp;
1554   this_tf.outer = state;
1555   if (using_eh_for_cleanups_p)
1556     this_tf.region = gen_eh_region_cleanup (state->cur_region);
1557   else
1558     this_tf.region = NULL;
1559
1560   this_state.cur_region = this_tf.region;
1561   this_state.ehp_region = state->ehp_region;
1562   this_state.tf = &this_tf;
1563
1564   lower_eh_constructs_1 (&this_state, gimple_try_eval(tp));
1565
1566   /* Determine if the try block is escaped through the bottom.  */
1567   this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1568
1569   /* Determine if any exceptions are possible within the try block.  */
1570   if (using_eh_for_cleanups_p)
1571     this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1572   if (this_tf.may_throw)
1573     honor_protect_cleanup_actions (state, &this_state, &this_tf);
1574
1575   /* Determine how many edges (still) reach the finally block.  Or rather,
1576      how many destinations are reached by the finally block.  Use this to
1577      determine how we process the finally block itself.  */
1578
1579   ndests = VEC_length (tree, this_tf.dest_array);
1580   ndests += this_tf.may_fallthru;
1581   ndests += this_tf.may_return;
1582   ndests += this_tf.may_throw;
1583
1584   /* If the FINALLY block is not reachable, dike it out.  */
1585   if (ndests == 0)
1586     {
1587       gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1588       gimple_try_set_cleanup (tp, NULL);
1589     }
1590   /* If the finally block doesn't fall through, then any destination
1591      we might try to impose there isn't reached either.  There may be
1592      some minor amount of cleanup and redirection still needed.  */
1593   else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1594     lower_try_finally_nofallthru (state, &this_tf);
1595
1596   /* We can easily special-case redirection to a single destination.  */
1597   else if (ndests == 1)
1598     lower_try_finally_onedest (state, &this_tf);
1599   else if (decide_copy_try_finally (ndests, gimple_try_cleanup (tp)))
1600     lower_try_finally_copy (state, &this_tf);
1601   else
1602     lower_try_finally_switch (state, &this_tf);
1603
1604   /* If someone requested we add a label at the end of the transformed
1605      block, do so.  */
1606   if (this_tf.fallthru_label)
1607     {
1608       /* This must be reached only if ndests == 0. */
1609       gimple x = gimple_build_label (this_tf.fallthru_label);
1610       gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1611     }
1612
1613   VEC_free (tree, heap, this_tf.dest_array);
1614   if (this_tf.goto_queue)
1615     free (this_tf.goto_queue);
1616   if (this_tf.goto_queue_map)
1617     pointer_map_destroy (this_tf.goto_queue_map);
1618
1619   return this_tf.top_p_seq;
1620 }
1621
1622 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY_CATCH with a
1623    list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1624    exception region trees that records all the magic.  */
1625
1626 static gimple_seq
1627 lower_catch (struct leh_state *state, gimple tp)
1628 {
1629   eh_region try_region = NULL;
1630   struct leh_state this_state = *state;
1631   gimple_stmt_iterator gsi;
1632   tree out_label;
1633   gimple_seq new_seq;
1634   gimple x;
1635   location_t try_catch_loc = gimple_location (tp);
1636
1637   if (flag_exceptions)
1638     {
1639       try_region = gen_eh_region_try (state->cur_region);
1640       this_state.cur_region = try_region;
1641     }
1642
1643   lower_eh_constructs_1 (&this_state, gimple_try_eval (tp));
1644
1645   if (!eh_region_may_contain_throw (try_region))
1646     return gimple_try_eval (tp);
1647
1648   new_seq = NULL;
1649   emit_eh_dispatch (&new_seq, try_region);
1650   emit_resx (&new_seq, try_region);
1651
1652   this_state.cur_region = state->cur_region;
1653   this_state.ehp_region = try_region;
1654
1655   out_label = NULL;
1656   for (gsi = gsi_start (gimple_try_cleanup (tp));
1657        !gsi_end_p (gsi);
1658        gsi_next (&gsi))
1659     {
1660       eh_catch c;
1661       gimple gcatch;
1662       gimple_seq handler;
1663
1664       gcatch = gsi_stmt (gsi);
1665       c = gen_eh_region_catch (try_region, gimple_catch_types (gcatch));
1666
1667       handler = gimple_catch_handler (gcatch);
1668       lower_eh_constructs_1 (&this_state, handler);
1669
1670       c->label = create_artificial_label (UNKNOWN_LOCATION);
1671       x = gimple_build_label (c->label);
1672       gimple_seq_add_stmt (&new_seq, x);
1673
1674       gimple_seq_add_seq (&new_seq, handler);
1675
1676       if (gimple_seq_may_fallthru (new_seq))
1677         {
1678           if (!out_label)
1679             out_label = create_artificial_label (try_catch_loc);
1680
1681           x = gimple_build_goto (out_label);
1682           gimple_seq_add_stmt (&new_seq, x);
1683         }
1684     }
1685
1686   gimple_try_set_cleanup (tp, new_seq);
1687
1688   return frob_into_branch_around (tp, try_region, out_label);
1689 }
1690
1691 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY with a
1692    GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1693    region trees that record all the magic.  */
1694
1695 static gimple_seq
1696 lower_eh_filter (struct leh_state *state, gimple tp)
1697 {
1698   struct leh_state this_state = *state;
1699   eh_region this_region = NULL;
1700   gimple inner, x;
1701   gimple_seq new_seq;
1702
1703   inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1704
1705   if (flag_exceptions)
1706     {
1707       this_region = gen_eh_region_allowed (state->cur_region,
1708                                            gimple_eh_filter_types (inner));
1709       this_state.cur_region = this_region;
1710     }
1711
1712   lower_eh_constructs_1 (&this_state, gimple_try_eval (tp));
1713
1714   if (!eh_region_may_contain_throw (this_region))
1715     return gimple_try_eval (tp);
1716
1717   new_seq = NULL;
1718   this_state.cur_region = state->cur_region;
1719   this_state.ehp_region = this_region;
1720
1721   emit_eh_dispatch (&new_seq, this_region);
1722   emit_resx (&new_seq, this_region);
1723
1724   this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1725   x = gimple_build_label (this_region->u.allowed.label);
1726   gimple_seq_add_stmt (&new_seq, x);
1727
1728   lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure (inner));
1729   gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1730
1731   gimple_try_set_cleanup (tp, new_seq);
1732
1733   return frob_into_branch_around (tp, this_region, NULL);
1734 }
1735
1736 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY with
1737    an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1738    plus the exception region trees that record all the magic.  */
1739
1740 static gimple_seq
1741 lower_eh_must_not_throw (struct leh_state *state, gimple tp)
1742 {
1743   struct leh_state this_state = *state;
1744
1745   if (flag_exceptions)
1746     {
1747       gimple inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1748       eh_region this_region;
1749
1750       this_region = gen_eh_region_must_not_throw (state->cur_region);
1751       this_region->u.must_not_throw.failure_decl
1752         = gimple_eh_must_not_throw_fndecl (inner);
1753       this_region->u.must_not_throw.failure_loc = gimple_location (tp);
1754
1755       /* In order to get mangling applied to this decl, we must mark it
1756          used now.  Otherwise, pass_ipa_free_lang_data won't think it
1757          needs to happen.  */
1758       TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1759
1760       this_state.cur_region = this_region;
1761     }
1762
1763   lower_eh_constructs_1 (&this_state, gimple_try_eval (tp));
1764
1765   return gimple_try_eval (tp);
1766 }
1767
1768 /* Implement a cleanup expression.  This is similar to try-finally,
1769    except that we only execute the cleanup block for exception edges.  */
1770
1771 static gimple_seq
1772 lower_cleanup (struct leh_state *state, gimple tp)
1773 {
1774   struct leh_state this_state = *state;
1775   eh_region this_region = NULL;
1776   struct leh_tf_state fake_tf;
1777   gimple_seq result;
1778
1779   if (flag_exceptions)
1780     {
1781       this_region = gen_eh_region_cleanup (state->cur_region);
1782       this_state.cur_region = this_region;
1783     }
1784
1785   lower_eh_constructs_1 (&this_state, gimple_try_eval (tp));
1786
1787   if (!eh_region_may_contain_throw (this_region))
1788     return gimple_try_eval (tp);
1789
1790   /* Build enough of a try-finally state so that we can reuse
1791      honor_protect_cleanup_actions.  */
1792   memset (&fake_tf, 0, sizeof (fake_tf));
1793   fake_tf.top_p = fake_tf.try_finally_expr = tp;
1794   fake_tf.outer = state;
1795   fake_tf.region = this_region;
1796   fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1797   fake_tf.may_throw = true;
1798
1799   honor_protect_cleanup_actions (state, NULL, &fake_tf);
1800
1801   if (fake_tf.may_throw)
1802     {
1803       /* In this case honor_protect_cleanup_actions had nothing to do,
1804          and we should process this normally.  */
1805       lower_eh_constructs_1 (state, gimple_try_cleanup (tp));
1806       result = frob_into_branch_around (tp, this_region,
1807                                         fake_tf.fallthru_label);
1808     }
1809   else
1810     {
1811       /* In this case honor_protect_cleanup_actions did nearly all of
1812          the work.  All we have left is to append the fallthru_label.  */
1813
1814       result = gimple_try_eval (tp);
1815       if (fake_tf.fallthru_label)
1816         {
1817           gimple x = gimple_build_label (fake_tf.fallthru_label);
1818           gimple_seq_add_stmt (&result, x);
1819         }
1820     }
1821   return result;
1822 }
1823
1824 /* Main loop for lowering eh constructs. Also moves gsi to the next
1825    statement. */
1826
1827 static void
1828 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1829 {
1830   gimple_seq replace;
1831   gimple x;
1832   gimple stmt = gsi_stmt (*gsi);
1833
1834   switch (gimple_code (stmt))
1835     {
1836     case GIMPLE_CALL:
1837       {
1838         tree fndecl = gimple_call_fndecl (stmt);
1839         tree rhs, lhs;
1840
1841         if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1842           switch (DECL_FUNCTION_CODE (fndecl))
1843             {
1844             case BUILT_IN_EH_POINTER:
1845               /* The front end may have generated a call to
1846                  __builtin_eh_pointer (0) within a catch region.  Replace
1847                  this zero argument with the current catch region number.  */
1848               if (state->ehp_region)
1849                 {
1850                   tree nr = build_int_cst (NULL, state->ehp_region->index);
1851                   gimple_call_set_arg (stmt, 0, nr);
1852                 }
1853               else
1854                 {
1855                   /* The user has dome something silly.  Remove it.  */
1856                   rhs = build_int_cst (ptr_type_node, 0);
1857                   goto do_replace;
1858                 }
1859               break;
1860
1861             case BUILT_IN_EH_FILTER:
1862               /* ??? This should never appear, but since it's a builtin it
1863                  is accessible to abuse by users.  Just remove it and
1864                  replace the use with the arbitrary value zero.  */
1865               rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
1866             do_replace:
1867               lhs = gimple_call_lhs (stmt);
1868               x = gimple_build_assign (lhs, rhs);
1869               gsi_insert_before (gsi, x, GSI_SAME_STMT);
1870               /* FALLTHRU */
1871
1872             case BUILT_IN_EH_COPY_VALUES:
1873               /* Likewise this should not appear.  Remove it.  */
1874               gsi_remove (gsi, true);
1875               return;
1876
1877             default:
1878               break;
1879             }
1880       }
1881       /* FALLTHRU */
1882
1883     case GIMPLE_ASSIGN:
1884       /* If the stmt can throw use a new temporary for the assignment
1885          to a LHS.  This makes sure the old value of the LHS is
1886          available on the EH edge.  */
1887       if (stmt_could_throw_p (stmt)
1888           && gimple_has_lhs (stmt)
1889           && !tree_could_throw_p (gimple_get_lhs (stmt))
1890           && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
1891         {
1892           tree lhs = gimple_get_lhs (stmt);
1893           tree tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
1894           gimple s = gimple_build_assign (lhs, tmp);
1895           gimple_set_location (s, gimple_location (stmt));
1896           gimple_set_block (s, gimple_block (stmt));
1897           gimple_set_lhs (stmt, tmp);
1898           if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
1899               || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
1900             DECL_GIMPLE_REG_P (tmp) = 1;
1901           gsi_insert_after (gsi, s, GSI_SAME_STMT);
1902         }
1903       /* Look for things that can throw exceptions, and record them.  */
1904       if (state->cur_region && stmt_could_throw_p (stmt))
1905         {
1906           record_stmt_eh_region (state->cur_region, stmt);
1907           note_eh_region_may_contain_throw (state->cur_region);
1908         }
1909       break;
1910
1911     case GIMPLE_COND:
1912     case GIMPLE_GOTO:
1913     case GIMPLE_RETURN:
1914       maybe_record_in_goto_queue (state, stmt);
1915       break;
1916
1917     case GIMPLE_SWITCH:
1918       verify_norecord_switch_expr (state, stmt);
1919       break;
1920
1921     case GIMPLE_TRY:
1922       if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
1923         replace = lower_try_finally (state, stmt);
1924       else
1925         {
1926           x = gimple_seq_first_stmt (gimple_try_cleanup (stmt));
1927           if (!x)
1928             {
1929               replace = gimple_try_eval (stmt);
1930               lower_eh_constructs_1 (state, replace);
1931             }
1932           else
1933             switch (gimple_code (x))
1934               {
1935                 case GIMPLE_CATCH:
1936                     replace = lower_catch (state, stmt);
1937                     break;
1938                 case GIMPLE_EH_FILTER:
1939                     replace = lower_eh_filter (state, stmt);
1940                     break;
1941                 case GIMPLE_EH_MUST_NOT_THROW:
1942                     replace = lower_eh_must_not_throw (state, stmt);
1943                     break;
1944                 default:
1945                     replace = lower_cleanup (state, stmt);
1946                     break;
1947               }
1948         }
1949
1950       /* Remove the old stmt and insert the transformed sequence
1951          instead. */
1952       gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
1953       gsi_remove (gsi, true);
1954
1955       /* Return since we don't want gsi_next () */
1956       return;
1957
1958     default:
1959       /* A type, a decl, or some kind of statement that we're not
1960          interested in.  Don't walk them.  */
1961       break;
1962     }
1963
1964   gsi_next (gsi);
1965 }
1966
1967 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
1968
1969 static void
1970 lower_eh_constructs_1 (struct leh_state *state, gimple_seq seq)
1971 {
1972   gimple_stmt_iterator gsi;
1973   for (gsi = gsi_start (seq); !gsi_end_p (gsi);)
1974     lower_eh_constructs_2 (state, &gsi);
1975 }
1976
1977 static unsigned int
1978 lower_eh_constructs (void)
1979 {
1980   struct leh_state null_state;
1981   gimple_seq bodyp;
1982
1983   bodyp = gimple_body (current_function_decl);
1984   if (bodyp == NULL)
1985     return 0;
1986
1987   finally_tree = htab_create (31, struct_ptr_hash, struct_ptr_eq, free);
1988   eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
1989   memset (&null_state, 0, sizeof (null_state));
1990
1991   collect_finally_tree_1 (bodyp, NULL);
1992   lower_eh_constructs_1 (&null_state, bodyp);
1993
1994   /* We assume there's a return statement, or something, at the end of
1995      the function, and thus ploping the EH sequence afterward won't
1996      change anything.  */
1997   gcc_assert (!gimple_seq_may_fallthru (bodyp));
1998   gimple_seq_add_seq (&bodyp, eh_seq);
1999
2000   /* We assume that since BODYP already existed, adding EH_SEQ to it
2001      didn't change its value, and we don't have to re-set the function.  */
2002   gcc_assert (bodyp == gimple_body (current_function_decl));
2003
2004   htab_delete (finally_tree);
2005   BITMAP_FREE (eh_region_may_contain_throw_map);
2006   eh_seq = NULL;
2007
2008   /* If this function needs a language specific EH personality routine
2009      and the frontend didn't already set one do so now.  */
2010   if (function_needs_eh_personality (cfun) == eh_personality_lang
2011       && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2012     DECL_FUNCTION_PERSONALITY (current_function_decl)
2013       = lang_hooks.eh_personality ();
2014
2015   return 0;
2016 }
2017
2018 struct gimple_opt_pass pass_lower_eh =
2019 {
2020  {
2021   GIMPLE_PASS,
2022   "eh",                                 /* name */
2023   NULL,                                 /* gate */
2024   lower_eh_constructs,                  /* execute */
2025   NULL,                                 /* sub */
2026   NULL,                                 /* next */
2027   0,                                    /* static_pass_number */
2028   TV_TREE_EH,                           /* tv_id */
2029   PROP_gimple_lcf,                      /* properties_required */
2030   PROP_gimple_leh,                      /* properties_provided */
2031   0,                                    /* properties_destroyed */
2032   0,                                    /* todo_flags_start */
2033   TODO_dump_func                        /* todo_flags_finish */
2034  }
2035 };
2036 \f
2037 /* Create the multiple edges from an EH_DISPATCH statement to all of
2038    the possible handlers for its EH region.  Return true if there's
2039    no fallthru edge; false if there is.  */
2040
2041 bool
2042 make_eh_dispatch_edges (gimple stmt)
2043 {
2044   eh_region r;
2045   eh_catch c;
2046   basic_block src, dst;
2047
2048   r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2049   src = gimple_bb (stmt);
2050
2051   switch (r->type)
2052     {
2053     case ERT_TRY:
2054       for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2055         {
2056           dst = label_to_block (c->label);
2057           make_edge (src, dst, 0);
2058
2059           /* A catch-all handler doesn't have a fallthru.  */
2060           if (c->type_list == NULL)
2061             return false;
2062         }
2063       break;
2064
2065     case ERT_ALLOWED_EXCEPTIONS:
2066       dst = label_to_block (r->u.allowed.label);
2067       make_edge (src, dst, 0);
2068       break;
2069
2070     default:
2071       gcc_unreachable ();
2072     }
2073
2074   return true;
2075 }
2076
2077 /* Create the single EH edge from STMT to its nearest landing pad,
2078    if there is such a landing pad within the current function.  */
2079
2080 void
2081 make_eh_edges (gimple stmt)
2082 {
2083   basic_block src, dst;
2084   eh_landing_pad lp;
2085   int lp_nr;
2086
2087   lp_nr = lookup_stmt_eh_lp (stmt);
2088   if (lp_nr <= 0)
2089     return;
2090
2091   lp = get_eh_landing_pad_from_number (lp_nr);
2092   gcc_assert (lp != NULL);
2093
2094   src = gimple_bb (stmt);
2095   dst = label_to_block (lp->post_landing_pad);
2096   make_edge (src, dst, EDGE_EH);
2097 }
2098
2099 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2100    do not actually perform the final edge redirection.
2101
2102    CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2103    we intend to change the destination EH region as well; this means
2104    EH_LANDING_PAD_NR must already be set on the destination block label.
2105    If false, we're being called from generic cfg manipulation code and we
2106    should preserve our place within the region tree.  */
2107
2108 static void
2109 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2110 {
2111   eh_landing_pad old_lp, new_lp;
2112   basic_block old_bb;
2113   gimple throw_stmt;
2114   int old_lp_nr, new_lp_nr;
2115   tree old_label, new_label;
2116   edge_iterator ei;
2117   edge e;
2118
2119   old_bb = edge_in->dest;
2120   old_label = gimple_block_label (old_bb);
2121   old_lp_nr = EH_LANDING_PAD_NR (old_label);
2122   gcc_assert (old_lp_nr > 0);
2123   old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2124
2125   throw_stmt = last_stmt (edge_in->src);
2126   gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2127
2128   new_label = gimple_block_label (new_bb);
2129
2130   /* Look for an existing region that might be using NEW_BB already.  */
2131   new_lp_nr = EH_LANDING_PAD_NR (new_label);
2132   if (new_lp_nr)
2133     {
2134       new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2135       gcc_assert (new_lp);
2136       
2137       /* Unless CHANGE_REGION is true, the new and old landing pad
2138          had better be associated with the same EH region.  */
2139       gcc_assert (change_region || new_lp->region == old_lp->region);
2140     }
2141   else
2142     {
2143       new_lp = NULL;
2144       gcc_assert (!change_region);
2145     }
2146
2147   /* Notice when we redirect the last EH edge away from OLD_BB.  */
2148   FOR_EACH_EDGE (e, ei, old_bb->preds)
2149     if (e != edge_in && (e->flags & EDGE_EH))
2150       break;
2151
2152   if (new_lp)
2153     {
2154       /* NEW_LP already exists.  If there are still edges into OLD_LP,
2155          there's nothing to do with the EH tree.  If there are no more
2156          edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2157          If CHANGE_REGION is true, then our caller is expecting to remove
2158          the landing pad.  */
2159       if (e == NULL && !change_region)
2160         remove_eh_landing_pad (old_lp);
2161     }
2162   else
2163     {
2164       /* No correct landing pad exists.  If there are no more edges
2165          into OLD_LP, then we can simply re-use the existing landing pad.
2166          Otherwise, we have to create a new landing pad.  */
2167       if (e == NULL)
2168         {
2169           EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2170           new_lp = old_lp;
2171         }
2172       else
2173         new_lp = gen_eh_landing_pad (old_lp->region);
2174       new_lp->post_landing_pad = new_label;
2175       EH_LANDING_PAD_NR (new_label) = new_lp->index;
2176     }
2177
2178   /* Maybe move the throwing statement to the new region.  */
2179   if (old_lp != new_lp)
2180     {
2181       remove_stmt_from_eh_lp (throw_stmt);
2182       add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2183     }
2184 }
2185
2186 /* Redirect EH edge E to NEW_BB.  */
2187
2188 edge
2189 redirect_eh_edge (edge edge_in, basic_block new_bb)
2190 {
2191   redirect_eh_edge_1 (edge_in, new_bb, false);
2192   return ssa_redirect_edge (edge_in, new_bb);
2193 }
2194
2195 /* This is a subroutine of gimple_redirect_edge_and_branch.  Update the
2196    labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2197    The actual edge update will happen in the caller.  */
2198
2199 void
2200 redirect_eh_dispatch_edge (gimple stmt, edge e, basic_block new_bb)
2201 {
2202   tree new_lab = gimple_block_label (new_bb);
2203   bool any_changed = false;
2204   basic_block old_bb;
2205   eh_region r;
2206   eh_catch c;
2207
2208   r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2209   switch (r->type)
2210     {
2211     case ERT_TRY:
2212       for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2213         {
2214           old_bb = label_to_block (c->label);
2215           if (old_bb == e->dest)
2216             {
2217               c->label = new_lab;
2218               any_changed = true;
2219             }
2220         }
2221       break;
2222
2223     case ERT_ALLOWED_EXCEPTIONS:
2224       old_bb = label_to_block (r->u.allowed.label);
2225       gcc_assert (old_bb == e->dest);
2226       r->u.allowed.label = new_lab;
2227       any_changed = true;
2228       break;
2229
2230     default:
2231       gcc_unreachable ();
2232     }
2233
2234   gcc_assert (any_changed);
2235 }
2236 \f
2237 /* Helper function for operation_could_trap_p and stmt_could_throw_p.  */
2238
2239 bool
2240 operation_could_trap_helper_p (enum tree_code op,
2241                                bool fp_operation,
2242                                bool honor_trapv,
2243                                bool honor_nans,
2244                                bool honor_snans,
2245                                tree divisor,
2246                                bool *handled)
2247 {
2248   *handled = true;
2249   switch (op)
2250     {
2251     case TRUNC_DIV_EXPR:
2252     case CEIL_DIV_EXPR:
2253     case FLOOR_DIV_EXPR:
2254     case ROUND_DIV_EXPR:
2255     case EXACT_DIV_EXPR:
2256     case CEIL_MOD_EXPR:
2257     case FLOOR_MOD_EXPR:
2258     case ROUND_MOD_EXPR:
2259     case TRUNC_MOD_EXPR:
2260     case RDIV_EXPR:
2261       if (honor_snans || honor_trapv)
2262         return true;
2263       if (fp_operation)
2264         return flag_trapping_math;
2265       if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2266         return true;
2267       return false;
2268
2269     case LT_EXPR:
2270     case LE_EXPR:
2271     case GT_EXPR:
2272     case GE_EXPR:
2273     case LTGT_EXPR:
2274       /* Some floating point comparisons may trap.  */
2275       return honor_nans;
2276
2277     case EQ_EXPR:
2278     case NE_EXPR:
2279     case UNORDERED_EXPR:
2280     case ORDERED_EXPR:
2281     case UNLT_EXPR:
2282     case UNLE_EXPR:
2283     case UNGT_EXPR:
2284     case UNGE_EXPR:
2285     case UNEQ_EXPR:
2286       return honor_snans;
2287
2288     case CONVERT_EXPR:
2289     case FIX_TRUNC_EXPR:
2290       /* Conversion of floating point might trap.  */
2291       return honor_nans;
2292
2293     case NEGATE_EXPR:
2294     case ABS_EXPR:
2295     case CONJ_EXPR:
2296       /* These operations don't trap with floating point.  */
2297       if (honor_trapv)
2298         return true;
2299       return false;
2300
2301     case PLUS_EXPR:
2302     case MINUS_EXPR:
2303     case MULT_EXPR:
2304       /* Any floating arithmetic may trap.  */
2305       if (fp_operation && flag_trapping_math)
2306         return true;
2307       if (honor_trapv)
2308         return true;
2309       return false;
2310
2311     default:
2312       /* Any floating arithmetic may trap.  */
2313       if (fp_operation && flag_trapping_math)
2314         return true;
2315
2316       *handled = false;
2317       return false;
2318     }
2319 }
2320
2321 /* Return true if operation OP may trap.  FP_OPERATION is true if OP is applied
2322    on floating-point values.  HONOR_TRAPV is true if OP is applied on integer
2323    type operands that may trap.  If OP is a division operator, DIVISOR contains
2324    the value of the divisor.  */
2325
2326 bool
2327 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2328                         tree divisor)
2329 {
2330   bool honor_nans = (fp_operation && flag_trapping_math
2331                      && !flag_finite_math_only);
2332   bool honor_snans = fp_operation && flag_signaling_nans != 0;
2333   bool handled;
2334
2335   if (TREE_CODE_CLASS (op) != tcc_comparison
2336       && TREE_CODE_CLASS (op) != tcc_unary
2337       && TREE_CODE_CLASS (op) != tcc_binary)
2338     return false;
2339
2340   return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2341                                         honor_nans, honor_snans, divisor,
2342                                         &handled);
2343 }
2344
2345 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2346    location or floating point arithmetic.  C.f. the rtl version, may_trap_p.
2347    This routine expects only GIMPLE lhs or rhs input.  */
2348
2349 bool
2350 tree_could_trap_p (tree expr)
2351 {
2352   enum tree_code code;
2353   bool fp_operation = false;
2354   bool honor_trapv = false;
2355   tree t, base, div = NULL_TREE;
2356
2357   if (!expr)
2358     return false;
2359
2360   code = TREE_CODE (expr);
2361   t = TREE_TYPE (expr);
2362
2363   if (t)
2364     {
2365       if (COMPARISON_CLASS_P (expr))
2366         fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2367       else
2368         fp_operation = FLOAT_TYPE_P (t);
2369       honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2370     }
2371
2372   if (TREE_CODE_CLASS (code) == tcc_binary)
2373     div = TREE_OPERAND (expr, 1);
2374   if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2375     return true;
2376
2377  restart:
2378   switch (code)
2379     {
2380     case TARGET_MEM_REF:
2381       /* For TARGET_MEM_REFs use the information based on the original
2382          reference.  */
2383       expr = TMR_ORIGINAL (expr);
2384       code = TREE_CODE (expr);
2385       goto restart;
2386
2387     case COMPONENT_REF:
2388     case REALPART_EXPR:
2389     case IMAGPART_EXPR:
2390     case BIT_FIELD_REF:
2391     case VIEW_CONVERT_EXPR:
2392     case WITH_SIZE_EXPR:
2393       expr = TREE_OPERAND (expr, 0);
2394       code = TREE_CODE (expr);
2395       goto restart;
2396
2397     case ARRAY_RANGE_REF:
2398       base = TREE_OPERAND (expr, 0);
2399       if (tree_could_trap_p (base))
2400         return true;
2401       if (TREE_THIS_NOTRAP (expr))
2402         return false;
2403       return !range_in_array_bounds_p (expr);
2404
2405     case ARRAY_REF:
2406       base = TREE_OPERAND (expr, 0);
2407       if (tree_could_trap_p (base))
2408         return true;
2409       if (TREE_THIS_NOTRAP (expr))
2410         return false;
2411       return !in_array_bounds_p (expr);
2412
2413     case INDIRECT_REF:
2414     case ALIGN_INDIRECT_REF:
2415     case MISALIGNED_INDIRECT_REF:
2416       return !TREE_THIS_NOTRAP (expr);
2417
2418     case ASM_EXPR:
2419       return TREE_THIS_VOLATILE (expr);
2420
2421     case CALL_EXPR:
2422       t = get_callee_fndecl (expr);
2423       /* Assume that calls to weak functions may trap.  */
2424       if (!t || !DECL_P (t) || DECL_WEAK (t))
2425         return true;
2426       return false;
2427
2428     default:
2429       return false;
2430     }
2431 }
2432
2433
2434 /* Helper for stmt_could_throw_p.  Return true if STMT (assumed to be a
2435    an assignment or a conditional) may throw.  */
2436
2437 static bool
2438 stmt_could_throw_1_p (gimple stmt)
2439 {
2440   enum tree_code code = gimple_expr_code (stmt);
2441   bool honor_nans = false;
2442   bool honor_snans = false;
2443   bool fp_operation = false;
2444   bool honor_trapv = false;
2445   tree t;
2446   size_t i;
2447   bool handled, ret;
2448
2449   if (TREE_CODE_CLASS (code) == tcc_comparison
2450       || TREE_CODE_CLASS (code) == tcc_unary
2451       || TREE_CODE_CLASS (code) == tcc_binary)
2452     {
2453       t = gimple_expr_type (stmt);
2454       fp_operation = FLOAT_TYPE_P (t);
2455       if (fp_operation)
2456         {
2457           honor_nans = flag_trapping_math && !flag_finite_math_only;
2458           honor_snans = flag_signaling_nans != 0;
2459         }
2460       else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2461         honor_trapv = true;
2462     }
2463
2464   /* Check if the main expression may trap.  */
2465   t = is_gimple_assign (stmt) ? gimple_assign_rhs2 (stmt) : NULL;
2466   ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2467                                        honor_nans, honor_snans, t,
2468                                        &handled);
2469   if (handled)
2470     return ret;
2471
2472   /* If the expression does not trap, see if any of the individual operands may
2473      trap.  */
2474   for (i = 0; i < gimple_num_ops (stmt); i++)
2475     if (tree_could_trap_p (gimple_op (stmt, i)))
2476       return true;
2477
2478   return false;
2479 }
2480
2481
2482 /* Return true if statement STMT could throw an exception.  */
2483
2484 bool
2485 stmt_could_throw_p (gimple stmt)
2486 {
2487   if (!flag_exceptions)
2488     return false;
2489
2490   /* The only statements that can throw an exception are assignments,
2491      conditionals, calls, resx, and asms.  */
2492   switch (gimple_code (stmt))
2493     {
2494     case GIMPLE_RESX:
2495       return true;
2496
2497     case GIMPLE_CALL:
2498       return !gimple_call_nothrow_p (stmt);
2499
2500     case GIMPLE_ASSIGN:
2501     case GIMPLE_COND:
2502       if (!flag_non_call_exceptions)
2503         return false;
2504       return stmt_could_throw_1_p (stmt);
2505
2506     case GIMPLE_ASM:
2507       if (!flag_non_call_exceptions)
2508         return false;
2509       return gimple_asm_volatile_p (stmt);
2510
2511     default:
2512       return false;
2513     }
2514 }
2515
2516
2517 /* Return true if expression T could throw an exception.  */
2518
2519 bool
2520 tree_could_throw_p (tree t)
2521 {
2522   if (!flag_exceptions)
2523     return false;
2524   if (TREE_CODE (t) == MODIFY_EXPR)
2525     {
2526       if (flag_non_call_exceptions
2527           && tree_could_trap_p (TREE_OPERAND (t, 0)))
2528         return true;
2529       t = TREE_OPERAND (t, 1);
2530     }
2531
2532   if (TREE_CODE (t) == WITH_SIZE_EXPR)
2533     t = TREE_OPERAND (t, 0);
2534   if (TREE_CODE (t) == CALL_EXPR)
2535     return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2536   if (flag_non_call_exceptions)
2537     return tree_could_trap_p (t);
2538   return false;
2539 }
2540
2541 /* Return true if STMT can throw an exception that is not caught within
2542    the current function (CFUN).  */
2543
2544 bool
2545 stmt_can_throw_external (gimple stmt)
2546 {
2547   int lp_nr;
2548
2549   if (!stmt_could_throw_p (stmt))
2550     return false;
2551
2552   lp_nr = lookup_stmt_eh_lp (stmt);
2553   return lp_nr == 0;
2554 }
2555
2556 /* Return true if STMT can throw an exception that is caught within
2557    the current function (CFUN).  */
2558
2559 bool
2560 stmt_can_throw_internal (gimple stmt)
2561 {
2562   int lp_nr;
2563
2564   if (!stmt_could_throw_p (stmt))
2565     return false;
2566
2567   lp_nr = lookup_stmt_eh_lp (stmt);
2568   return lp_nr > 0;
2569 }
2570
2571 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2572    remove any entry it might have from the EH table.  Return true if
2573    any change was made.  */
2574
2575 bool
2576 maybe_clean_eh_stmt_fn (struct function *ifun, gimple stmt)
2577 {
2578   if (stmt_could_throw_p (stmt))
2579     return false;
2580   return remove_stmt_from_eh_lp_fn (ifun, stmt);
2581 }
2582
2583 /* Likewise, but always use the current function.  */
2584
2585 bool
2586 maybe_clean_eh_stmt (gimple stmt)
2587 {
2588   return maybe_clean_eh_stmt_fn (cfun, stmt);
2589 }
2590
2591 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2592    OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2593    in the table if it should be in there.  Return TRUE if a replacement was
2594    done that my require an EH edge purge.  */
2595
2596 bool
2597 maybe_clean_or_replace_eh_stmt (gimple old_stmt, gimple new_stmt)
2598 {
2599   int lp_nr = lookup_stmt_eh_lp (old_stmt);
2600
2601   if (lp_nr != 0)
2602     {
2603       bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2604
2605       if (new_stmt == old_stmt && new_stmt_could_throw)
2606         return false;
2607
2608       remove_stmt_from_eh_lp (old_stmt);
2609       if (new_stmt_could_throw)
2610         {
2611           add_stmt_to_eh_lp (new_stmt, lp_nr);
2612           return false;
2613         }
2614       else
2615         return true;
2616     }
2617
2618   return false;
2619 }
2620
2621 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statment NEW_STMT
2622    in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT.  The MAP
2623    operand is the return value of duplicate_eh_regions.  */
2624
2625 bool
2626 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple new_stmt,
2627                             struct function *old_fun, gimple old_stmt,
2628                             struct pointer_map_t *map, int default_lp_nr)
2629 {
2630   int old_lp_nr, new_lp_nr;
2631   void **slot;
2632
2633   if (!stmt_could_throw_p (new_stmt))
2634     return false;
2635
2636   old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2637   if (old_lp_nr == 0)
2638     {
2639       if (default_lp_nr == 0)
2640         return false;
2641       new_lp_nr = default_lp_nr;
2642     }
2643   else if (old_lp_nr > 0)
2644     {
2645       eh_landing_pad old_lp, new_lp;
2646
2647       old_lp = VEC_index (eh_landing_pad, old_fun->eh->lp_array, old_lp_nr);
2648       slot = pointer_map_contains (map, old_lp);
2649       new_lp = (eh_landing_pad) *slot;
2650       new_lp_nr = new_lp->index;
2651     }
2652   else
2653     {
2654       eh_region old_r, new_r;
2655
2656       old_r = VEC_index (eh_region, old_fun->eh->region_array, -old_lp_nr);
2657       slot = pointer_map_contains (map, old_r);
2658       new_r = (eh_region) *slot;
2659       new_lp_nr = -new_r->index;
2660     }
2661
2662   add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2663   return true;
2664 }
2665
2666 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2667    and thus no remapping is required.  */
2668
2669 bool
2670 maybe_duplicate_eh_stmt (gimple new_stmt, gimple old_stmt)
2671 {
2672   int lp_nr;
2673
2674   if (!stmt_could_throw_p (new_stmt))
2675     return false;
2676
2677   lp_nr = lookup_stmt_eh_lp (old_stmt);
2678   if (lp_nr == 0)
2679     return false;
2680
2681   add_stmt_to_eh_lp (new_stmt, lp_nr);
2682   return true;
2683 }
2684 \f
2685 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2686    GIMPLE_TRY) that are similar enough to be considered the same.  Currently
2687    this only handles handlers consisting of a single call, as that's the
2688    important case for C++: a destructor call for a particular object showing
2689    up in multiple handlers.  */
2690
2691 static bool
2692 same_handler_p (gimple_seq oneh, gimple_seq twoh)
2693 {
2694   gimple_stmt_iterator gsi;
2695   gimple ones, twos;
2696   unsigned int ai;
2697
2698   gsi = gsi_start (oneh);
2699   if (!gsi_one_before_end_p (gsi))
2700     return false;
2701   ones = gsi_stmt (gsi);
2702
2703   gsi = gsi_start (twoh);
2704   if (!gsi_one_before_end_p (gsi))
2705     return false;
2706   twos = gsi_stmt (gsi);
2707
2708   if (!is_gimple_call (ones)
2709       || !is_gimple_call (twos)
2710       || gimple_call_lhs (ones)
2711       || gimple_call_lhs (twos)
2712       || gimple_call_chain (ones)
2713       || gimple_call_chain (twos)
2714       || !operand_equal_p (gimple_call_fn (ones), gimple_call_fn (twos), 0)
2715       || gimple_call_num_args (ones) != gimple_call_num_args (twos))
2716     return false;
2717
2718   for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
2719     if (!operand_equal_p (gimple_call_arg (ones, ai),
2720                           gimple_call_arg (twos, ai), 0))
2721       return false;
2722
2723   return true;
2724 }
2725
2726 /* Optimize
2727     try { A() } finally { try { ~B() } catch { ~A() } }
2728     try { ... } finally { ~A() }
2729    into
2730     try { A() } catch { ~B() }
2731     try { ~B() ... } finally { ~A() }
2732
2733    This occurs frequently in C++, where A is a local variable and B is a
2734    temporary used in the initializer for A.  */
2735
2736 static void
2737 optimize_double_finally (gimple one, gimple two)
2738 {
2739   gimple oneh;
2740   gimple_stmt_iterator gsi;
2741
2742   gsi = gsi_start (gimple_try_cleanup (one));
2743   if (!gsi_one_before_end_p (gsi))
2744     return;
2745
2746   oneh = gsi_stmt (gsi);
2747   if (gimple_code (oneh) != GIMPLE_TRY
2748       || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
2749     return;
2750
2751   if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
2752     {
2753       gimple_seq seq = gimple_try_eval (oneh);
2754
2755       gimple_try_set_cleanup (one, seq);
2756       gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
2757       seq = copy_gimple_seq_and_replace_locals (seq);
2758       gimple_seq_add_seq (&seq, gimple_try_eval (two));
2759       gimple_try_set_eval (two, seq);
2760     }
2761 }
2762
2763 /* Perform EH refactoring optimizations that are simpler to do when code
2764    flow has been lowered but EH structures haven't.  */
2765
2766 static void
2767 refactor_eh_r (gimple_seq seq)
2768 {
2769   gimple_stmt_iterator gsi;
2770   gimple one, two;
2771
2772   one = NULL;
2773   two = NULL;
2774   gsi = gsi_start (seq);
2775   while (1)
2776     {
2777       one = two;
2778       if (gsi_end_p (gsi))
2779         two = NULL;
2780       else
2781         two = gsi_stmt (gsi);
2782       if (one
2783           && two
2784           && gimple_code (one) == GIMPLE_TRY
2785           && gimple_code (two) == GIMPLE_TRY
2786           && gimple_try_kind (one) == GIMPLE_TRY_FINALLY
2787           && gimple_try_kind (two) == GIMPLE_TRY_FINALLY)
2788         optimize_double_finally (one, two);
2789       if (one)
2790         switch (gimple_code (one))
2791           {
2792           case GIMPLE_TRY:
2793             refactor_eh_r (gimple_try_eval (one));
2794             refactor_eh_r (gimple_try_cleanup (one));
2795             break;
2796           case GIMPLE_CATCH:
2797             refactor_eh_r (gimple_catch_handler (one));
2798             break;
2799           case GIMPLE_EH_FILTER:
2800             refactor_eh_r (gimple_eh_filter_failure (one));
2801             break;
2802           default:
2803             break;
2804           }
2805       if (two)
2806         gsi_next (&gsi);
2807       else
2808         break;
2809     }
2810 }
2811
2812 static unsigned
2813 refactor_eh (void)
2814 {
2815   refactor_eh_r (gimple_body (current_function_decl));
2816   return 0;
2817 }
2818
2819 static bool
2820 gate_refactor_eh (void)
2821 {
2822   return flag_exceptions != 0;
2823 }
2824
2825 struct gimple_opt_pass pass_refactor_eh =
2826 {
2827  {
2828   GIMPLE_PASS,
2829   "ehopt",                              /* name */
2830   gate_refactor_eh,                     /* gate */
2831   refactor_eh,                          /* execute */
2832   NULL,                                 /* sub */
2833   NULL,                                 /* next */
2834   0,                                    /* static_pass_number */
2835   TV_TREE_EH,                           /* tv_id */
2836   PROP_gimple_lcf,                      /* properties_required */
2837   0,                                    /* properties_provided */
2838   0,                                    /* properties_destroyed */
2839   0,                                    /* todo_flags_start */
2840   TODO_dump_func                        /* todo_flags_finish */
2841  }
2842 };
2843 \f
2844 /* At the end of gimple optimization, we can lower RESX.  */
2845
2846 static bool
2847 lower_resx (basic_block bb, gimple stmt, struct pointer_map_t *mnt_map)
2848 {
2849   int lp_nr;
2850   eh_region src_r, dst_r;
2851   gimple_stmt_iterator gsi;
2852   gimple x;
2853   tree fn, src_nr;
2854   bool ret = false;
2855
2856   lp_nr = lookup_stmt_eh_lp (stmt);
2857   if (lp_nr != 0)
2858     dst_r = get_eh_region_from_lp_number (lp_nr);
2859   else
2860     dst_r = NULL;
2861
2862   src_r = get_eh_region_from_number (gimple_resx_region (stmt));
2863   gsi = gsi_last_bb (bb);
2864
2865   if (src_r == NULL)
2866     {
2867       /* We can wind up with no source region when pass_cleanup_eh shows
2868          that there are no entries into an eh region and deletes it, but
2869          then the block that contains the resx isn't removed.  This can
2870          happen without optimization when the switch statement created by
2871          lower_try_finally_switch isn't simplified to remove the eh case.
2872
2873          Resolve this by expanding the resx node to an abort.  */
2874
2875       fn = implicit_built_in_decls[BUILT_IN_TRAP];
2876       x = gimple_build_call (fn, 0);
2877       gsi_insert_before (&gsi, x, GSI_SAME_STMT);
2878
2879       while (EDGE_COUNT (bb->succs) > 0)
2880         remove_edge (EDGE_SUCC (bb, 0));
2881     }
2882   else if (dst_r)
2883     {
2884       /* When we have a destination region, we resolve this by copying
2885          the excptr and filter values into place, and changing the edge
2886          to immediately after the landing pad.  */
2887       edge e;
2888
2889       if (lp_nr < 0)
2890         {
2891           basic_block new_bb;
2892           void **slot;
2893           tree lab;
2894
2895           /* We are resuming into a MUST_NOT_CALL region.  Expand a call to
2896              the failure decl into a new block, if needed.  */
2897           gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
2898
2899           slot = pointer_map_contains (mnt_map, dst_r);
2900           if (slot == NULL)
2901             {
2902               gimple_stmt_iterator gsi2;
2903
2904               new_bb = create_empty_bb (bb);
2905               lab = gimple_block_label (new_bb);
2906               gsi2 = gsi_start_bb (new_bb);
2907
2908               fn = dst_r->u.must_not_throw.failure_decl;
2909               x = gimple_build_call (fn, 0);
2910               gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
2911               gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
2912
2913               slot = pointer_map_insert (mnt_map, dst_r);
2914               *slot = lab;
2915             }
2916           else
2917             {
2918               lab = (tree) *slot;
2919               new_bb = label_to_block (lab);
2920             }
2921
2922           gcc_assert (EDGE_COUNT (bb->succs) == 0);
2923           e = make_edge (bb, new_bb, EDGE_FALLTHRU);
2924           e->count = bb->count;
2925           e->probability = REG_BR_PROB_BASE;
2926         }
2927       else
2928         {
2929           edge_iterator ei;
2930           tree dst_nr = build_int_cst (NULL, dst_r->index);
2931
2932           fn = implicit_built_in_decls[BUILT_IN_EH_COPY_VALUES];
2933           src_nr = build_int_cst (NULL, src_r->index);
2934           x = gimple_build_call (fn, 2, dst_nr, src_nr);
2935           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
2936
2937           /* Update the flags for the outgoing edge.  */
2938           e = single_succ_edge (bb);
2939           gcc_assert (e->flags & EDGE_EH);
2940           e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
2941
2942           /* If there are no more EH users of the landing pad, delete it.  */
2943           FOR_EACH_EDGE (e, ei, e->dest->preds)
2944             if (e->flags & EDGE_EH)
2945               break;
2946           if (e == NULL)
2947             {
2948               eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
2949               remove_eh_landing_pad (lp);
2950             }
2951         }
2952
2953       ret = true;
2954     }
2955   else
2956     {
2957       tree var;
2958
2959       /* When we don't have a destination region, this exception escapes
2960          up the call chain.  We resolve this by generating a call to the
2961          _Unwind_Resume library function.  */
2962
2963       /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
2964          with no arguments for C++ and Java.  Check for that.  */
2965       if (src_r->use_cxa_end_cleanup)
2966         {
2967           fn = implicit_built_in_decls[BUILT_IN_CXA_END_CLEANUP];
2968           x = gimple_build_call (fn, 0);
2969           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
2970         }
2971       else
2972         {
2973           fn = implicit_built_in_decls[BUILT_IN_EH_POINTER];
2974           src_nr = build_int_cst (NULL, src_r->index);
2975           x = gimple_build_call (fn, 1, src_nr);
2976           var = create_tmp_var (ptr_type_node, NULL);
2977           var = make_ssa_name (var, x);
2978           gimple_call_set_lhs (x, var);
2979           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
2980
2981           fn = implicit_built_in_decls[BUILT_IN_UNWIND_RESUME];
2982           x = gimple_build_call (fn, 1, var);
2983           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
2984         }
2985
2986       gcc_assert (EDGE_COUNT (bb->succs) == 0);
2987     }
2988
2989   gsi_remove (&gsi, true);
2990
2991   return ret;
2992 }
2993
2994 static unsigned
2995 execute_lower_resx (void)
2996 {
2997   basic_block bb;
2998   struct pointer_map_t *mnt_map;
2999   bool dominance_invalidated = false;
3000   bool any_rewritten = false;
3001
3002   mnt_map = pointer_map_create ();
3003
3004   FOR_EACH_BB (bb)
3005     {
3006       gimple last = last_stmt (bb);
3007       if (last && is_gimple_resx (last))
3008         {
3009           dominance_invalidated |= lower_resx (bb, last, mnt_map);
3010           any_rewritten = true;
3011         }
3012     }
3013
3014   pointer_map_destroy (mnt_map);
3015
3016   if (dominance_invalidated)
3017     {
3018       free_dominance_info (CDI_DOMINATORS);
3019       free_dominance_info (CDI_POST_DOMINATORS);
3020     }
3021
3022   return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3023 }
3024
3025 static bool
3026 gate_lower_resx (void)
3027 {
3028   return flag_exceptions != 0;
3029 }
3030
3031 struct gimple_opt_pass pass_lower_resx =
3032 {
3033  {
3034   GIMPLE_PASS,
3035   "resx",                               /* name */
3036   gate_lower_resx,                      /* gate */
3037   execute_lower_resx,                   /* execute */
3038   NULL,                                 /* sub */
3039   NULL,                                 /* next */
3040   0,                                    /* static_pass_number */
3041   TV_TREE_EH,                           /* tv_id */
3042   PROP_gimple_lcf,                      /* properties_required */
3043   0,                                    /* properties_provided */
3044   0,                                    /* properties_destroyed */
3045   0,                                    /* todo_flags_start */
3046   TODO_dump_func | TODO_verify_flow     /* todo_flags_finish */
3047  }
3048 };
3049
3050
3051 /* At the end of inlining, we can lower EH_DISPATCH.  */
3052
3053 static void
3054 lower_eh_dispatch (basic_block src, gimple stmt)
3055 {
3056   gimple_stmt_iterator gsi;
3057   int region_nr;
3058   eh_region r;
3059   tree filter, fn;
3060   gimple x;
3061
3062   region_nr = gimple_eh_dispatch_region (stmt);
3063   r = get_eh_region_from_number (region_nr);
3064
3065   gsi = gsi_last_bb (src);
3066
3067   switch (r->type)
3068     {
3069     case ERT_TRY:
3070       {
3071         VEC (tree, heap) *labels = NULL;
3072         tree default_label = NULL;
3073         eh_catch c;
3074         edge_iterator ei;
3075         edge e;
3076
3077         /* Collect the labels for a switch.  Zero the post_landing_pad
3078            field becase we'll no longer have anything keeping these labels
3079            in existance and the optimizer will be free to merge these
3080            blocks at will.  */
3081         for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3082           {
3083             tree tp_node, flt_node, lab = c->label;
3084
3085             c->label = NULL;
3086             tp_node = c->type_list;
3087             flt_node = c->filter_list;
3088
3089             if (tp_node == NULL)
3090               {
3091                 default_label = lab;
3092                 break;
3093               }
3094             do
3095               {
3096                 tree t = build3 (CASE_LABEL_EXPR, void_type_node,
3097                                  TREE_VALUE (flt_node), NULL, lab);
3098                 VEC_safe_push (tree, heap, labels, t);
3099
3100                 tp_node = TREE_CHAIN (tp_node);
3101                 flt_node = TREE_CHAIN (flt_node);
3102               }
3103             while (tp_node);
3104           }
3105
3106         /* Clean up the edge flags.  */
3107         FOR_EACH_EDGE (e, ei, src->succs)
3108           {
3109             if (e->flags & EDGE_FALLTHRU)
3110               {
3111                 /* If there was no catch-all, use the fallthru edge.  */
3112                 if (default_label == NULL)
3113                   default_label = gimple_block_label (e->dest);
3114                 e->flags &= ~EDGE_FALLTHRU;
3115               }
3116           }
3117         gcc_assert (default_label != NULL);
3118
3119         /* Don't generate a switch if there's only a default case.
3120            This is common in the form of try { A; } catch (...) { B; }.  */
3121         if (labels == NULL)
3122           {
3123             e = single_succ_edge (src);
3124             e->flags |= EDGE_FALLTHRU;
3125           }
3126         else
3127           {
3128             fn = implicit_built_in_decls[BUILT_IN_EH_FILTER];
3129             x = gimple_build_call (fn, 1, build_int_cst (NULL, region_nr));
3130             filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)), NULL);
3131             filter = make_ssa_name (filter, x);
3132             gimple_call_set_lhs (x, filter);
3133             gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3134
3135             /* Turn the default label into a default case.  */
3136             default_label = build3 (CASE_LABEL_EXPR, void_type_node,
3137                                     NULL, NULL, default_label);
3138             sort_case_labels (labels);
3139
3140             x = gimple_build_switch_vec (filter, default_label, labels);
3141             gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3142
3143             VEC_free (tree, heap, labels);
3144           }
3145       }
3146       break;
3147
3148     case ERT_ALLOWED_EXCEPTIONS:
3149       {
3150         edge b_e = BRANCH_EDGE (src);
3151         edge f_e = FALLTHRU_EDGE (src);
3152
3153         fn = implicit_built_in_decls[BUILT_IN_EH_FILTER];
3154         x = gimple_build_call (fn, 1, build_int_cst (NULL, region_nr));
3155         filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)), NULL);
3156         filter = make_ssa_name (filter, x);
3157         gimple_call_set_lhs (x, filter);
3158         gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3159
3160         r->u.allowed.label = NULL;
3161         x = gimple_build_cond (EQ_EXPR, filter,
3162                                build_int_cst (TREE_TYPE (filter),
3163                                               r->u.allowed.filter),
3164                                NULL_TREE, NULL_TREE);
3165         gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3166
3167         b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3168         f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3169       }
3170       break;
3171
3172     default:
3173       gcc_unreachable ();
3174     }
3175
3176   /* Replace the EH_DISPATCH with the SWITCH or COND generated above.  */
3177   gsi_remove (&gsi, true);
3178 }
3179
3180 static unsigned
3181 execute_lower_eh_dispatch (void)
3182 {
3183   basic_block bb;
3184   bool any_rewritten = false;
3185
3186   assign_filter_values ();
3187
3188   FOR_EACH_BB (bb)
3189     {
3190       gimple last = last_stmt (bb);
3191       if (last && gimple_code (last) == GIMPLE_EH_DISPATCH)
3192         {
3193           lower_eh_dispatch (bb, last);
3194           any_rewritten = true;
3195         }
3196     }
3197
3198   return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3199 }
3200
3201 static bool
3202 gate_lower_eh_dispatch (void)
3203 {
3204   return cfun->eh->region_tree != NULL;
3205 }
3206
3207 struct gimple_opt_pass pass_lower_eh_dispatch =
3208 {
3209  {
3210   GIMPLE_PASS,
3211   "ehdisp",                             /* name */
3212   gate_lower_eh_dispatch,               /* gate */
3213   execute_lower_eh_dispatch,            /* execute */
3214   NULL,                                 /* sub */
3215   NULL,                                 /* next */
3216   0,                                    /* static_pass_number */
3217   TV_TREE_EH,                           /* tv_id */
3218   PROP_gimple_lcf,                      /* properties_required */
3219   0,                                    /* properties_provided */
3220   0,                                    /* properties_destroyed */
3221   0,                                    /* todo_flags_start */
3222   TODO_dump_func | TODO_verify_flow     /* todo_flags_finish */
3223  }
3224 };
3225 \f
3226 /* Walk statements, see what regions are really referenced and remove
3227    those that are unused.  */
3228
3229 static void
3230 remove_unreachable_handlers (void)
3231 {
3232   sbitmap r_reachable, lp_reachable;
3233   eh_region region;
3234   eh_landing_pad lp;
3235   basic_block bb;
3236   int lp_nr, r_nr;
3237
3238   r_reachable = sbitmap_alloc (VEC_length (eh_region, cfun->eh->region_array));
3239   lp_reachable
3240     = sbitmap_alloc (VEC_length (eh_landing_pad, cfun->eh->lp_array));
3241   sbitmap_zero (r_reachable);
3242   sbitmap_zero (lp_reachable);
3243
3244   FOR_EACH_BB (bb)
3245     {
3246       gimple_stmt_iterator gsi = gsi_start_bb (bb);
3247
3248       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3249         {
3250           gimple stmt = gsi_stmt (gsi);
3251           lp_nr = lookup_stmt_eh_lp (stmt);
3252
3253           /* Negative LP numbers are MUST_NOT_THROW regions which
3254              are not considered BB enders.  */
3255           if (lp_nr < 0)
3256             SET_BIT (r_reachable, -lp_nr);
3257
3258           /* Positive LP numbers are real landing pads, are are BB enders.  */
3259           else if (lp_nr > 0)
3260             {
3261               gcc_assert (gsi_one_before_end_p (gsi));
3262               region = get_eh_region_from_lp_number (lp_nr);
3263               SET_BIT (r_reachable, region->index);
3264               SET_BIT (lp_reachable, lp_nr);
3265             }
3266         }
3267     }
3268
3269   if (dump_file)
3270     {
3271       fprintf (dump_file, "Before removal of unreachable regions:\n");
3272       dump_eh_tree (dump_file, cfun);
3273       fprintf (dump_file, "Reachable regions: ");
3274       dump_sbitmap_file (dump_file, r_reachable);
3275       fprintf (dump_file, "Reachable landing pads: ");
3276       dump_sbitmap_file (dump_file, lp_reachable);
3277     }
3278
3279   for (r_nr = 1;
3280        VEC_iterate (eh_region, cfun->eh->region_array, r_nr, region); ++r_nr)
3281     if (region && !TEST_BIT (r_reachable, r_nr))
3282       {
3283         if (dump_file)
3284           fprintf (dump_file, "Removing unreachable region %d\n", r_nr);
3285         remove_eh_handler (region);
3286       }
3287
3288   for (lp_nr = 1;
3289        VEC_iterate (eh_landing_pad, cfun->eh->lp_array, lp_nr, lp); ++lp_nr)
3290     if (lp && !TEST_BIT (lp_reachable, lp_nr))
3291       {
3292         if (dump_file)
3293           fprintf (dump_file, "Removing unreachable landing pad %d\n", lp_nr);
3294         remove_eh_landing_pad (lp);
3295       }
3296     
3297   if (dump_file)
3298     {
3299       fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3300       dump_eh_tree (dump_file, cfun);
3301       fprintf (dump_file, "\n\n");
3302     }
3303
3304   sbitmap_free (r_reachable);
3305   sbitmap_free (lp_reachable);
3306
3307 #ifdef ENABLE_CHECKING
3308   verify_eh_tree (cfun);
3309 #endif
3310 }
3311
3312 /* Remove regions that do not have landing pads.  This assumes
3313    that remove_unreachable_handlers has already been run, and
3314    that we've just manipulated the landing pads since then.  */
3315
3316 static void
3317 remove_unreachable_handlers_no_lp (void)
3318 {
3319   eh_region r;
3320   int i;
3321
3322   for (i = 1; VEC_iterate (eh_region, cfun->eh->region_array, i, r); ++i)
3323     if (r && r->landing_pads == NULL && r->type != ERT_MUST_NOT_THROW)
3324       {
3325         if (dump_file)
3326           fprintf (dump_file, "Removing unreachable region %d\n", i);
3327         remove_eh_handler (r);
3328       }
3329 }
3330
3331 /* Undo critical edge splitting on an EH landing pad.  Earlier, we
3332    optimisticaly split all sorts of edges, including EH edges.  The
3333    optimization passes in between may not have needed them; if not,
3334    we should undo the split.
3335
3336    Recognize this case by having one EH edge incoming to the BB and
3337    one normal edge outgoing; BB should be empty apart from the
3338    post_landing_pad label.
3339
3340    Note that this is slightly different from the empty handler case
3341    handled by cleanup_empty_eh, in that the actual handler may yet
3342    have actual code but the landing pad has been separated from the
3343    handler.  As such, cleanup_empty_eh relies on this transformation
3344    having been done first.  */
3345
3346 static bool
3347 unsplit_eh (eh_landing_pad lp)
3348 {
3349   basic_block bb = label_to_block (lp->post_landing_pad);
3350   gimple_stmt_iterator gsi;
3351   edge e_in, e_out;
3352
3353   /* Quickly check the edge counts on BB for singularity.  */
3354   if (EDGE_COUNT (bb->preds) != 1 || EDGE_COUNT (bb->succs) != 1)
3355     return false;
3356   e_in = EDGE_PRED (bb, 0);
3357   e_out = EDGE_SUCC (bb, 0);
3358
3359   /* Input edge must be EH and output edge must be normal.  */
3360   if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
3361     return false;
3362
3363   /* The block must be empty except for the labels.  */
3364   if (!gsi_end_p (gsi_after_labels (bb)))
3365     return false;
3366
3367   /* The destination block must not already have a landing pad
3368      for a different region.  */
3369   for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
3370     {
3371       gimple stmt = gsi_stmt (gsi);
3372       tree lab;
3373       int lp_nr;
3374
3375       if (gimple_code (stmt) != GIMPLE_LABEL)
3376         break;
3377       lab = gimple_label_label (stmt);
3378       lp_nr = EH_LANDING_PAD_NR (lab);
3379       if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
3380         return false;
3381     }
3382
3383   /* The new destination block must not already be a destination of
3384      the source block, lest we merge fallthru and eh edges and get
3385      all sorts of confused.  */
3386   if (find_edge (e_in->src, e_out->dest))
3387     return false;
3388
3389   /* ??? We can get degenerate phis due to cfg cleanups.  I would have
3390      thought this should have been cleaned up by a phicprop pass, but
3391      that doesn't appear to handle virtuals.  Propagate by hand.  */
3392   if (!gimple_seq_empty_p (phi_nodes (bb)))
3393     {
3394       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); )
3395         {
3396           gimple use_stmt, phi = gsi_stmt (gsi);
3397           tree lhs = gimple_phi_result (phi);
3398           tree rhs = gimple_phi_arg_def (phi, 0);
3399           use_operand_p use_p;
3400           imm_use_iterator iter;
3401
3402           FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
3403             {
3404               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3405                 SET_USE (use_p, rhs);
3406             }
3407
3408           if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
3409             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
3410
3411           remove_phi_node (&gsi, true);
3412         }
3413     }
3414
3415   if (dump_file && (dump_flags & TDF_DETAILS))
3416     fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
3417              lp->index, e_out->dest->index);
3418
3419   /* Redirect the edge.  Since redirect_eh_edge_1 expects to be moving
3420      a successor edge, humor it.  But do the real CFG change with the
3421      predecessor of E_OUT in order to preserve the ordering of arguments
3422      to the PHI nodes in E_OUT->DEST.  */
3423   redirect_eh_edge_1 (e_in, e_out->dest, false);
3424   redirect_edge_pred (e_out, e_in->src);
3425   e_out->flags = e_in->flags;
3426   e_out->probability = e_in->probability;
3427   e_out->count = e_in->count;
3428   remove_edge (e_in);
3429
3430   return true;
3431 }
3432
3433 /* Examine each landing pad block and see if it matches unsplit_eh.  */
3434
3435 static bool
3436 unsplit_all_eh (void)
3437 {
3438   bool changed = false;
3439   eh_landing_pad lp;
3440   int i;
3441
3442   for (i = 1; VEC_iterate (eh_landing_pad, cfun->eh->lp_array, i, lp); ++i)
3443     if (lp)
3444       changed |= unsplit_eh (lp);
3445
3446   return changed;
3447 }
3448
3449 /* A subroutine of cleanup_empty_eh.  Redirect all EH edges incoming
3450    to OLD_BB to NEW_BB; return true on success, false on failure.
3451
3452    OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
3453    PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
3454    Virtual PHIs may be deleted and marked for renaming.  */
3455
3456 static bool
3457 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
3458                              edge old_bb_out, bool change_region)
3459 {
3460   gimple_stmt_iterator ngsi, ogsi;
3461   edge_iterator ei;
3462   edge e;
3463   bitmap rename_virts;
3464   bitmap ophi_handled;
3465
3466   FOR_EACH_EDGE (e, ei, old_bb->preds)
3467     redirect_edge_var_map_clear (e);
3468
3469   ophi_handled = BITMAP_ALLOC (NULL);
3470   rename_virts = BITMAP_ALLOC (NULL);
3471
3472   /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
3473      for the edges we're going to move.  */
3474   for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
3475     {
3476       gimple ophi, nphi = gsi_stmt (ngsi);
3477       tree nresult, nop;
3478
3479       nresult = gimple_phi_result (nphi);
3480       nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
3481
3482       /* Find the corresponding PHI in OLD_BB so we can forward-propagate
3483          the source ssa_name.  */
3484       ophi = NULL;
3485       for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
3486         {
3487           ophi = gsi_stmt (ogsi);
3488           if (gimple_phi_result (ophi) == nop)
3489             break;
3490           ophi = NULL;
3491         }
3492
3493       /* If we did find the corresponding PHI, copy those inputs.  */
3494       if (ophi)
3495         {
3496           bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
3497           FOR_EACH_EDGE (e, ei, old_bb->preds)
3498             {
3499               location_t oloc;
3500               tree oop;
3501
3502               if ((e->flags & EDGE_EH) == 0)
3503                 continue;
3504               oop = gimple_phi_arg_def (ophi, e->dest_idx);
3505               oloc = gimple_phi_arg_location (ophi, e->dest_idx);
3506               redirect_edge_var_map_add (e, nresult, oop, oloc);
3507             }
3508         }
3509       /* If we didn't find the PHI, but it's a VOP, remember to rename
3510          it later, assuming all other tests succeed.  */
3511       else if (!is_gimple_reg (nresult))
3512         bitmap_set_bit (rename_virts, SSA_NAME_VERSION (nresult));
3513       /* If we didn't find the PHI, and it's a real variable, we know
3514          from the fact that OLD_BB is tree_empty_eh_handler_p that the
3515          variable is unchanged from input to the block and we can simply
3516          re-use the input to NEW_BB from the OLD_BB_OUT edge.  */
3517       else
3518         {
3519           location_t nloc
3520             = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
3521           FOR_EACH_EDGE (e, ei, old_bb->preds)
3522             redirect_edge_var_map_add (e, nresult, nop, nloc);
3523         }
3524     }
3525
3526   /* Second, verify that all PHIs from OLD_BB have been handled.  If not,
3527      we don't know what values from the other edges into NEW_BB to use.  */
3528   for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
3529     {
3530       gimple ophi = gsi_stmt (ogsi);
3531       tree oresult = gimple_phi_result (ophi);
3532       if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
3533         goto fail;
3534     }
3535
3536   /* At this point we know that the merge will succeed.  Remove the PHI
3537      nodes for the virtuals that we want to rename.  */
3538   if (!bitmap_empty_p (rename_virts))
3539     {
3540       for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); )
3541         {
3542           gimple nphi = gsi_stmt (ngsi);
3543           tree nresult = gimple_phi_result (nphi);
3544           if (bitmap_bit_p (rename_virts, SSA_NAME_VERSION (nresult)))
3545             {
3546               mark_virtual_phi_result_for_renaming (nphi);
3547               remove_phi_node (&ngsi, true);
3548             }
3549           else
3550             gsi_next (&ngsi);
3551         }
3552     }
3553
3554   /* Finally, move the edges and update the PHIs.  */
3555   for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
3556     if (e->flags & EDGE_EH)
3557       {
3558         redirect_eh_edge_1 (e, new_bb, change_region);
3559         redirect_edge_succ (e, new_bb);
3560         flush_pending_stmts (e);
3561       }
3562     else
3563       ei_next (&ei);
3564
3565   BITMAP_FREE (ophi_handled);
3566   BITMAP_FREE (rename_virts);
3567   return true;
3568
3569  fail:
3570   FOR_EACH_EDGE (e, ei, old_bb->preds)
3571     redirect_edge_var_map_clear (e);
3572   BITMAP_FREE (ophi_handled);
3573   BITMAP_FREE (rename_virts);
3574   return false;
3575 }
3576
3577 /* A subroutine of cleanup_empty_eh.  Move a landing pad LP from its
3578    old region to NEW_REGION at BB.  */
3579
3580 static void
3581 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
3582                           eh_landing_pad lp, eh_region new_region)
3583 {
3584   gimple_stmt_iterator gsi;
3585   eh_landing_pad *pp;
3586
3587   for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
3588     continue;
3589   *pp = lp->next_lp;
3590
3591   lp->region = new_region;
3592   lp->next_lp = new_region->landing_pads;
3593   new_region->landing_pads = lp;
3594
3595   /* Delete the RESX that was matched within the empty handler block.  */
3596   gsi = gsi_last_bb (bb);
3597   mark_virtual_ops_for_renaming (gsi_stmt (gsi));
3598   gsi_remove (&gsi, true);
3599
3600   /* Clean up E_OUT for the fallthru.  */
3601   e_out->flags = (e_out->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3602   e_out->probability = REG_BR_PROB_BASE;
3603 }
3604
3605 /* A subroutine of cleanup_empty_eh.  Handle more complex cases of
3606    unsplitting than unsplit_eh was prepared to handle, e.g. when 
3607    multiple incoming edges and phis are involved.  */
3608
3609 static bool
3610 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
3611 {
3612   gimple_stmt_iterator gsi;
3613   tree lab;
3614
3615   /* We really ought not have totally lost everything following
3616      a landing pad label.  Given that BB is empty, there had better
3617      be a successor.  */
3618   gcc_assert (e_out != NULL);
3619
3620   /* The destination block must not already have a landing pad
3621      for a different region.  */
3622   lab = NULL;
3623   for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
3624     {
3625       gimple stmt = gsi_stmt (gsi);
3626       int lp_nr;
3627
3628       if (gimple_code (stmt) != GIMPLE_LABEL)
3629         break;
3630       lab = gimple_label_label (stmt);
3631       lp_nr = EH_LANDING_PAD_NR (lab);
3632       if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
3633         return false;
3634     }
3635
3636   /* Attempt to move the PHIs into the successor block.  */
3637   if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
3638     {
3639       if (dump_file && (dump_flags & TDF_DETAILS))
3640         fprintf (dump_file,
3641                  "Unsplit EH landing pad %d to block %i "
3642                  "(via cleanup_empty_eh).\n",
3643                  lp->index, e_out->dest->index);
3644       return true;
3645     }
3646
3647   return false;
3648 }
3649
3650 /* Examine the block associated with LP to determine if it's an empty
3651    handler for its EH region.  If so, attempt to redirect EH edges to
3652    an outer region.  Return true the CFG was updated in any way.  This
3653    is similar to jump forwarding, just across EH edges.  */
3654
3655 static bool
3656 cleanup_empty_eh (eh_landing_pad lp)
3657 {
3658   basic_block bb = label_to_block (lp->post_landing_pad);
3659   gimple_stmt_iterator gsi;
3660   gimple resx;
3661   eh_region new_region;
3662   edge_iterator ei;
3663   edge e, e_out;
3664   bool has_non_eh_pred;
3665   int new_lp_nr;
3666
3667   /* There can be zero or one edges out of BB.  This is the quickest test.  */
3668   switch (EDGE_COUNT (bb->succs))
3669     {
3670     case 0:
3671       e_out = NULL;
3672       break;
3673     case 1:
3674       e_out = EDGE_SUCC (bb, 0);
3675       break;
3676     default:
3677       return false;
3678     }
3679   gsi = gsi_after_labels (bb);
3680
3681   /* Make sure to skip debug statements.  */
3682   if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
3683     gsi_next_nondebug (&gsi);
3684
3685   /* If the block is totally empty, look for more unsplitting cases.  */
3686   if (gsi_end_p (gsi))
3687     return cleanup_empty_eh_unsplit (bb, e_out, lp);
3688
3689   /* The block should consist only of a single RESX statement.  */
3690   resx = gsi_stmt (gsi);
3691   if (!is_gimple_resx (resx))
3692     return false;
3693   gcc_assert (gsi_one_before_end_p (gsi));
3694
3695   /* Determine if there are non-EH edges, or resx edges into the handler.  */
3696   has_non_eh_pred = false;
3697   FOR_EACH_EDGE (e, ei, bb->preds)
3698     if (!(e->flags & EDGE_EH))
3699       has_non_eh_pred = true;
3700
3701   /* Find the handler that's outer of the empty handler by looking at
3702      where the RESX instruction was vectored.  */
3703   new_lp_nr = lookup_stmt_eh_lp (resx);
3704   new_region = get_eh_region_from_lp_number (new_lp_nr);
3705
3706   /* If there's no destination region within the current function,
3707      redirection is trivial via removing the throwing statements from
3708      the EH region, removing the EH edges, and allowing the block
3709      to go unreachable.  */
3710   if (new_region == NULL)
3711     {
3712       gcc_assert (e_out == NULL);
3713       for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
3714         if (e->flags & EDGE_EH)
3715           {
3716             gimple stmt = last_stmt (e->src);
3717             remove_stmt_from_eh_lp (stmt);
3718             remove_edge (e);
3719           }
3720         else
3721           ei_next (&ei);
3722       goto succeed;
3723     }
3724
3725   /* If the destination region is a MUST_NOT_THROW, allow the runtime
3726      to handle the abort and allow the blocks to go unreachable.  */
3727   if (new_region->type == ERT_MUST_NOT_THROW)
3728     {
3729       for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
3730         if (e->flags & EDGE_EH)
3731           {
3732             gimple stmt = last_stmt (e->src);
3733             remove_stmt_from_eh_lp (stmt);
3734             add_stmt_to_eh_lp (stmt, new_lp_nr);
3735             remove_edge (e);
3736           }
3737         else
3738           ei_next (&ei);
3739       goto succeed;
3740     }
3741
3742   /* Try to redirect the EH edges and merge the PHIs into the destination
3743      landing pad block.  If the merge succeeds, we'll already have redirected
3744      all the EH edges.  The handler itself will go unreachable if there were
3745      no normal edges.  */
3746   if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
3747     goto succeed;
3748
3749   /* Finally, if all input edges are EH edges, then we can (potentially)
3750      reduce the number of transfers from the runtime by moving the landing
3751      pad from the original region to the new region.  This is a win when
3752      we remove the last CLEANUP region along a particular exception
3753      propagation path.  Since nothing changes except for the region with
3754      which the landing pad is associated, the PHI nodes do not need to be
3755      adjusted at all.  */
3756   if (!has_non_eh_pred)
3757     {
3758       cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
3759       if (dump_file && (dump_flags & TDF_DETAILS))
3760         fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
3761                  lp->index, new_region->index);
3762
3763       /* ??? The CFG didn't change, but we may have rendered the
3764          old EH region unreachable.  Trigger a cleanup there.  */
3765       return true;
3766     }
3767
3768   return false;
3769
3770  succeed:
3771   if (dump_file && (dump_flags & TDF_DETAILS))
3772     fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
3773   remove_eh_landing_pad (lp);
3774   return true;
3775 }
3776
3777 /* Do a post-order traversal of the EH region tree.  Examine each
3778    post_landing_pad block and see if we can eliminate it as empty.  */
3779
3780 static bool
3781 cleanup_all_empty_eh (void)
3782 {
3783   bool changed = false;
3784   eh_landing_pad lp;
3785   int i;
3786
3787   for (i = 1; VEC_iterate (eh_landing_pad, cfun->eh->lp_array, i, lp); ++i)
3788     if (lp)
3789       changed |= cleanup_empty_eh (lp);
3790
3791   return changed;
3792 }
3793
3794 /* Perform cleanups and lowering of exception handling
3795     1) cleanups regions with handlers doing nothing are optimized out
3796     2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
3797     3) Info about regions that are containing instructions, and regions
3798        reachable via local EH edges is collected
3799     4) Eh tree is pruned for regions no longer neccesary.
3800
3801    TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
3802          Unify those that have the same failure decl and locus.
3803 */
3804
3805 static unsigned int
3806 execute_cleanup_eh (void)
3807 {
3808   /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
3809      looking up unreachable landing pads.  */
3810   remove_unreachable_handlers ();
3811
3812   /* Watch out for the region tree vanishing due to all unreachable.  */
3813   if (cfun->eh->region_tree && optimize)
3814     {
3815       bool changed = false;
3816
3817       changed |= unsplit_all_eh ();
3818       changed |= cleanup_all_empty_eh ();
3819
3820       if (changed)
3821         {
3822           free_dominance_info (CDI_DOMINATORS);
3823           free_dominance_info (CDI_POST_DOMINATORS);
3824
3825           /* We delayed all basic block deletion, as we may have performed
3826              cleanups on EH edges while non-EH edges were still present.  */
3827           delete_unreachable_blocks ();
3828
3829           /* We manipulated the landing pads.  Remove any region that no
3830              longer has a landing pad.  */
3831           remove_unreachable_handlers_no_lp ();
3832
3833           return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
3834         }
3835     }
3836
3837   return 0;
3838 }
3839
3840 static bool
3841 gate_cleanup_eh (void)
3842 {
3843   return cfun->eh != NULL && cfun->eh->region_tree != NULL;
3844 }
3845
3846 struct gimple_opt_pass pass_cleanup_eh = {
3847   {
3848    GIMPLE_PASS,
3849    "ehcleanup",                 /* name */
3850    gate_cleanup_eh,             /* gate */
3851    execute_cleanup_eh,          /* execute */
3852    NULL,                        /* sub */
3853    NULL,                        /* next */
3854    0,                           /* static_pass_number */
3855    TV_TREE_EH,                  /* tv_id */
3856    PROP_gimple_lcf,             /* properties_required */
3857    0,                           /* properties_provided */
3858    0,                           /* properties_destroyed */
3859    0,                           /* todo_flags_start */
3860    TODO_dump_func               /* todo_flags_finish */
3861    }
3862 };
3863 \f
3864 /* Verify that BB containing STMT as the last statement, has precisely the
3865    edge that make_eh_edges would create.  */
3866
3867 bool
3868 verify_eh_edges (gimple stmt)
3869 {
3870   basic_block bb = gimple_bb (stmt);
3871   eh_landing_pad lp = NULL;
3872   int lp_nr;
3873   edge_iterator ei;
3874   edge e, eh_edge;
3875
3876   lp_nr = lookup_stmt_eh_lp (stmt);
3877   if (lp_nr > 0)
3878     lp = get_eh_landing_pad_from_number (lp_nr);
3879
3880   eh_edge = NULL;
3881   FOR_EACH_EDGE (e, ei, bb->succs)
3882     {
3883       if (e->flags & EDGE_EH)
3884         {
3885           if (eh_edge)
3886             {
3887               error ("BB %i has multiple EH edges", bb->index);
3888               return true;
3889             }
3890           else
3891             eh_edge = e;
3892         }
3893     }
3894
3895   if (lp == NULL)
3896     {
3897       if (eh_edge)
3898         {
3899           error ("BB %i can not throw but has an EH edge", bb->index);
3900           return true;
3901         }
3902       return false;
3903     }
3904
3905   if (!stmt_could_throw_p (stmt))
3906     {
3907       error ("BB %i last statement has incorrectly set lp", bb->index);
3908       return true;
3909     }
3910
3911   if (eh_edge == NULL)
3912     {
3913       error ("BB %i is missing an EH edge", bb->index);
3914       return true;
3915     }
3916
3917   if (eh_edge->dest != label_to_block (lp->post_landing_pad))
3918     {
3919       error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
3920       return true;
3921     }
3922
3923   return false;
3924 }
3925
3926 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically.  */
3927
3928 bool
3929 verify_eh_dispatch_edge (gimple stmt)
3930 {
3931   eh_region r;
3932   eh_catch c;
3933   basic_block src, dst;
3934   bool want_fallthru = true;
3935   edge_iterator ei;
3936   edge e, fall_edge;
3937
3938   r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
3939   src = gimple_bb (stmt);
3940
3941   FOR_EACH_EDGE (e, ei, src->succs)
3942     gcc_assert (e->aux == NULL);
3943
3944   switch (r->type)
3945     {
3946     case ERT_TRY:
3947       for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3948         {
3949           dst = label_to_block (c->label);
3950           e = find_edge (src, dst);
3951           if (e == NULL)
3952             {
3953               error ("BB %i is missing an edge", src->index);
3954               return true;
3955             }
3956           e->aux = (void *)e;
3957
3958           /* A catch-all handler doesn't have a fallthru.  */
3959           if (c->type_list == NULL)
3960             {
3961               want_fallthru = false;
3962               break;
3963             }
3964         }
3965       break;
3966
3967     case ERT_ALLOWED_EXCEPTIONS:
3968       dst = label_to_block (r->u.allowed.label);
3969       e = find_edge (src, dst);
3970       if (e == NULL)
3971         {
3972           error ("BB %i is missing an edge", src->index);
3973           return true;
3974         }
3975       e->aux = (void *)e;
3976       break;
3977
3978     default:
3979       gcc_unreachable ();
3980     }
3981
3982   fall_edge = NULL;
3983   FOR_EACH_EDGE (e, ei, src->succs)
3984     {
3985       if (e->flags & EDGE_FALLTHRU)
3986         {
3987           if (fall_edge != NULL)
3988             {
3989               error ("BB %i too many fallthru edges", src->index);
3990               return true;
3991             }
3992           fall_edge = e;
3993         }
3994       else if (e->aux)
3995         e->aux = NULL;
3996       else
3997         {
3998           error ("BB %i has incorrect edge", src->index);
3999           return true;
4000         }
4001     }
4002   if ((fall_edge != NULL) ^ want_fallthru)
4003     {
4004       error ("BB %i has incorrect fallthru edge", src->index);
4005       return true;
4006     }
4007
4008   return false;
4009 }