2013-11-21 Edward Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / gcc / tree-eh.c
blob7778678758583eadf2a647b6c04ce0e8e6b7f278
1 /* Exception handling semantics and decomposition for trees.
2 Copyright (C) 2003-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "hash-table.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "expr.h"
27 #include "calls.h"
28 #include "flags.h"
29 #include "function.h"
30 #include "except.h"
31 #include "pointer-set.h"
32 #include "gimple.h"
33 #include "gimple-iterator.h"
34 #include "gimple-ssa.h"
35 #include "cgraph.h"
36 #include "tree-cfg.h"
37 #include "tree-phinodes.h"
38 #include "ssa-iterators.h"
39 #include "stringpool.h"
40 #include "tree-ssanames.h"
41 #include "tree-into-ssa.h"
42 #include "tree-ssa.h"
43 #include "tree-inline.h"
44 #include "tree-pass.h"
45 #include "langhooks.h"
46 #include "ggc.h"
47 #include "diagnostic-core.h"
48 #include "target.h"
49 #include "cfgloop.h"
50 #include "gimple-low.h"
52 /* In some instances a tree and a gimple need to be stored in a same table,
53 i.e. in hash tables. This is a structure to do this. */
54 typedef union {tree *tp; tree t; gimple g;} treemple;
56 /* Misc functions used in this file. */
58 /* Remember and lookup EH landing pad data for arbitrary statements.
59 Really this means any statement that could_throw_p. We could
60 stuff this information into the stmt_ann data structure, but:
62 (1) We absolutely rely on this information being kept until
63 we get to rtl. Once we're done with lowering here, if we lose
64 the information there's no way to recover it!
66 (2) There are many more statements that *cannot* throw as
67 compared to those that can. We should be saving some amount
68 of space by only allocating memory for those that can throw. */
70 /* Add statement T in function IFUN to landing pad NUM. */
72 static void
73 add_stmt_to_eh_lp_fn (struct function *ifun, gimple t, int num)
75 struct throw_stmt_node *n;
76 void **slot;
78 gcc_assert (num != 0);
80 n = ggc_alloc_throw_stmt_node ();
81 n->stmt = t;
82 n->lp_nr = num;
84 if (!get_eh_throw_stmt_table (ifun))
85 set_eh_throw_stmt_table (ifun, htab_create_ggc (31, struct_ptr_hash,
86 struct_ptr_eq,
87 ggc_free));
89 slot = htab_find_slot (get_eh_throw_stmt_table (ifun), n, INSERT);
90 gcc_assert (!*slot);
91 *slot = n;
94 /* Add statement T in the current function (cfun) to EH landing pad NUM. */
96 void
97 add_stmt_to_eh_lp (gimple t, int num)
99 add_stmt_to_eh_lp_fn (cfun, t, num);
102 /* Add statement T to the single EH landing pad in REGION. */
104 static void
105 record_stmt_eh_region (eh_region region, gimple t)
107 if (region == NULL)
108 return;
109 if (region->type == ERT_MUST_NOT_THROW)
110 add_stmt_to_eh_lp_fn (cfun, t, -region->index);
111 else
113 eh_landing_pad lp = region->landing_pads;
114 if (lp == NULL)
115 lp = gen_eh_landing_pad (region);
116 else
117 gcc_assert (lp->next_lp == NULL);
118 add_stmt_to_eh_lp_fn (cfun, t, lp->index);
123 /* Remove statement T in function IFUN from its EH landing pad. */
125 bool
126 remove_stmt_from_eh_lp_fn (struct function *ifun, gimple t)
128 struct throw_stmt_node dummy;
129 void **slot;
131 if (!get_eh_throw_stmt_table (ifun))
132 return false;
134 dummy.stmt = t;
135 slot = htab_find_slot (get_eh_throw_stmt_table (ifun), &dummy,
136 NO_INSERT);
137 if (slot)
139 htab_clear_slot (get_eh_throw_stmt_table (ifun), slot);
140 return true;
142 else
143 return false;
147 /* Remove statement T in the current function (cfun) from its
148 EH landing pad. */
150 bool
151 remove_stmt_from_eh_lp (gimple t)
153 return remove_stmt_from_eh_lp_fn (cfun, t);
156 /* Determine if statement T is inside an EH region in function IFUN.
157 Positive numbers indicate a landing pad index; negative numbers
158 indicate a MUST_NOT_THROW region index; zero indicates that the
159 statement is not recorded in the region table. */
162 lookup_stmt_eh_lp_fn (struct function *ifun, gimple t)
164 struct throw_stmt_node *p, n;
166 if (ifun->eh->throw_stmt_table == NULL)
167 return 0;
169 n.stmt = t;
170 p = (struct throw_stmt_node *) htab_find (ifun->eh->throw_stmt_table, &n);
171 return p ? p->lp_nr : 0;
174 /* Likewise, but always use the current function. */
177 lookup_stmt_eh_lp (gimple t)
179 /* We can get called from initialized data when -fnon-call-exceptions
180 is on; prevent crash. */
181 if (!cfun)
182 return 0;
183 return lookup_stmt_eh_lp_fn (cfun, t);
186 /* First pass of EH node decomposition. Build up a tree of GIMPLE_TRY_FINALLY
187 nodes and LABEL_DECL nodes. We will use this during the second phase to
188 determine if a goto leaves the body of a TRY_FINALLY_EXPR node. */
190 struct finally_tree_node
192 /* When storing a GIMPLE_TRY, we have to record a gimple. However
193 when deciding whether a GOTO to a certain LABEL_DECL (which is a
194 tree) leaves the TRY block, its necessary to record a tree in
195 this field. Thus a treemple is used. */
196 treemple child;
197 gimple parent;
200 /* Hashtable helpers. */
202 struct finally_tree_hasher : typed_free_remove <finally_tree_node>
204 typedef finally_tree_node value_type;
205 typedef finally_tree_node compare_type;
206 static inline hashval_t hash (const value_type *);
207 static inline bool equal (const value_type *, const compare_type *);
210 inline hashval_t
211 finally_tree_hasher::hash (const value_type *v)
213 return (intptr_t)v->child.t >> 4;
216 inline bool
217 finally_tree_hasher::equal (const value_type *v, const compare_type *c)
219 return v->child.t == c->child.t;
222 /* Note that this table is *not* marked GTY. It is short-lived. */
223 static hash_table <finally_tree_hasher> finally_tree;
225 static void
226 record_in_finally_tree (treemple child, gimple parent)
228 struct finally_tree_node *n;
229 finally_tree_node **slot;
231 n = XNEW (struct finally_tree_node);
232 n->child = child;
233 n->parent = parent;
235 slot = finally_tree.find_slot (n, INSERT);
236 gcc_assert (!*slot);
237 *slot = n;
240 static void
241 collect_finally_tree (gimple stmt, gimple region);
243 /* Go through the gimple sequence. Works with collect_finally_tree to
244 record all GIMPLE_LABEL and GIMPLE_TRY statements. */
246 static void
247 collect_finally_tree_1 (gimple_seq seq, gimple region)
249 gimple_stmt_iterator gsi;
251 for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
252 collect_finally_tree (gsi_stmt (gsi), region);
255 static void
256 collect_finally_tree (gimple stmt, gimple region)
258 treemple temp;
260 switch (gimple_code (stmt))
262 case GIMPLE_LABEL:
263 temp.t = gimple_label_label (stmt);
264 record_in_finally_tree (temp, region);
265 break;
267 case GIMPLE_TRY:
268 if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
270 temp.g = stmt;
271 record_in_finally_tree (temp, region);
272 collect_finally_tree_1 (gimple_try_eval (stmt), stmt);
273 collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
275 else if (gimple_try_kind (stmt) == GIMPLE_TRY_CATCH)
277 collect_finally_tree_1 (gimple_try_eval (stmt), region);
278 collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
280 break;
282 case GIMPLE_CATCH:
283 collect_finally_tree_1 (gimple_catch_handler (stmt), region);
284 break;
286 case GIMPLE_EH_FILTER:
287 collect_finally_tree_1 (gimple_eh_filter_failure (stmt), region);
288 break;
290 case GIMPLE_EH_ELSE:
291 collect_finally_tree_1 (gimple_eh_else_n_body (stmt), region);
292 collect_finally_tree_1 (gimple_eh_else_e_body (stmt), region);
293 break;
295 default:
296 /* A type, a decl, or some kind of statement that we're not
297 interested in. Don't walk them. */
298 break;
303 /* Use the finally tree to determine if a jump from START to TARGET
304 would leave the try_finally node that START lives in. */
306 static bool
307 outside_finally_tree (treemple start, gimple target)
309 struct finally_tree_node n, *p;
313 n.child = start;
314 p = finally_tree.find (&n);
315 if (!p)
316 return true;
317 start.g = p->parent;
319 while (start.g != target);
321 return false;
324 /* Second pass of EH node decomposition. Actually transform the GIMPLE_TRY
325 nodes into a set of gotos, magic labels, and eh regions.
326 The eh region creation is straight-forward, but frobbing all the gotos
327 and such into shape isn't. */
329 /* The sequence into which we record all EH stuff. This will be
330 placed at the end of the function when we're all done. */
331 static gimple_seq eh_seq;
333 /* Record whether an EH region contains something that can throw,
334 indexed by EH region number. */
335 static bitmap eh_region_may_contain_throw_map;
337 /* The GOTO_QUEUE is is an array of GIMPLE_GOTO and GIMPLE_RETURN
338 statements that are seen to escape this GIMPLE_TRY_FINALLY node.
339 The idea is to record a gimple statement for everything except for
340 the conditionals, which get their labels recorded. Since labels are
341 of type 'tree', we need this node to store both gimple and tree
342 objects. REPL_STMT is the sequence used to replace the goto/return
343 statement. CONT_STMT is used to store the statement that allows
344 the return/goto to jump to the original destination. */
346 struct goto_queue_node
348 treemple stmt;
349 location_t location;
350 gimple_seq repl_stmt;
351 gimple cont_stmt;
352 int index;
353 /* This is used when index >= 0 to indicate that stmt is a label (as
354 opposed to a goto stmt). */
355 int is_label;
358 /* State of the world while lowering. */
360 struct leh_state
362 /* What's "current" while constructing the eh region tree. These
363 correspond to variables of the same name in cfun->eh, which we
364 don't have easy access to. */
365 eh_region cur_region;
367 /* What's "current" for the purposes of __builtin_eh_pointer. For
368 a CATCH, this is the associated TRY. For an EH_FILTER, this is
369 the associated ALLOWED_EXCEPTIONS, etc. */
370 eh_region ehp_region;
372 /* Processing of TRY_FINALLY requires a bit more state. This is
373 split out into a separate structure so that we don't have to
374 copy so much when processing other nodes. */
375 struct leh_tf_state *tf;
378 struct leh_tf_state
380 /* Pointer to the GIMPLE_TRY_FINALLY node under discussion. The
381 try_finally_expr is the original GIMPLE_TRY_FINALLY. We need to retain
382 this so that outside_finally_tree can reliably reference the tree used
383 in the collect_finally_tree data structures. */
384 gimple try_finally_expr;
385 gimple top_p;
387 /* While lowering a top_p usually it is expanded into multiple statements,
388 thus we need the following field to store them. */
389 gimple_seq top_p_seq;
391 /* The state outside this try_finally node. */
392 struct leh_state *outer;
394 /* The exception region created for it. */
395 eh_region region;
397 /* The goto queue. */
398 struct goto_queue_node *goto_queue;
399 size_t goto_queue_size;
400 size_t goto_queue_active;
402 /* Pointer map to help in searching goto_queue when it is large. */
403 struct pointer_map_t *goto_queue_map;
405 /* The set of unique labels seen as entries in the goto queue. */
406 vec<tree> dest_array;
408 /* A label to be added at the end of the completed transformed
409 sequence. It will be set if may_fallthru was true *at one time*,
410 though subsequent transformations may have cleared that flag. */
411 tree fallthru_label;
413 /* True if it is possible to fall out the bottom of the try block.
414 Cleared if the fallthru is converted to a goto. */
415 bool may_fallthru;
417 /* True if any entry in goto_queue is a GIMPLE_RETURN. */
418 bool may_return;
420 /* True if the finally block can receive an exception edge.
421 Cleared if the exception case is handled by code duplication. */
422 bool may_throw;
425 static gimple_seq lower_eh_must_not_throw (struct leh_state *, gimple);
427 /* Search for STMT in the goto queue. Return the replacement,
428 or null if the statement isn't in the queue. */
430 #define LARGE_GOTO_QUEUE 20
432 static void lower_eh_constructs_1 (struct leh_state *state, gimple_seq *seq);
434 static gimple_seq
435 find_goto_replacement (struct leh_tf_state *tf, treemple stmt)
437 unsigned int i;
438 void **slot;
440 if (tf->goto_queue_active < LARGE_GOTO_QUEUE)
442 for (i = 0; i < tf->goto_queue_active; i++)
443 if ( tf->goto_queue[i].stmt.g == stmt.g)
444 return tf->goto_queue[i].repl_stmt;
445 return NULL;
448 /* If we have a large number of entries in the goto_queue, create a
449 pointer map and use that for searching. */
451 if (!tf->goto_queue_map)
453 tf->goto_queue_map = pointer_map_create ();
454 for (i = 0; i < tf->goto_queue_active; i++)
456 slot = pointer_map_insert (tf->goto_queue_map,
457 tf->goto_queue[i].stmt.g);
458 gcc_assert (*slot == NULL);
459 *slot = &tf->goto_queue[i];
463 slot = pointer_map_contains (tf->goto_queue_map, stmt.g);
464 if (slot != NULL)
465 return (((struct goto_queue_node *) *slot)->repl_stmt);
467 return NULL;
470 /* A subroutine of replace_goto_queue_1. Handles the sub-clauses of a
471 lowered GIMPLE_COND. If, by chance, the replacement is a simple goto,
472 then we can just splat it in, otherwise we add the new stmts immediately
473 after the GIMPLE_COND and redirect. */
475 static void
476 replace_goto_queue_cond_clause (tree *tp, struct leh_tf_state *tf,
477 gimple_stmt_iterator *gsi)
479 tree label;
480 gimple_seq new_seq;
481 treemple temp;
482 location_t loc = gimple_location (gsi_stmt (*gsi));
484 temp.tp = tp;
485 new_seq = find_goto_replacement (tf, temp);
486 if (!new_seq)
487 return;
489 if (gimple_seq_singleton_p (new_seq)
490 && gimple_code (gimple_seq_first_stmt (new_seq)) == GIMPLE_GOTO)
492 *tp = gimple_goto_dest (gimple_seq_first_stmt (new_seq));
493 return;
496 label = create_artificial_label (loc);
497 /* Set the new label for the GIMPLE_COND */
498 *tp = label;
500 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
501 gsi_insert_seq_after (gsi, gimple_seq_copy (new_seq), GSI_CONTINUE_LINKING);
504 /* The real work of replace_goto_queue. Returns with TSI updated to
505 point to the next statement. */
507 static void replace_goto_queue_stmt_list (gimple_seq *, struct leh_tf_state *);
509 static void
510 replace_goto_queue_1 (gimple stmt, struct leh_tf_state *tf,
511 gimple_stmt_iterator *gsi)
513 gimple_seq seq;
514 treemple temp;
515 temp.g = NULL;
517 switch (gimple_code (stmt))
519 case GIMPLE_GOTO:
520 case GIMPLE_RETURN:
521 temp.g = stmt;
522 seq = find_goto_replacement (tf, temp);
523 if (seq)
525 gsi_insert_seq_before (gsi, gimple_seq_copy (seq), GSI_SAME_STMT);
526 gsi_remove (gsi, false);
527 return;
529 break;
531 case GIMPLE_COND:
532 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 2), tf, gsi);
533 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 3), tf, gsi);
534 break;
536 case GIMPLE_TRY:
537 replace_goto_queue_stmt_list (gimple_try_eval_ptr (stmt), tf);
538 replace_goto_queue_stmt_list (gimple_try_cleanup_ptr (stmt), tf);
539 break;
540 case GIMPLE_CATCH:
541 replace_goto_queue_stmt_list (gimple_catch_handler_ptr (stmt), tf);
542 break;
543 case GIMPLE_EH_FILTER:
544 replace_goto_queue_stmt_list (gimple_eh_filter_failure_ptr (stmt), tf);
545 break;
546 case GIMPLE_EH_ELSE:
547 replace_goto_queue_stmt_list (gimple_eh_else_n_body_ptr (stmt), tf);
548 replace_goto_queue_stmt_list (gimple_eh_else_e_body_ptr (stmt), tf);
549 break;
551 default:
552 /* These won't have gotos in them. */
553 break;
556 gsi_next (gsi);
559 /* A subroutine of replace_goto_queue. Handles GIMPLE_SEQ. */
561 static void
562 replace_goto_queue_stmt_list (gimple_seq *seq, struct leh_tf_state *tf)
564 gimple_stmt_iterator gsi = gsi_start (*seq);
566 while (!gsi_end_p (gsi))
567 replace_goto_queue_1 (gsi_stmt (gsi), tf, &gsi);
570 /* Replace all goto queue members. */
572 static void
573 replace_goto_queue (struct leh_tf_state *tf)
575 if (tf->goto_queue_active == 0)
576 return;
577 replace_goto_queue_stmt_list (&tf->top_p_seq, tf);
578 replace_goto_queue_stmt_list (&eh_seq, tf);
581 /* Add a new record to the goto queue contained in TF. NEW_STMT is the
582 data to be added, IS_LABEL indicates whether NEW_STMT is a label or
583 a gimple return. */
585 static void
586 record_in_goto_queue (struct leh_tf_state *tf,
587 treemple new_stmt,
588 int index,
589 bool is_label,
590 location_t location)
592 size_t active, size;
593 struct goto_queue_node *q;
595 gcc_assert (!tf->goto_queue_map);
597 active = tf->goto_queue_active;
598 size = tf->goto_queue_size;
599 if (active >= size)
601 size = (size ? size * 2 : 32);
602 tf->goto_queue_size = size;
603 tf->goto_queue
604 = XRESIZEVEC (struct goto_queue_node, tf->goto_queue, size);
607 q = &tf->goto_queue[active];
608 tf->goto_queue_active = active + 1;
610 memset (q, 0, sizeof (*q));
611 q->stmt = new_stmt;
612 q->index = index;
613 q->location = location;
614 q->is_label = is_label;
617 /* Record the LABEL label in the goto queue contained in TF.
618 TF is not null. */
620 static void
621 record_in_goto_queue_label (struct leh_tf_state *tf, treemple stmt, tree label,
622 location_t location)
624 int index;
625 treemple temp, new_stmt;
627 if (!label)
628 return;
630 /* Computed and non-local gotos do not get processed. Given
631 their nature we can neither tell whether we've escaped the
632 finally block nor redirect them if we knew. */
633 if (TREE_CODE (label) != LABEL_DECL)
634 return;
636 /* No need to record gotos that don't leave the try block. */
637 temp.t = label;
638 if (!outside_finally_tree (temp, tf->try_finally_expr))
639 return;
641 if (! tf->dest_array.exists ())
643 tf->dest_array.create (10);
644 tf->dest_array.quick_push (label);
645 index = 0;
647 else
649 int n = tf->dest_array.length ();
650 for (index = 0; index < n; ++index)
651 if (tf->dest_array[index] == label)
652 break;
653 if (index == n)
654 tf->dest_array.safe_push (label);
657 /* In the case of a GOTO we want to record the destination label,
658 since with a GIMPLE_COND we have an easy access to the then/else
659 labels. */
660 new_stmt = stmt;
661 record_in_goto_queue (tf, new_stmt, index, true, location);
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. */
668 static void
669 maybe_record_in_goto_queue (struct leh_state *state, gimple stmt)
671 struct leh_tf_state *tf = state->tf;
672 treemple new_stmt;
674 if (!tf)
675 return;
677 switch (gimple_code (stmt))
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 EXPR_LOCATION (*new_stmt.tp));
683 new_stmt.tp = gimple_op_ptr (stmt, 3);
684 record_in_goto_queue_label (tf, new_stmt, gimple_cond_false_label (stmt),
685 EXPR_LOCATION (*new_stmt.tp));
686 break;
687 case GIMPLE_GOTO:
688 new_stmt.g = stmt;
689 record_in_goto_queue_label (tf, new_stmt, gimple_goto_dest (stmt),
690 gimple_location (stmt));
691 break;
693 case GIMPLE_RETURN:
694 tf->may_return = true;
695 new_stmt.g = stmt;
696 record_in_goto_queue (tf, new_stmt, -1, false, gimple_location (stmt));
697 break;
699 default:
700 gcc_unreachable ();
705 #ifdef ENABLE_CHECKING
706 /* We do not process GIMPLE_SWITCHes for now. As long as the original source
707 was in fact structured, and we've not yet done jump threading, then none
708 of the labels will leave outer GIMPLE_TRY_FINALLY nodes. Verify this. */
710 static void
711 verify_norecord_switch_expr (struct leh_state *state, gimple switch_expr)
713 struct leh_tf_state *tf = state->tf;
714 size_t i, n;
716 if (!tf)
717 return;
719 n = gimple_switch_num_labels (switch_expr);
721 for (i = 0; i < n; ++i)
723 treemple temp;
724 tree lab = CASE_LABEL (gimple_switch_label (switch_expr, i));
725 temp.t = lab;
726 gcc_assert (!outside_finally_tree (temp, tf->try_finally_expr));
729 #else
730 #define verify_norecord_switch_expr(state, switch_expr)
731 #endif
733 /* Redirect a RETURN_EXPR pointed to by Q to FINLAB. If MOD is
734 non-null, insert it before the new branch. */
736 static void
737 do_return_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod)
739 gimple x;
741 /* In the case of a return, the queue node must be a gimple statement. */
742 gcc_assert (!q->is_label);
744 /* Note that the return value may have already been computed, e.g.,
746 int x;
747 int foo (void)
749 x = 0;
750 try {
751 return x;
752 } finally {
753 x++;
757 should return 0, not 1. We don't have to do anything to make
758 this happens because the return value has been placed in the
759 RESULT_DECL already. */
761 q->cont_stmt = q->stmt.g;
763 if (mod)
764 gimple_seq_add_seq (&q->repl_stmt, mod);
766 x = gimple_build_goto (finlab);
767 gimple_set_location (x, q->location);
768 gimple_seq_add_stmt (&q->repl_stmt, x);
771 /* Similar, but easier, for GIMPLE_GOTO. */
773 static void
774 do_goto_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
775 struct leh_tf_state *tf)
777 gimple x;
779 gcc_assert (q->is_label);
781 q->cont_stmt = gimple_build_goto (tf->dest_array[q->index]);
783 if (mod)
784 gimple_seq_add_seq (&q->repl_stmt, mod);
786 x = gimple_build_goto (finlab);
787 gimple_set_location (x, q->location);
788 gimple_seq_add_stmt (&q->repl_stmt, x);
791 /* Emit a standard landing pad sequence into SEQ for REGION. */
793 static void
794 emit_post_landing_pad (gimple_seq *seq, eh_region region)
796 eh_landing_pad lp = region->landing_pads;
797 gimple x;
799 if (lp == NULL)
800 lp = gen_eh_landing_pad (region);
802 lp->post_landing_pad = create_artificial_label (UNKNOWN_LOCATION);
803 EH_LANDING_PAD_NR (lp->post_landing_pad) = lp->index;
805 x = gimple_build_label (lp->post_landing_pad);
806 gimple_seq_add_stmt (seq, x);
809 /* Emit a RESX statement into SEQ for REGION. */
811 static void
812 emit_resx (gimple_seq *seq, eh_region region)
814 gimple x = gimple_build_resx (region->index);
815 gimple_seq_add_stmt (seq, x);
816 if (region->outer)
817 record_stmt_eh_region (region->outer, x);
820 /* Emit an EH_DISPATCH statement into SEQ for REGION. */
822 static void
823 emit_eh_dispatch (gimple_seq *seq, eh_region region)
825 gimple x = gimple_build_eh_dispatch (region->index);
826 gimple_seq_add_stmt (seq, x);
829 /* Note that the current EH region may contain a throw, or a
830 call to a function which itself may contain a throw. */
832 static void
833 note_eh_region_may_contain_throw (eh_region region)
835 while (bitmap_set_bit (eh_region_may_contain_throw_map, region->index))
837 if (region->type == ERT_MUST_NOT_THROW)
838 break;
839 region = region->outer;
840 if (region == NULL)
841 break;
845 /* Check if REGION has been marked as containing a throw. If REGION is
846 NULL, this predicate is false. */
848 static inline bool
849 eh_region_may_contain_throw (eh_region r)
851 return r && bitmap_bit_p (eh_region_may_contain_throw_map, r->index);
854 /* We want to transform
855 try { body; } catch { stuff; }
857 normal_seqence:
858 body;
859 over:
860 eh_seqence:
861 landing_pad:
862 stuff;
863 goto over;
865 TP is a GIMPLE_TRY node. REGION is the region whose post_landing_pad
866 should be placed before the second operand, or NULL. OVER is
867 an existing label that should be put at the exit, or NULL. */
869 static gimple_seq
870 frob_into_branch_around (gimple tp, eh_region region, tree over)
872 gimple x;
873 gimple_seq cleanup, result;
874 location_t loc = gimple_location (tp);
876 cleanup = gimple_try_cleanup (tp);
877 result = gimple_try_eval (tp);
879 if (region)
880 emit_post_landing_pad (&eh_seq, region);
882 if (gimple_seq_may_fallthru (cleanup))
884 if (!over)
885 over = create_artificial_label (loc);
886 x = gimple_build_goto (over);
887 gimple_set_location (x, loc);
888 gimple_seq_add_stmt (&cleanup, x);
890 gimple_seq_add_seq (&eh_seq, cleanup);
892 if (over)
894 x = gimple_build_label (over);
895 gimple_seq_add_stmt (&result, x);
897 return result;
900 /* A subroutine of lower_try_finally. Duplicate the tree rooted at T.
901 Make sure to record all new labels found. */
903 static gimple_seq
904 lower_try_finally_dup_block (gimple_seq seq, struct leh_state *outer_state,
905 location_t loc)
907 gimple region = NULL;
908 gimple_seq new_seq;
909 gimple_stmt_iterator gsi;
911 new_seq = copy_gimple_seq_and_replace_locals (seq);
913 for (gsi = gsi_start (new_seq); !gsi_end_p (gsi); gsi_next (&gsi))
915 gimple stmt = gsi_stmt (gsi);
916 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
918 tree block = gimple_block (stmt);
919 gimple_set_location (stmt, loc);
920 gimple_set_block (stmt, block);
924 if (outer_state->tf)
925 region = outer_state->tf->try_finally_expr;
926 collect_finally_tree_1 (new_seq, region);
928 return new_seq;
931 /* A subroutine of lower_try_finally. Create a fallthru label for
932 the given try_finally state. The only tricky bit here is that
933 we have to make sure to record the label in our outer context. */
935 static tree
936 lower_try_finally_fallthru_label (struct leh_tf_state *tf)
938 tree label = tf->fallthru_label;
939 treemple temp;
941 if (!label)
943 label = create_artificial_label (gimple_location (tf->try_finally_expr));
944 tf->fallthru_label = label;
945 if (tf->outer->tf)
947 temp.t = label;
948 record_in_finally_tree (temp, tf->outer->tf->try_finally_expr);
951 return label;
954 /* A subroutine of lower_try_finally. If FINALLY consits of a
955 GIMPLE_EH_ELSE node, return it. */
957 static inline gimple
958 get_eh_else (gimple_seq finally)
960 gimple x = gimple_seq_first_stmt (finally);
961 if (gimple_code (x) == GIMPLE_EH_ELSE)
963 gcc_assert (gimple_seq_singleton_p (finally));
964 return x;
966 return NULL;
969 /* A subroutine of lower_try_finally. If the eh_protect_cleanup_actions
970 langhook returns non-null, then the language requires that the exception
971 path out of a try_finally be treated specially. To wit: the code within
972 the finally block may not itself throw an exception. We have two choices
973 here. First we can duplicate the finally block and wrap it in a
974 must_not_throw region. Second, we can generate code like
976 try {
977 finally_block;
978 } catch {
979 if (fintmp == eh_edge)
980 protect_cleanup_actions;
983 where "fintmp" is the temporary used in the switch statement generation
984 alternative considered below. For the nonce, we always choose the first
985 option.
987 THIS_STATE may be null if this is a try-cleanup, not a try-finally. */
989 static void
990 honor_protect_cleanup_actions (struct leh_state *outer_state,
991 struct leh_state *this_state,
992 struct leh_tf_state *tf)
994 tree protect_cleanup_actions;
995 gimple_stmt_iterator gsi;
996 bool finally_may_fallthru;
997 gimple_seq finally;
998 gimple x, eh_else;
1000 /* First check for nothing to do. */
1001 if (lang_hooks.eh_protect_cleanup_actions == NULL)
1002 return;
1003 protect_cleanup_actions = lang_hooks.eh_protect_cleanup_actions ();
1004 if (protect_cleanup_actions == NULL)
1005 return;
1007 finally = gimple_try_cleanup (tf->top_p);
1008 eh_else = get_eh_else (finally);
1010 /* Duplicate the FINALLY block. Only need to do this for try-finally,
1011 and not for cleanups. If we've got an EH_ELSE, extract it now. */
1012 if (eh_else)
1014 finally = gimple_eh_else_e_body (eh_else);
1015 gimple_try_set_cleanup (tf->top_p, gimple_eh_else_n_body (eh_else));
1017 else if (this_state)
1018 finally = lower_try_finally_dup_block (finally, outer_state,
1019 gimple_location (tf->try_finally_expr));
1020 finally_may_fallthru = gimple_seq_may_fallthru (finally);
1022 /* If this cleanup consists of a TRY_CATCH_EXPR with TRY_CATCH_IS_CLEANUP
1023 set, the handler of the TRY_CATCH_EXPR is another cleanup which ought
1024 to be in an enclosing scope, but needs to be implemented at this level
1025 to avoid a nesting violation (see wrap_temporary_cleanups in
1026 cp/decl.c). Since it's logically at an outer level, we should call
1027 terminate before we get to it, so strip it away before adding the
1028 MUST_NOT_THROW filter. */
1029 gsi = gsi_start (finally);
1030 x = gsi_stmt (gsi);
1031 if (gimple_code (x) == GIMPLE_TRY
1032 && gimple_try_kind (x) == GIMPLE_TRY_CATCH
1033 && gimple_try_catch_is_cleanup (x))
1035 gsi_insert_seq_before (&gsi, gimple_try_eval (x), GSI_SAME_STMT);
1036 gsi_remove (&gsi, false);
1039 /* Wrap the block with protect_cleanup_actions as the action. */
1040 x = gimple_build_eh_must_not_throw (protect_cleanup_actions);
1041 x = gimple_build_try (finally, gimple_seq_alloc_with_stmt (x),
1042 GIMPLE_TRY_CATCH);
1043 finally = lower_eh_must_not_throw (outer_state, x);
1045 /* Drop all of this into the exception sequence. */
1046 emit_post_landing_pad (&eh_seq, tf->region);
1047 gimple_seq_add_seq (&eh_seq, finally);
1048 if (finally_may_fallthru)
1049 emit_resx (&eh_seq, tf->region);
1051 /* Having now been handled, EH isn't to be considered with
1052 the rest of the outgoing edges. */
1053 tf->may_throw = false;
1056 /* A subroutine of lower_try_finally. We have determined that there is
1057 no fallthru edge out of the finally block. This means that there is
1058 no outgoing edge corresponding to any incoming edge. Restructure the
1059 try_finally node for this special case. */
1061 static void
1062 lower_try_finally_nofallthru (struct leh_state *state,
1063 struct leh_tf_state *tf)
1065 tree lab;
1066 gimple x, eh_else;
1067 gimple_seq finally;
1068 struct goto_queue_node *q, *qe;
1070 lab = create_artificial_label (gimple_location (tf->try_finally_expr));
1072 /* We expect that tf->top_p is a GIMPLE_TRY. */
1073 finally = gimple_try_cleanup (tf->top_p);
1074 tf->top_p_seq = gimple_try_eval (tf->top_p);
1076 x = gimple_build_label (lab);
1077 gimple_seq_add_stmt (&tf->top_p_seq, x);
1079 q = tf->goto_queue;
1080 qe = q + tf->goto_queue_active;
1081 for (; q < qe; ++q)
1082 if (q->index < 0)
1083 do_return_redirection (q, lab, NULL);
1084 else
1085 do_goto_redirection (q, lab, NULL, tf);
1087 replace_goto_queue (tf);
1089 /* Emit the finally block into the stream. Lower EH_ELSE at this time. */
1090 eh_else = get_eh_else (finally);
1091 if (eh_else)
1093 finally = gimple_eh_else_n_body (eh_else);
1094 lower_eh_constructs_1 (state, &finally);
1095 gimple_seq_add_seq (&tf->top_p_seq, finally);
1097 if (tf->may_throw)
1099 finally = gimple_eh_else_e_body (eh_else);
1100 lower_eh_constructs_1 (state, &finally);
1102 emit_post_landing_pad (&eh_seq, tf->region);
1103 gimple_seq_add_seq (&eh_seq, finally);
1106 else
1108 lower_eh_constructs_1 (state, &finally);
1109 gimple_seq_add_seq (&tf->top_p_seq, finally);
1111 if (tf->may_throw)
1113 emit_post_landing_pad (&eh_seq, tf->region);
1115 x = gimple_build_goto (lab);
1116 gimple_set_location (x, gimple_location (tf->try_finally_expr));
1117 gimple_seq_add_stmt (&eh_seq, x);
1122 /* A subroutine of lower_try_finally. We have determined that there is
1123 exactly one destination of the finally block. Restructure the
1124 try_finally node for this special case. */
1126 static void
1127 lower_try_finally_onedest (struct leh_state *state, struct leh_tf_state *tf)
1129 struct goto_queue_node *q, *qe;
1130 gimple x;
1131 gimple_seq finally;
1132 gimple_stmt_iterator gsi;
1133 tree finally_label;
1134 location_t loc = gimple_location (tf->try_finally_expr);
1136 finally = gimple_try_cleanup (tf->top_p);
1137 tf->top_p_seq = gimple_try_eval (tf->top_p);
1139 /* Since there's only one destination, and the destination edge can only
1140 either be EH or non-EH, that implies that all of our incoming edges
1141 are of the same type. Therefore we can lower EH_ELSE immediately. */
1142 x = get_eh_else (finally);
1143 if (x)
1145 if (tf->may_throw)
1146 finally = gimple_eh_else_e_body (x);
1147 else
1148 finally = gimple_eh_else_n_body (x);
1151 lower_eh_constructs_1 (state, &finally);
1153 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1155 gimple stmt = gsi_stmt (gsi);
1156 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
1158 tree block = gimple_block (stmt);
1159 gimple_set_location (stmt, gimple_location (tf->try_finally_expr));
1160 gimple_set_block (stmt, block);
1164 if (tf->may_throw)
1166 /* Only reachable via the exception edge. Add the given label to
1167 the head of the FINALLY block. Append a RESX at the end. */
1168 emit_post_landing_pad (&eh_seq, tf->region);
1169 gimple_seq_add_seq (&eh_seq, finally);
1170 emit_resx (&eh_seq, tf->region);
1171 return;
1174 if (tf->may_fallthru)
1176 /* Only reachable via the fallthru edge. Do nothing but let
1177 the two blocks run together; we'll fall out the bottom. */
1178 gimple_seq_add_seq (&tf->top_p_seq, finally);
1179 return;
1182 finally_label = create_artificial_label (loc);
1183 x = gimple_build_label (finally_label);
1184 gimple_seq_add_stmt (&tf->top_p_seq, x);
1186 gimple_seq_add_seq (&tf->top_p_seq, finally);
1188 q = tf->goto_queue;
1189 qe = q + tf->goto_queue_active;
1191 if (tf->may_return)
1193 /* Reachable by return expressions only. Redirect them. */
1194 for (; q < qe; ++q)
1195 do_return_redirection (q, finally_label, NULL);
1196 replace_goto_queue (tf);
1198 else
1200 /* Reachable by goto expressions only. Redirect them. */
1201 for (; q < qe; ++q)
1202 do_goto_redirection (q, finally_label, NULL, tf);
1203 replace_goto_queue (tf);
1205 if (tf->dest_array[0] == tf->fallthru_label)
1207 /* Reachable by goto to fallthru label only. Redirect it
1208 to the new label (already created, sadly), and do not
1209 emit the final branch out, or the fallthru label. */
1210 tf->fallthru_label = NULL;
1211 return;
1215 /* Place the original return/goto to the original destination
1216 immediately after the finally block. */
1217 x = tf->goto_queue[0].cont_stmt;
1218 gimple_seq_add_stmt (&tf->top_p_seq, x);
1219 maybe_record_in_goto_queue (state, x);
1222 /* A subroutine of lower_try_finally. There are multiple edges incoming
1223 and outgoing from the finally block. Implement this by duplicating the
1224 finally block for every destination. */
1226 static void
1227 lower_try_finally_copy (struct leh_state *state, struct leh_tf_state *tf)
1229 gimple_seq finally;
1230 gimple_seq new_stmt;
1231 gimple_seq seq;
1232 gimple x, eh_else;
1233 tree tmp;
1234 location_t tf_loc = gimple_location (tf->try_finally_expr);
1236 finally = gimple_try_cleanup (tf->top_p);
1238 /* Notice EH_ELSE, and simplify some of the remaining code
1239 by considering FINALLY to be the normal return path only. */
1240 eh_else = get_eh_else (finally);
1241 if (eh_else)
1242 finally = gimple_eh_else_n_body (eh_else);
1244 tf->top_p_seq = gimple_try_eval (tf->top_p);
1245 new_stmt = NULL;
1247 if (tf->may_fallthru)
1249 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1250 lower_eh_constructs_1 (state, &seq);
1251 gimple_seq_add_seq (&new_stmt, seq);
1253 tmp = lower_try_finally_fallthru_label (tf);
1254 x = gimple_build_goto (tmp);
1255 gimple_set_location (x, tf_loc);
1256 gimple_seq_add_stmt (&new_stmt, x);
1259 if (tf->may_throw)
1261 /* We don't need to copy the EH path of EH_ELSE,
1262 since it is only emitted once. */
1263 if (eh_else)
1264 seq = gimple_eh_else_e_body (eh_else);
1265 else
1266 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1267 lower_eh_constructs_1 (state, &seq);
1269 emit_post_landing_pad (&eh_seq, tf->region);
1270 gimple_seq_add_seq (&eh_seq, seq);
1271 emit_resx (&eh_seq, tf->region);
1274 if (tf->goto_queue)
1276 struct goto_queue_node *q, *qe;
1277 int return_index, index;
1278 struct labels_s
1280 struct goto_queue_node *q;
1281 tree label;
1282 } *labels;
1284 return_index = tf->dest_array.length ();
1285 labels = XCNEWVEC (struct labels_s, return_index + 1);
1287 q = tf->goto_queue;
1288 qe = q + tf->goto_queue_active;
1289 for (; q < qe; q++)
1291 index = q->index < 0 ? return_index : q->index;
1293 if (!labels[index].q)
1294 labels[index].q = q;
1297 for (index = 0; index < return_index + 1; index++)
1299 tree lab;
1301 q = labels[index].q;
1302 if (! q)
1303 continue;
1305 lab = labels[index].label
1306 = create_artificial_label (tf_loc);
1308 if (index == return_index)
1309 do_return_redirection (q, lab, NULL);
1310 else
1311 do_goto_redirection (q, lab, NULL, tf);
1313 x = gimple_build_label (lab);
1314 gimple_seq_add_stmt (&new_stmt, x);
1316 seq = lower_try_finally_dup_block (finally, state, q->location);
1317 lower_eh_constructs_1 (state, &seq);
1318 gimple_seq_add_seq (&new_stmt, seq);
1320 gimple_seq_add_stmt (&new_stmt, q->cont_stmt);
1321 maybe_record_in_goto_queue (state, q->cont_stmt);
1324 for (q = tf->goto_queue; q < qe; q++)
1326 tree lab;
1328 index = q->index < 0 ? return_index : q->index;
1330 if (labels[index].q == q)
1331 continue;
1333 lab = labels[index].label;
1335 if (index == return_index)
1336 do_return_redirection (q, lab, NULL);
1337 else
1338 do_goto_redirection (q, lab, NULL, tf);
1341 replace_goto_queue (tf);
1342 free (labels);
1345 /* Need to link new stmts after running replace_goto_queue due
1346 to not wanting to process the same goto stmts twice. */
1347 gimple_seq_add_seq (&tf->top_p_seq, new_stmt);
1350 /* A subroutine of lower_try_finally. There are multiple edges incoming
1351 and outgoing from the finally block. Implement this by instrumenting
1352 each incoming edge and creating a switch statement at the end of the
1353 finally block that branches to the appropriate destination. */
1355 static void
1356 lower_try_finally_switch (struct leh_state *state, struct leh_tf_state *tf)
1358 struct goto_queue_node *q, *qe;
1359 tree finally_tmp, finally_label;
1360 int return_index, eh_index, fallthru_index;
1361 int nlabels, ndests, j, last_case_index;
1362 tree last_case;
1363 vec<tree> case_label_vec;
1364 gimple_seq switch_body = NULL;
1365 gimple x, eh_else;
1366 tree tmp;
1367 gimple switch_stmt;
1368 gimple_seq finally;
1369 struct pointer_map_t *cont_map = NULL;
1370 /* The location of the TRY_FINALLY stmt. */
1371 location_t tf_loc = gimple_location (tf->try_finally_expr);
1372 /* The location of the finally block. */
1373 location_t finally_loc;
1375 finally = gimple_try_cleanup (tf->top_p);
1376 eh_else = get_eh_else (finally);
1378 /* Mash the TRY block to the head of the chain. */
1379 tf->top_p_seq = gimple_try_eval (tf->top_p);
1381 /* The location of the finally is either the last stmt in the finally
1382 block or the location of the TRY_FINALLY itself. */
1383 x = gimple_seq_last_stmt (finally);
1384 finally_loc = x ? gimple_location (x) : tf_loc;
1386 /* Lower the finally block itself. */
1387 lower_eh_constructs_1 (state, &finally);
1389 /* Prepare for switch statement generation. */
1390 nlabels = tf->dest_array.length ();
1391 return_index = nlabels;
1392 eh_index = return_index + tf->may_return;
1393 fallthru_index = eh_index + (tf->may_throw && !eh_else);
1394 ndests = fallthru_index + tf->may_fallthru;
1396 finally_tmp = create_tmp_var (integer_type_node, "finally_tmp");
1397 finally_label = create_artificial_label (finally_loc);
1399 /* We use vec::quick_push on case_label_vec throughout this function,
1400 since we know the size in advance and allocate precisely as muce
1401 space as needed. */
1402 case_label_vec.create (ndests);
1403 last_case = NULL;
1404 last_case_index = 0;
1406 /* Begin inserting code for getting to the finally block. Things
1407 are done in this order to correspond to the sequence the code is
1408 laid out. */
1410 if (tf->may_fallthru)
1412 x = gimple_build_assign (finally_tmp,
1413 build_int_cst (integer_type_node,
1414 fallthru_index));
1415 gimple_seq_add_stmt (&tf->top_p_seq, x);
1417 tmp = build_int_cst (integer_type_node, fallthru_index);
1418 last_case = build_case_label (tmp, NULL,
1419 create_artificial_label (tf_loc));
1420 case_label_vec.quick_push (last_case);
1421 last_case_index++;
1423 x = gimple_build_label (CASE_LABEL (last_case));
1424 gimple_seq_add_stmt (&switch_body, x);
1426 tmp = lower_try_finally_fallthru_label (tf);
1427 x = gimple_build_goto (tmp);
1428 gimple_set_location (x, tf_loc);
1429 gimple_seq_add_stmt (&switch_body, x);
1432 /* For EH_ELSE, emit the exception path (plus resx) now, then
1433 subsequently we only need consider the normal path. */
1434 if (eh_else)
1436 if (tf->may_throw)
1438 finally = gimple_eh_else_e_body (eh_else);
1439 lower_eh_constructs_1 (state, &finally);
1441 emit_post_landing_pad (&eh_seq, tf->region);
1442 gimple_seq_add_seq (&eh_seq, finally);
1443 emit_resx (&eh_seq, tf->region);
1446 finally = gimple_eh_else_n_body (eh_else);
1448 else if (tf->may_throw)
1450 emit_post_landing_pad (&eh_seq, tf->region);
1452 x = gimple_build_assign (finally_tmp,
1453 build_int_cst (integer_type_node, eh_index));
1454 gimple_seq_add_stmt (&eh_seq, x);
1456 x = gimple_build_goto (finally_label);
1457 gimple_set_location (x, tf_loc);
1458 gimple_seq_add_stmt (&eh_seq, x);
1460 tmp = build_int_cst (integer_type_node, eh_index);
1461 last_case = build_case_label (tmp, NULL,
1462 create_artificial_label (tf_loc));
1463 case_label_vec.quick_push (last_case);
1464 last_case_index++;
1466 x = gimple_build_label (CASE_LABEL (last_case));
1467 gimple_seq_add_stmt (&eh_seq, x);
1468 emit_resx (&eh_seq, tf->region);
1471 x = gimple_build_label (finally_label);
1472 gimple_seq_add_stmt (&tf->top_p_seq, x);
1474 gimple_seq_add_seq (&tf->top_p_seq, finally);
1476 /* Redirect each incoming goto edge. */
1477 q = tf->goto_queue;
1478 qe = q + tf->goto_queue_active;
1479 j = last_case_index + tf->may_return;
1480 /* Prepare the assignments to finally_tmp that are executed upon the
1481 entrance through a particular edge. */
1482 for (; q < qe; ++q)
1484 gimple_seq mod = NULL;
1485 int switch_id;
1486 unsigned int case_index;
1488 if (q->index < 0)
1490 x = gimple_build_assign (finally_tmp,
1491 build_int_cst (integer_type_node,
1492 return_index));
1493 gimple_seq_add_stmt (&mod, x);
1494 do_return_redirection (q, finally_label, mod);
1495 switch_id = return_index;
1497 else
1499 x = gimple_build_assign (finally_tmp,
1500 build_int_cst (integer_type_node, q->index));
1501 gimple_seq_add_stmt (&mod, x);
1502 do_goto_redirection (q, finally_label, mod, tf);
1503 switch_id = q->index;
1506 case_index = j + q->index;
1507 if (case_label_vec.length () <= case_index || !case_label_vec[case_index])
1509 tree case_lab;
1510 void **slot;
1511 tmp = build_int_cst (integer_type_node, switch_id);
1512 case_lab = build_case_label (tmp, NULL,
1513 create_artificial_label (tf_loc));
1514 /* We store the cont_stmt in the pointer map, so that we can recover
1515 it in the loop below. */
1516 if (!cont_map)
1517 cont_map = pointer_map_create ();
1518 slot = pointer_map_insert (cont_map, case_lab);
1519 *slot = q->cont_stmt;
1520 case_label_vec.quick_push (case_lab);
1523 for (j = last_case_index; j < last_case_index + nlabels; j++)
1525 gimple cont_stmt;
1526 void **slot;
1528 last_case = case_label_vec[j];
1530 gcc_assert (last_case);
1531 gcc_assert (cont_map);
1533 slot = pointer_map_contains (cont_map, last_case);
1534 gcc_assert (slot);
1535 cont_stmt = *(gimple *) slot;
1537 x = gimple_build_label (CASE_LABEL (last_case));
1538 gimple_seq_add_stmt (&switch_body, x);
1539 gimple_seq_add_stmt (&switch_body, cont_stmt);
1540 maybe_record_in_goto_queue (state, cont_stmt);
1542 if (cont_map)
1543 pointer_map_destroy (cont_map);
1545 replace_goto_queue (tf);
1547 /* Make sure that the last case is the default label, as one is required.
1548 Then sort the labels, which is also required in GIMPLE. */
1549 CASE_LOW (last_case) = NULL;
1550 sort_case_labels (case_label_vec);
1552 /* Build the switch statement, setting last_case to be the default
1553 label. */
1554 switch_stmt = gimple_build_switch (finally_tmp, last_case,
1555 case_label_vec);
1556 gimple_set_location (switch_stmt, finally_loc);
1558 /* Need to link SWITCH_STMT after running replace_goto_queue
1559 due to not wanting to process the same goto stmts twice. */
1560 gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1561 gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1564 /* Decide whether or not we are going to duplicate the finally block.
1565 There are several considerations.
1567 First, if this is Java, then the finally block contains code
1568 written by the user. It has line numbers associated with it,
1569 so duplicating the block means it's difficult to set a breakpoint.
1570 Since controlling code generation via -g is verboten, we simply
1571 never duplicate code without optimization.
1573 Second, we'd like to prevent egregious code growth. One way to
1574 do this is to estimate the size of the finally block, multiply
1575 that by the number of copies we'd need to make, and compare against
1576 the estimate of the size of the switch machinery we'd have to add. */
1578 static bool
1579 decide_copy_try_finally (int ndests, bool may_throw, gimple_seq finally)
1581 int f_estimate, sw_estimate;
1582 gimple eh_else;
1584 /* If there's an EH_ELSE involved, the exception path is separate
1585 and really doesn't come into play for this computation. */
1586 eh_else = get_eh_else (finally);
1587 if (eh_else)
1589 ndests -= may_throw;
1590 finally = gimple_eh_else_n_body (eh_else);
1593 if (!optimize)
1595 gimple_stmt_iterator gsi;
1597 if (ndests == 1)
1598 return true;
1600 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1602 gimple stmt = gsi_stmt (gsi);
1603 if (!is_gimple_debug (stmt) && !gimple_clobber_p (stmt))
1604 return false;
1606 return true;
1609 /* Finally estimate N times, plus N gotos. */
1610 f_estimate = count_insns_seq (finally, &eni_size_weights);
1611 f_estimate = (f_estimate + 1) * ndests;
1613 /* Switch statement (cost 10), N variable assignments, N gotos. */
1614 sw_estimate = 10 + 2 * ndests;
1616 /* Optimize for size clearly wants our best guess. */
1617 if (optimize_function_for_size_p (cfun))
1618 return f_estimate < sw_estimate;
1620 /* ??? These numbers are completely made up so far. */
1621 if (optimize > 1)
1622 return f_estimate < 100 || f_estimate < sw_estimate * 2;
1623 else
1624 return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1627 /* REG is the enclosing region for a possible cleanup region, or the region
1628 itself. Returns TRUE if such a region would be unreachable.
1630 Cleanup regions within a must-not-throw region aren't actually reachable
1631 even if there are throwing stmts within them, because the personality
1632 routine will call terminate before unwinding. */
1634 static bool
1635 cleanup_is_dead_in (eh_region reg)
1637 while (reg && reg->type == ERT_CLEANUP)
1638 reg = reg->outer;
1639 return (reg && reg->type == ERT_MUST_NOT_THROW);
1642 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_FINALLY nodes
1643 to a sequence of labels and blocks, plus the exception region trees
1644 that record all the magic. This is complicated by the need to
1645 arrange for the FINALLY block to be executed on all exits. */
1647 static gimple_seq
1648 lower_try_finally (struct leh_state *state, gimple tp)
1650 struct leh_tf_state this_tf;
1651 struct leh_state this_state;
1652 int ndests;
1653 gimple_seq old_eh_seq;
1655 /* Process the try block. */
1657 memset (&this_tf, 0, sizeof (this_tf));
1658 this_tf.try_finally_expr = tp;
1659 this_tf.top_p = tp;
1660 this_tf.outer = state;
1661 if (using_eh_for_cleanups_p () && !cleanup_is_dead_in (state->cur_region))
1663 this_tf.region = gen_eh_region_cleanup (state->cur_region);
1664 this_state.cur_region = this_tf.region;
1666 else
1668 this_tf.region = NULL;
1669 this_state.cur_region = state->cur_region;
1672 this_state.ehp_region = state->ehp_region;
1673 this_state.tf = &this_tf;
1675 old_eh_seq = eh_seq;
1676 eh_seq = NULL;
1678 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1680 /* Determine if the try block is escaped through the bottom. */
1681 this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1683 /* Determine if any exceptions are possible within the try block. */
1684 if (this_tf.region)
1685 this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1686 if (this_tf.may_throw)
1687 honor_protect_cleanup_actions (state, &this_state, &this_tf);
1689 /* Determine how many edges (still) reach the finally block. Or rather,
1690 how many destinations are reached by the finally block. Use this to
1691 determine how we process the finally block itself. */
1693 ndests = this_tf.dest_array.length ();
1694 ndests += this_tf.may_fallthru;
1695 ndests += this_tf.may_return;
1696 ndests += this_tf.may_throw;
1698 /* If the FINALLY block is not reachable, dike it out. */
1699 if (ndests == 0)
1701 gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1702 gimple_try_set_cleanup (tp, NULL);
1704 /* If the finally block doesn't fall through, then any destination
1705 we might try to impose there isn't reached either. There may be
1706 some minor amount of cleanup and redirection still needed. */
1707 else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1708 lower_try_finally_nofallthru (state, &this_tf);
1710 /* We can easily special-case redirection to a single destination. */
1711 else if (ndests == 1)
1712 lower_try_finally_onedest (state, &this_tf);
1713 else if (decide_copy_try_finally (ndests, this_tf.may_throw,
1714 gimple_try_cleanup (tp)))
1715 lower_try_finally_copy (state, &this_tf);
1716 else
1717 lower_try_finally_switch (state, &this_tf);
1719 /* If someone requested we add a label at the end of the transformed
1720 block, do so. */
1721 if (this_tf.fallthru_label)
1723 /* This must be reached only if ndests == 0. */
1724 gimple x = gimple_build_label (this_tf.fallthru_label);
1725 gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1728 this_tf.dest_array.release ();
1729 free (this_tf.goto_queue);
1730 if (this_tf.goto_queue_map)
1731 pointer_map_destroy (this_tf.goto_queue_map);
1733 /* If there was an old (aka outer) eh_seq, append the current eh_seq.
1734 If there was no old eh_seq, then the append is trivially already done. */
1735 if (old_eh_seq)
1737 if (eh_seq == NULL)
1738 eh_seq = old_eh_seq;
1739 else
1741 gimple_seq new_eh_seq = eh_seq;
1742 eh_seq = old_eh_seq;
1743 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1747 return this_tf.top_p_seq;
1750 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_CATCH with a
1751 list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1752 exception region trees that records all the magic. */
1754 static gimple_seq
1755 lower_catch (struct leh_state *state, gimple tp)
1757 eh_region try_region = NULL;
1758 struct leh_state this_state = *state;
1759 gimple_stmt_iterator gsi;
1760 tree out_label;
1761 gimple_seq new_seq, cleanup;
1762 gimple x;
1763 location_t try_catch_loc = gimple_location (tp);
1765 if (flag_exceptions)
1767 try_region = gen_eh_region_try (state->cur_region);
1768 this_state.cur_region = try_region;
1771 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1773 if (!eh_region_may_contain_throw (try_region))
1774 return gimple_try_eval (tp);
1776 new_seq = NULL;
1777 emit_eh_dispatch (&new_seq, try_region);
1778 emit_resx (&new_seq, try_region);
1780 this_state.cur_region = state->cur_region;
1781 this_state.ehp_region = try_region;
1783 out_label = NULL;
1784 cleanup = gimple_try_cleanup (tp);
1785 for (gsi = gsi_start (cleanup);
1786 !gsi_end_p (gsi);
1787 gsi_next (&gsi))
1789 eh_catch c;
1790 gimple gcatch;
1791 gimple_seq handler;
1793 gcatch = gsi_stmt (gsi);
1794 c = gen_eh_region_catch (try_region, gimple_catch_types (gcatch));
1796 handler = gimple_catch_handler (gcatch);
1797 lower_eh_constructs_1 (&this_state, &handler);
1799 c->label = create_artificial_label (UNKNOWN_LOCATION);
1800 x = gimple_build_label (c->label);
1801 gimple_seq_add_stmt (&new_seq, x);
1803 gimple_seq_add_seq (&new_seq, handler);
1805 if (gimple_seq_may_fallthru (new_seq))
1807 if (!out_label)
1808 out_label = create_artificial_label (try_catch_loc);
1810 x = gimple_build_goto (out_label);
1811 gimple_seq_add_stmt (&new_seq, x);
1813 if (!c->type_list)
1814 break;
1817 gimple_try_set_cleanup (tp, new_seq);
1819 return frob_into_branch_around (tp, try_region, out_label);
1822 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with a
1823 GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1824 region trees that record all the magic. */
1826 static gimple_seq
1827 lower_eh_filter (struct leh_state *state, gimple tp)
1829 struct leh_state this_state = *state;
1830 eh_region this_region = NULL;
1831 gimple inner, x;
1832 gimple_seq new_seq;
1834 inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1836 if (flag_exceptions)
1838 this_region = gen_eh_region_allowed (state->cur_region,
1839 gimple_eh_filter_types (inner));
1840 this_state.cur_region = this_region;
1843 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1845 if (!eh_region_may_contain_throw (this_region))
1846 return gimple_try_eval (tp);
1848 new_seq = NULL;
1849 this_state.cur_region = state->cur_region;
1850 this_state.ehp_region = this_region;
1852 emit_eh_dispatch (&new_seq, this_region);
1853 emit_resx (&new_seq, this_region);
1855 this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1856 x = gimple_build_label (this_region->u.allowed.label);
1857 gimple_seq_add_stmt (&new_seq, x);
1859 lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure_ptr (inner));
1860 gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1862 gimple_try_set_cleanup (tp, new_seq);
1864 return frob_into_branch_around (tp, this_region, NULL);
1867 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with
1868 an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1869 plus the exception region trees that record all the magic. */
1871 static gimple_seq
1872 lower_eh_must_not_throw (struct leh_state *state, gimple tp)
1874 struct leh_state this_state = *state;
1876 if (flag_exceptions)
1878 gimple inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1879 eh_region this_region;
1881 this_region = gen_eh_region_must_not_throw (state->cur_region);
1882 this_region->u.must_not_throw.failure_decl
1883 = gimple_eh_must_not_throw_fndecl (inner);
1884 this_region->u.must_not_throw.failure_loc
1885 = LOCATION_LOCUS (gimple_location (tp));
1887 /* In order to get mangling applied to this decl, we must mark it
1888 used now. Otherwise, pass_ipa_free_lang_data won't think it
1889 needs to happen. */
1890 TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1892 this_state.cur_region = this_region;
1895 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1897 return gimple_try_eval (tp);
1900 /* Implement a cleanup expression. This is similar to try-finally,
1901 except that we only execute the cleanup block for exception edges. */
1903 static gimple_seq
1904 lower_cleanup (struct leh_state *state, gimple tp)
1906 struct leh_state this_state = *state;
1907 eh_region this_region = NULL;
1908 struct leh_tf_state fake_tf;
1909 gimple_seq result;
1910 bool cleanup_dead = cleanup_is_dead_in (state->cur_region);
1912 if (flag_exceptions && !cleanup_dead)
1914 this_region = gen_eh_region_cleanup (state->cur_region);
1915 this_state.cur_region = this_region;
1918 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1920 if (cleanup_dead || !eh_region_may_contain_throw (this_region))
1921 return gimple_try_eval (tp);
1923 /* Build enough of a try-finally state so that we can reuse
1924 honor_protect_cleanup_actions. */
1925 memset (&fake_tf, 0, sizeof (fake_tf));
1926 fake_tf.top_p = fake_tf.try_finally_expr = tp;
1927 fake_tf.outer = state;
1928 fake_tf.region = this_region;
1929 fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1930 fake_tf.may_throw = true;
1932 honor_protect_cleanup_actions (state, NULL, &fake_tf);
1934 if (fake_tf.may_throw)
1936 /* In this case honor_protect_cleanup_actions had nothing to do,
1937 and we should process this normally. */
1938 lower_eh_constructs_1 (state, gimple_try_cleanup_ptr (tp));
1939 result = frob_into_branch_around (tp, this_region,
1940 fake_tf.fallthru_label);
1942 else
1944 /* In this case honor_protect_cleanup_actions did nearly all of
1945 the work. All we have left is to append the fallthru_label. */
1947 result = gimple_try_eval (tp);
1948 if (fake_tf.fallthru_label)
1950 gimple x = gimple_build_label (fake_tf.fallthru_label);
1951 gimple_seq_add_stmt (&result, x);
1954 return result;
1957 /* Main loop for lowering eh constructs. Also moves gsi to the next
1958 statement. */
1960 static void
1961 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1963 gimple_seq replace;
1964 gimple x;
1965 gimple stmt = gsi_stmt (*gsi);
1967 switch (gimple_code (stmt))
1969 case GIMPLE_CALL:
1971 tree fndecl = gimple_call_fndecl (stmt);
1972 tree rhs, lhs;
1974 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1975 switch (DECL_FUNCTION_CODE (fndecl))
1977 case BUILT_IN_EH_POINTER:
1978 /* The front end may have generated a call to
1979 __builtin_eh_pointer (0) within a catch region. Replace
1980 this zero argument with the current catch region number. */
1981 if (state->ehp_region)
1983 tree nr = build_int_cst (integer_type_node,
1984 state->ehp_region->index);
1985 gimple_call_set_arg (stmt, 0, nr);
1987 else
1989 /* The user has dome something silly. Remove it. */
1990 rhs = null_pointer_node;
1991 goto do_replace;
1993 break;
1995 case BUILT_IN_EH_FILTER:
1996 /* ??? This should never appear, but since it's a builtin it
1997 is accessible to abuse by users. Just remove it and
1998 replace the use with the arbitrary value zero. */
1999 rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
2000 do_replace:
2001 lhs = gimple_call_lhs (stmt);
2002 x = gimple_build_assign (lhs, rhs);
2003 gsi_insert_before (gsi, x, GSI_SAME_STMT);
2004 /* FALLTHRU */
2006 case BUILT_IN_EH_COPY_VALUES:
2007 /* Likewise this should not appear. Remove it. */
2008 gsi_remove (gsi, true);
2009 return;
2011 default:
2012 break;
2015 /* FALLTHRU */
2017 case GIMPLE_ASSIGN:
2018 /* If the stmt can throw use a new temporary for the assignment
2019 to a LHS. This makes sure the old value of the LHS is
2020 available on the EH edge. Only do so for statements that
2021 potentially fall through (no noreturn calls e.g.), otherwise
2022 this new assignment might create fake fallthru regions. */
2023 if (stmt_could_throw_p (stmt)
2024 && gimple_has_lhs (stmt)
2025 && gimple_stmt_may_fallthru (stmt)
2026 && !tree_could_throw_p (gimple_get_lhs (stmt))
2027 && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
2029 tree lhs = gimple_get_lhs (stmt);
2030 tree tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2031 gimple s = gimple_build_assign (lhs, tmp);
2032 gimple_set_location (s, gimple_location (stmt));
2033 gimple_set_block (s, gimple_block (stmt));
2034 gimple_set_lhs (stmt, tmp);
2035 if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
2036 || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
2037 DECL_GIMPLE_REG_P (tmp) = 1;
2038 gsi_insert_after (gsi, s, GSI_SAME_STMT);
2040 /* Look for things that can throw exceptions, and record them. */
2041 if (state->cur_region && stmt_could_throw_p (stmt))
2043 record_stmt_eh_region (state->cur_region, stmt);
2044 note_eh_region_may_contain_throw (state->cur_region);
2046 break;
2048 case GIMPLE_COND:
2049 case GIMPLE_GOTO:
2050 case GIMPLE_RETURN:
2051 maybe_record_in_goto_queue (state, stmt);
2052 break;
2054 case GIMPLE_SWITCH:
2055 verify_norecord_switch_expr (state, stmt);
2056 break;
2058 case GIMPLE_TRY:
2059 if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
2060 replace = lower_try_finally (state, stmt);
2061 else
2063 x = gimple_seq_first_stmt (gimple_try_cleanup (stmt));
2064 if (!x)
2066 replace = gimple_try_eval (stmt);
2067 lower_eh_constructs_1 (state, &replace);
2069 else
2070 switch (gimple_code (x))
2072 case GIMPLE_CATCH:
2073 replace = lower_catch (state, stmt);
2074 break;
2075 case GIMPLE_EH_FILTER:
2076 replace = lower_eh_filter (state, stmt);
2077 break;
2078 case GIMPLE_EH_MUST_NOT_THROW:
2079 replace = lower_eh_must_not_throw (state, stmt);
2080 break;
2081 case GIMPLE_EH_ELSE:
2082 /* This code is only valid with GIMPLE_TRY_FINALLY. */
2083 gcc_unreachable ();
2084 default:
2085 replace = lower_cleanup (state, stmt);
2086 break;
2090 /* Remove the old stmt and insert the transformed sequence
2091 instead. */
2092 gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
2093 gsi_remove (gsi, true);
2095 /* Return since we don't want gsi_next () */
2096 return;
2098 case GIMPLE_EH_ELSE:
2099 /* We should be eliminating this in lower_try_finally et al. */
2100 gcc_unreachable ();
2102 default:
2103 /* A type, a decl, or some kind of statement that we're not
2104 interested in. Don't walk them. */
2105 break;
2108 gsi_next (gsi);
2111 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
2113 static void
2114 lower_eh_constructs_1 (struct leh_state *state, gimple_seq *pseq)
2116 gimple_stmt_iterator gsi;
2117 for (gsi = gsi_start (*pseq); !gsi_end_p (gsi);)
2118 lower_eh_constructs_2 (state, &gsi);
2121 static unsigned int
2122 lower_eh_constructs (void)
2124 struct leh_state null_state;
2125 gimple_seq bodyp;
2127 bodyp = gimple_body (current_function_decl);
2128 if (bodyp == NULL)
2129 return 0;
2131 finally_tree.create (31);
2132 eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
2133 memset (&null_state, 0, sizeof (null_state));
2135 collect_finally_tree_1 (bodyp, NULL);
2136 lower_eh_constructs_1 (&null_state, &bodyp);
2137 gimple_set_body (current_function_decl, bodyp);
2139 /* We assume there's a return statement, or something, at the end of
2140 the function, and thus ploping the EH sequence afterward won't
2141 change anything. */
2142 gcc_assert (!gimple_seq_may_fallthru (bodyp));
2143 gimple_seq_add_seq (&bodyp, eh_seq);
2145 /* We assume that since BODYP already existed, adding EH_SEQ to it
2146 didn't change its value, and we don't have to re-set the function. */
2147 gcc_assert (bodyp == gimple_body (current_function_decl));
2149 finally_tree.dispose ();
2150 BITMAP_FREE (eh_region_may_contain_throw_map);
2151 eh_seq = NULL;
2153 /* If this function needs a language specific EH personality routine
2154 and the frontend didn't already set one do so now. */
2155 if (function_needs_eh_personality (cfun) == eh_personality_lang
2156 && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2157 DECL_FUNCTION_PERSONALITY (current_function_decl)
2158 = lang_hooks.eh_personality ();
2160 return 0;
2163 namespace {
2165 const pass_data pass_data_lower_eh =
2167 GIMPLE_PASS, /* type */
2168 "eh", /* name */
2169 OPTGROUP_NONE, /* optinfo_flags */
2170 false, /* has_gate */
2171 true, /* has_execute */
2172 TV_TREE_EH, /* tv_id */
2173 PROP_gimple_lcf, /* properties_required */
2174 PROP_gimple_leh, /* properties_provided */
2175 0, /* properties_destroyed */
2176 0, /* todo_flags_start */
2177 0, /* todo_flags_finish */
2180 class pass_lower_eh : public gimple_opt_pass
2182 public:
2183 pass_lower_eh (gcc::context *ctxt)
2184 : gimple_opt_pass (pass_data_lower_eh, ctxt)
2187 /* opt_pass methods: */
2188 unsigned int execute () { return lower_eh_constructs (); }
2190 }; // class pass_lower_eh
2192 } // anon namespace
2194 gimple_opt_pass *
2195 make_pass_lower_eh (gcc::context *ctxt)
2197 return new pass_lower_eh (ctxt);
2200 /* Create the multiple edges from an EH_DISPATCH statement to all of
2201 the possible handlers for its EH region. Return true if there's
2202 no fallthru edge; false if there is. */
2204 bool
2205 make_eh_dispatch_edges (gimple stmt)
2207 eh_region r;
2208 eh_catch c;
2209 basic_block src, dst;
2211 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2212 src = gimple_bb (stmt);
2214 switch (r->type)
2216 case ERT_TRY:
2217 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2219 dst = label_to_block (c->label);
2220 make_edge (src, dst, 0);
2222 /* A catch-all handler doesn't have a fallthru. */
2223 if (c->type_list == NULL)
2224 return false;
2226 break;
2228 case ERT_ALLOWED_EXCEPTIONS:
2229 dst = label_to_block (r->u.allowed.label);
2230 make_edge (src, dst, 0);
2231 break;
2233 default:
2234 gcc_unreachable ();
2237 return true;
2240 /* Create the single EH edge from STMT to its nearest landing pad,
2241 if there is such a landing pad within the current function. */
2243 void
2244 make_eh_edges (gimple stmt)
2246 basic_block src, dst;
2247 eh_landing_pad lp;
2248 int lp_nr;
2250 lp_nr = lookup_stmt_eh_lp (stmt);
2251 if (lp_nr <= 0)
2252 return;
2254 lp = get_eh_landing_pad_from_number (lp_nr);
2255 gcc_assert (lp != NULL);
2257 src = gimple_bb (stmt);
2258 dst = label_to_block (lp->post_landing_pad);
2259 make_edge (src, dst, EDGE_EH);
2262 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2263 do not actually perform the final edge redirection.
2265 CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2266 we intend to change the destination EH region as well; this means
2267 EH_LANDING_PAD_NR must already be set on the destination block label.
2268 If false, we're being called from generic cfg manipulation code and we
2269 should preserve our place within the region tree. */
2271 static void
2272 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2274 eh_landing_pad old_lp, new_lp;
2275 basic_block old_bb;
2276 gimple throw_stmt;
2277 int old_lp_nr, new_lp_nr;
2278 tree old_label, new_label;
2279 edge_iterator ei;
2280 edge e;
2282 old_bb = edge_in->dest;
2283 old_label = gimple_block_label (old_bb);
2284 old_lp_nr = EH_LANDING_PAD_NR (old_label);
2285 gcc_assert (old_lp_nr > 0);
2286 old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2288 throw_stmt = last_stmt (edge_in->src);
2289 gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2291 new_label = gimple_block_label (new_bb);
2293 /* Look for an existing region that might be using NEW_BB already. */
2294 new_lp_nr = EH_LANDING_PAD_NR (new_label);
2295 if (new_lp_nr)
2297 new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2298 gcc_assert (new_lp);
2300 /* Unless CHANGE_REGION is true, the new and old landing pad
2301 had better be associated with the same EH region. */
2302 gcc_assert (change_region || new_lp->region == old_lp->region);
2304 else
2306 new_lp = NULL;
2307 gcc_assert (!change_region);
2310 /* Notice when we redirect the last EH edge away from OLD_BB. */
2311 FOR_EACH_EDGE (e, ei, old_bb->preds)
2312 if (e != edge_in && (e->flags & EDGE_EH))
2313 break;
2315 if (new_lp)
2317 /* NEW_LP already exists. If there are still edges into OLD_LP,
2318 there's nothing to do with the EH tree. If there are no more
2319 edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2320 If CHANGE_REGION is true, then our caller is expecting to remove
2321 the landing pad. */
2322 if (e == NULL && !change_region)
2323 remove_eh_landing_pad (old_lp);
2325 else
2327 /* No correct landing pad exists. If there are no more edges
2328 into OLD_LP, then we can simply re-use the existing landing pad.
2329 Otherwise, we have to create a new landing pad. */
2330 if (e == NULL)
2332 EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2333 new_lp = old_lp;
2335 else
2336 new_lp = gen_eh_landing_pad (old_lp->region);
2337 new_lp->post_landing_pad = new_label;
2338 EH_LANDING_PAD_NR (new_label) = new_lp->index;
2341 /* Maybe move the throwing statement to the new region. */
2342 if (old_lp != new_lp)
2344 remove_stmt_from_eh_lp (throw_stmt);
2345 add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2349 /* Redirect EH edge E to NEW_BB. */
2351 edge
2352 redirect_eh_edge (edge edge_in, basic_block new_bb)
2354 redirect_eh_edge_1 (edge_in, new_bb, false);
2355 return ssa_redirect_edge (edge_in, new_bb);
2358 /* This is a subroutine of gimple_redirect_edge_and_branch. Update the
2359 labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2360 The actual edge update will happen in the caller. */
2362 void
2363 redirect_eh_dispatch_edge (gimple stmt, edge e, basic_block new_bb)
2365 tree new_lab = gimple_block_label (new_bb);
2366 bool any_changed = false;
2367 basic_block old_bb;
2368 eh_region r;
2369 eh_catch c;
2371 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2372 switch (r->type)
2374 case ERT_TRY:
2375 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2377 old_bb = label_to_block (c->label);
2378 if (old_bb == e->dest)
2380 c->label = new_lab;
2381 any_changed = true;
2384 break;
2386 case ERT_ALLOWED_EXCEPTIONS:
2387 old_bb = label_to_block (r->u.allowed.label);
2388 gcc_assert (old_bb == e->dest);
2389 r->u.allowed.label = new_lab;
2390 any_changed = true;
2391 break;
2393 default:
2394 gcc_unreachable ();
2397 gcc_assert (any_changed);
2400 /* Helper function for operation_could_trap_p and stmt_could_throw_p. */
2402 bool
2403 operation_could_trap_helper_p (enum tree_code op,
2404 bool fp_operation,
2405 bool honor_trapv,
2406 bool honor_nans,
2407 bool honor_snans,
2408 tree divisor,
2409 bool *handled)
2411 *handled = true;
2412 switch (op)
2414 case TRUNC_DIV_EXPR:
2415 case CEIL_DIV_EXPR:
2416 case FLOOR_DIV_EXPR:
2417 case ROUND_DIV_EXPR:
2418 case EXACT_DIV_EXPR:
2419 case CEIL_MOD_EXPR:
2420 case FLOOR_MOD_EXPR:
2421 case ROUND_MOD_EXPR:
2422 case TRUNC_MOD_EXPR:
2423 case RDIV_EXPR:
2424 if (honor_snans || honor_trapv)
2425 return true;
2426 if (fp_operation)
2427 return flag_trapping_math;
2428 if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2429 return true;
2430 return false;
2432 case LT_EXPR:
2433 case LE_EXPR:
2434 case GT_EXPR:
2435 case GE_EXPR:
2436 case LTGT_EXPR:
2437 /* Some floating point comparisons may trap. */
2438 return honor_nans;
2440 case EQ_EXPR:
2441 case NE_EXPR:
2442 case UNORDERED_EXPR:
2443 case ORDERED_EXPR:
2444 case UNLT_EXPR:
2445 case UNLE_EXPR:
2446 case UNGT_EXPR:
2447 case UNGE_EXPR:
2448 case UNEQ_EXPR:
2449 return honor_snans;
2451 case CONVERT_EXPR:
2452 case FIX_TRUNC_EXPR:
2453 /* Conversion of floating point might trap. */
2454 return honor_nans;
2456 case NEGATE_EXPR:
2457 case ABS_EXPR:
2458 case CONJ_EXPR:
2459 /* These operations don't trap with floating point. */
2460 if (honor_trapv)
2461 return true;
2462 return false;
2464 case PLUS_EXPR:
2465 case MINUS_EXPR:
2466 case MULT_EXPR:
2467 /* Any floating arithmetic may trap. */
2468 if (fp_operation && flag_trapping_math)
2469 return true;
2470 if (honor_trapv)
2471 return true;
2472 return false;
2474 case COMPLEX_EXPR:
2475 case CONSTRUCTOR:
2476 /* Constructing an object cannot trap. */
2477 return false;
2479 default:
2480 /* Any floating arithmetic may trap. */
2481 if (fp_operation && flag_trapping_math)
2482 return true;
2484 *handled = false;
2485 return false;
2489 /* Return true if operation OP may trap. FP_OPERATION is true if OP is applied
2490 on floating-point values. HONOR_TRAPV is true if OP is applied on integer
2491 type operands that may trap. If OP is a division operator, DIVISOR contains
2492 the value of the divisor. */
2494 bool
2495 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2496 tree divisor)
2498 bool honor_nans = (fp_operation && flag_trapping_math
2499 && !flag_finite_math_only);
2500 bool honor_snans = fp_operation && flag_signaling_nans != 0;
2501 bool handled;
2503 if (TREE_CODE_CLASS (op) != tcc_comparison
2504 && TREE_CODE_CLASS (op) != tcc_unary
2505 && TREE_CODE_CLASS (op) != tcc_binary)
2506 return false;
2508 return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2509 honor_nans, honor_snans, divisor,
2510 &handled);
2514 /* Returns true if it is possible to prove that the index of
2515 an array access REF (an ARRAY_REF expression) falls into the
2516 array bounds. */
2518 static bool
2519 in_array_bounds_p (tree ref)
2521 tree idx = TREE_OPERAND (ref, 1);
2522 tree min, max;
2524 if (TREE_CODE (idx) != INTEGER_CST)
2525 return false;
2527 min = array_ref_low_bound (ref);
2528 max = array_ref_up_bound (ref);
2529 if (!min
2530 || !max
2531 || TREE_CODE (min) != INTEGER_CST
2532 || TREE_CODE (max) != INTEGER_CST)
2533 return false;
2535 if (tree_int_cst_lt (idx, min)
2536 || tree_int_cst_lt (max, idx))
2537 return false;
2539 return true;
2542 /* Returns true if it is possible to prove that the range of
2543 an array access REF (an ARRAY_RANGE_REF expression) falls
2544 into the array bounds. */
2546 static bool
2547 range_in_array_bounds_p (tree ref)
2549 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ref));
2550 tree range_min, range_max, min, max;
2552 range_min = TYPE_MIN_VALUE (domain_type);
2553 range_max = TYPE_MAX_VALUE (domain_type);
2554 if (!range_min
2555 || !range_max
2556 || TREE_CODE (range_min) != INTEGER_CST
2557 || TREE_CODE (range_max) != INTEGER_CST)
2558 return false;
2560 min = array_ref_low_bound (ref);
2561 max = array_ref_up_bound (ref);
2562 if (!min
2563 || !max
2564 || TREE_CODE (min) != INTEGER_CST
2565 || TREE_CODE (max) != INTEGER_CST)
2566 return false;
2568 if (tree_int_cst_lt (range_min, min)
2569 || tree_int_cst_lt (max, range_max))
2570 return false;
2572 return true;
2575 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2576 location or floating point arithmetic. C.f. the rtl version, may_trap_p.
2577 This routine expects only GIMPLE lhs or rhs input. */
2579 bool
2580 tree_could_trap_p (tree expr)
2582 enum tree_code code;
2583 bool fp_operation = false;
2584 bool honor_trapv = false;
2585 tree t, base, div = NULL_TREE;
2587 if (!expr)
2588 return false;
2590 code = TREE_CODE (expr);
2591 t = TREE_TYPE (expr);
2593 if (t)
2595 if (COMPARISON_CLASS_P (expr))
2596 fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2597 else
2598 fp_operation = FLOAT_TYPE_P (t);
2599 honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2602 if (TREE_CODE_CLASS (code) == tcc_binary)
2603 div = TREE_OPERAND (expr, 1);
2604 if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2605 return true;
2607 restart:
2608 switch (code)
2610 case TARGET_MEM_REF:
2611 if (TREE_CODE (TMR_BASE (expr)) == ADDR_EXPR
2612 && !TMR_INDEX (expr) && !TMR_INDEX2 (expr))
2613 return false;
2614 return !TREE_THIS_NOTRAP (expr);
2616 case COMPONENT_REF:
2617 case REALPART_EXPR:
2618 case IMAGPART_EXPR:
2619 case BIT_FIELD_REF:
2620 case VIEW_CONVERT_EXPR:
2621 case WITH_SIZE_EXPR:
2622 expr = TREE_OPERAND (expr, 0);
2623 code = TREE_CODE (expr);
2624 goto restart;
2626 case ARRAY_RANGE_REF:
2627 base = TREE_OPERAND (expr, 0);
2628 if (tree_could_trap_p (base))
2629 return true;
2630 if (TREE_THIS_NOTRAP (expr))
2631 return false;
2632 return !range_in_array_bounds_p (expr);
2634 case ARRAY_REF:
2635 base = TREE_OPERAND (expr, 0);
2636 if (tree_could_trap_p (base))
2637 return true;
2638 if (TREE_THIS_NOTRAP (expr))
2639 return false;
2640 return !in_array_bounds_p (expr);
2642 case MEM_REF:
2643 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR)
2644 return false;
2645 /* Fallthru. */
2646 case INDIRECT_REF:
2647 return !TREE_THIS_NOTRAP (expr);
2649 case ASM_EXPR:
2650 return TREE_THIS_VOLATILE (expr);
2652 case CALL_EXPR:
2653 t = get_callee_fndecl (expr);
2654 /* Assume that calls to weak functions may trap. */
2655 if (!t || !DECL_P (t))
2656 return true;
2657 if (DECL_WEAK (t))
2658 return tree_could_trap_p (t);
2659 return false;
2661 case FUNCTION_DECL:
2662 /* Assume that accesses to weak functions may trap, unless we know
2663 they are certainly defined in current TU or in some other
2664 LTO partition. */
2665 if (DECL_WEAK (expr) && !DECL_COMDAT (expr))
2667 struct cgraph_node *node;
2668 if (!DECL_EXTERNAL (expr))
2669 return false;
2670 node = cgraph_function_node (cgraph_get_node (expr), NULL);
2671 if (node && node->in_other_partition)
2672 return false;
2673 return true;
2675 return false;
2677 case VAR_DECL:
2678 /* Assume that accesses to weak vars may trap, unless we know
2679 they are certainly defined in current TU or in some other
2680 LTO partition. */
2681 if (DECL_WEAK (expr) && !DECL_COMDAT (expr))
2683 struct varpool_node *node;
2684 if (!DECL_EXTERNAL (expr))
2685 return false;
2686 node = varpool_variable_node (varpool_get_node (expr), NULL);
2687 if (node && node->in_other_partition)
2688 return false;
2689 return true;
2691 return false;
2693 default:
2694 return false;
2699 /* Helper for stmt_could_throw_p. Return true if STMT (assumed to be a
2700 an assignment or a conditional) may throw. */
2702 static bool
2703 stmt_could_throw_1_p (gimple stmt)
2705 enum tree_code code = gimple_expr_code (stmt);
2706 bool honor_nans = false;
2707 bool honor_snans = false;
2708 bool fp_operation = false;
2709 bool honor_trapv = false;
2710 tree t;
2711 size_t i;
2712 bool handled, ret;
2714 if (TREE_CODE_CLASS (code) == tcc_comparison
2715 || TREE_CODE_CLASS (code) == tcc_unary
2716 || TREE_CODE_CLASS (code) == tcc_binary)
2718 if (is_gimple_assign (stmt)
2719 && TREE_CODE_CLASS (code) == tcc_comparison)
2720 t = TREE_TYPE (gimple_assign_rhs1 (stmt));
2721 else if (gimple_code (stmt) == GIMPLE_COND)
2722 t = TREE_TYPE (gimple_cond_lhs (stmt));
2723 else
2724 t = gimple_expr_type (stmt);
2725 fp_operation = FLOAT_TYPE_P (t);
2726 if (fp_operation)
2728 honor_nans = flag_trapping_math && !flag_finite_math_only;
2729 honor_snans = flag_signaling_nans != 0;
2731 else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2732 honor_trapv = true;
2735 /* Check if the main expression may trap. */
2736 t = is_gimple_assign (stmt) ? gimple_assign_rhs2 (stmt) : NULL;
2737 ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2738 honor_nans, honor_snans, t,
2739 &handled);
2740 if (handled)
2741 return ret;
2743 /* If the expression does not trap, see if any of the individual operands may
2744 trap. */
2745 for (i = 0; i < gimple_num_ops (stmt); i++)
2746 if (tree_could_trap_p (gimple_op (stmt, i)))
2747 return true;
2749 return false;
2753 /* Return true if statement STMT could throw an exception. */
2755 bool
2756 stmt_could_throw_p (gimple stmt)
2758 if (!flag_exceptions)
2759 return false;
2761 /* The only statements that can throw an exception are assignments,
2762 conditionals, calls, resx, and asms. */
2763 switch (gimple_code (stmt))
2765 case GIMPLE_RESX:
2766 return true;
2768 case GIMPLE_CALL:
2769 return !gimple_call_nothrow_p (stmt);
2771 case GIMPLE_ASSIGN:
2772 case GIMPLE_COND:
2773 if (!cfun->can_throw_non_call_exceptions)
2774 return false;
2775 return stmt_could_throw_1_p (stmt);
2777 case GIMPLE_ASM:
2778 if (!cfun->can_throw_non_call_exceptions)
2779 return false;
2780 return gimple_asm_volatile_p (stmt);
2782 default:
2783 return false;
2788 /* Return true if expression T could throw an exception. */
2790 bool
2791 tree_could_throw_p (tree t)
2793 if (!flag_exceptions)
2794 return false;
2795 if (TREE_CODE (t) == MODIFY_EXPR)
2797 if (cfun->can_throw_non_call_exceptions
2798 && tree_could_trap_p (TREE_OPERAND (t, 0)))
2799 return true;
2800 t = TREE_OPERAND (t, 1);
2803 if (TREE_CODE (t) == WITH_SIZE_EXPR)
2804 t = TREE_OPERAND (t, 0);
2805 if (TREE_CODE (t) == CALL_EXPR)
2806 return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2807 if (cfun->can_throw_non_call_exceptions)
2808 return tree_could_trap_p (t);
2809 return false;
2812 /* Return true if STMT can throw an exception that is not caught within
2813 the current function (CFUN). */
2815 bool
2816 stmt_can_throw_external (gimple stmt)
2818 int lp_nr;
2820 if (!stmt_could_throw_p (stmt))
2821 return false;
2823 lp_nr = lookup_stmt_eh_lp (stmt);
2824 return lp_nr == 0;
2827 /* Return true if STMT can throw an exception that is caught within
2828 the current function (CFUN). */
2830 bool
2831 stmt_can_throw_internal (gimple stmt)
2833 int lp_nr;
2835 if (!stmt_could_throw_p (stmt))
2836 return false;
2838 lp_nr = lookup_stmt_eh_lp (stmt);
2839 return lp_nr > 0;
2842 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2843 remove any entry it might have from the EH table. Return true if
2844 any change was made. */
2846 bool
2847 maybe_clean_eh_stmt_fn (struct function *ifun, gimple stmt)
2849 if (stmt_could_throw_p (stmt))
2850 return false;
2851 return remove_stmt_from_eh_lp_fn (ifun, stmt);
2854 /* Likewise, but always use the current function. */
2856 bool
2857 maybe_clean_eh_stmt (gimple stmt)
2859 return maybe_clean_eh_stmt_fn (cfun, stmt);
2862 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2863 OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2864 in the table if it should be in there. Return TRUE if a replacement was
2865 done that my require an EH edge purge. */
2867 bool
2868 maybe_clean_or_replace_eh_stmt (gimple old_stmt, gimple new_stmt)
2870 int lp_nr = lookup_stmt_eh_lp (old_stmt);
2872 if (lp_nr != 0)
2874 bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2876 if (new_stmt == old_stmt && new_stmt_could_throw)
2877 return false;
2879 remove_stmt_from_eh_lp (old_stmt);
2880 if (new_stmt_could_throw)
2882 add_stmt_to_eh_lp (new_stmt, lp_nr);
2883 return false;
2885 else
2886 return true;
2889 return false;
2892 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statement NEW_STMT
2893 in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT. The MAP
2894 operand is the return value of duplicate_eh_regions. */
2896 bool
2897 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple new_stmt,
2898 struct function *old_fun, gimple old_stmt,
2899 struct pointer_map_t *map, int default_lp_nr)
2901 int old_lp_nr, new_lp_nr;
2902 void **slot;
2904 if (!stmt_could_throw_p (new_stmt))
2905 return false;
2907 old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2908 if (old_lp_nr == 0)
2910 if (default_lp_nr == 0)
2911 return false;
2912 new_lp_nr = default_lp_nr;
2914 else if (old_lp_nr > 0)
2916 eh_landing_pad old_lp, new_lp;
2918 old_lp = (*old_fun->eh->lp_array)[old_lp_nr];
2919 slot = pointer_map_contains (map, old_lp);
2920 new_lp = (eh_landing_pad) *slot;
2921 new_lp_nr = new_lp->index;
2923 else
2925 eh_region old_r, new_r;
2927 old_r = (*old_fun->eh->region_array)[-old_lp_nr];
2928 slot = pointer_map_contains (map, old_r);
2929 new_r = (eh_region) *slot;
2930 new_lp_nr = -new_r->index;
2933 add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2934 return true;
2937 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2938 and thus no remapping is required. */
2940 bool
2941 maybe_duplicate_eh_stmt (gimple new_stmt, gimple old_stmt)
2943 int lp_nr;
2945 if (!stmt_could_throw_p (new_stmt))
2946 return false;
2948 lp_nr = lookup_stmt_eh_lp (old_stmt);
2949 if (lp_nr == 0)
2950 return false;
2952 add_stmt_to_eh_lp (new_stmt, lp_nr);
2953 return true;
2956 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2957 GIMPLE_TRY) that are similar enough to be considered the same. Currently
2958 this only handles handlers consisting of a single call, as that's the
2959 important case for C++: a destructor call for a particular object showing
2960 up in multiple handlers. */
2962 static bool
2963 same_handler_p (gimple_seq oneh, gimple_seq twoh)
2965 gimple_stmt_iterator gsi;
2966 gimple ones, twos;
2967 unsigned int ai;
2969 gsi = gsi_start (oneh);
2970 if (!gsi_one_before_end_p (gsi))
2971 return false;
2972 ones = gsi_stmt (gsi);
2974 gsi = gsi_start (twoh);
2975 if (!gsi_one_before_end_p (gsi))
2976 return false;
2977 twos = gsi_stmt (gsi);
2979 if (!is_gimple_call (ones)
2980 || !is_gimple_call (twos)
2981 || gimple_call_lhs (ones)
2982 || gimple_call_lhs (twos)
2983 || gimple_call_chain (ones)
2984 || gimple_call_chain (twos)
2985 || !gimple_call_same_target_p (ones, twos)
2986 || gimple_call_num_args (ones) != gimple_call_num_args (twos))
2987 return false;
2989 for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
2990 if (!operand_equal_p (gimple_call_arg (ones, ai),
2991 gimple_call_arg (twos, ai), 0))
2992 return false;
2994 return true;
2997 /* Optimize
2998 try { A() } finally { try { ~B() } catch { ~A() } }
2999 try { ... } finally { ~A() }
3000 into
3001 try { A() } catch { ~B() }
3002 try { ~B() ... } finally { ~A() }
3004 This occurs frequently in C++, where A is a local variable and B is a
3005 temporary used in the initializer for A. */
3007 static void
3008 optimize_double_finally (gimple one, gimple two)
3010 gimple oneh;
3011 gimple_stmt_iterator gsi;
3012 gimple_seq cleanup;
3014 cleanup = gimple_try_cleanup (one);
3015 gsi = gsi_start (cleanup);
3016 if (!gsi_one_before_end_p (gsi))
3017 return;
3019 oneh = gsi_stmt (gsi);
3020 if (gimple_code (oneh) != GIMPLE_TRY
3021 || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
3022 return;
3024 if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
3026 gimple_seq seq = gimple_try_eval (oneh);
3028 gimple_try_set_cleanup (one, seq);
3029 gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
3030 seq = copy_gimple_seq_and_replace_locals (seq);
3031 gimple_seq_add_seq (&seq, gimple_try_eval (two));
3032 gimple_try_set_eval (two, seq);
3036 /* Perform EH refactoring optimizations that are simpler to do when code
3037 flow has been lowered but EH structures haven't. */
3039 static void
3040 refactor_eh_r (gimple_seq seq)
3042 gimple_stmt_iterator gsi;
3043 gimple one, two;
3045 one = NULL;
3046 two = NULL;
3047 gsi = gsi_start (seq);
3048 while (1)
3050 one = two;
3051 if (gsi_end_p (gsi))
3052 two = NULL;
3053 else
3054 two = gsi_stmt (gsi);
3055 if (one
3056 && two
3057 && gimple_code (one) == GIMPLE_TRY
3058 && gimple_code (two) == GIMPLE_TRY
3059 && gimple_try_kind (one) == GIMPLE_TRY_FINALLY
3060 && gimple_try_kind (two) == GIMPLE_TRY_FINALLY)
3061 optimize_double_finally (one, two);
3062 if (one)
3063 switch (gimple_code (one))
3065 case GIMPLE_TRY:
3066 refactor_eh_r (gimple_try_eval (one));
3067 refactor_eh_r (gimple_try_cleanup (one));
3068 break;
3069 case GIMPLE_CATCH:
3070 refactor_eh_r (gimple_catch_handler (one));
3071 break;
3072 case GIMPLE_EH_FILTER:
3073 refactor_eh_r (gimple_eh_filter_failure (one));
3074 break;
3075 case GIMPLE_EH_ELSE:
3076 refactor_eh_r (gimple_eh_else_n_body (one));
3077 refactor_eh_r (gimple_eh_else_e_body (one));
3078 break;
3079 default:
3080 break;
3082 if (two)
3083 gsi_next (&gsi);
3084 else
3085 break;
3089 static unsigned
3090 refactor_eh (void)
3092 refactor_eh_r (gimple_body (current_function_decl));
3093 return 0;
3096 static bool
3097 gate_refactor_eh (void)
3099 return flag_exceptions != 0;
3102 namespace {
3104 const pass_data pass_data_refactor_eh =
3106 GIMPLE_PASS, /* type */
3107 "ehopt", /* name */
3108 OPTGROUP_NONE, /* optinfo_flags */
3109 true, /* has_gate */
3110 true, /* has_execute */
3111 TV_TREE_EH, /* tv_id */
3112 PROP_gimple_lcf, /* properties_required */
3113 0, /* properties_provided */
3114 0, /* properties_destroyed */
3115 0, /* todo_flags_start */
3116 0, /* todo_flags_finish */
3119 class pass_refactor_eh : public gimple_opt_pass
3121 public:
3122 pass_refactor_eh (gcc::context *ctxt)
3123 : gimple_opt_pass (pass_data_refactor_eh, ctxt)
3126 /* opt_pass methods: */
3127 bool gate () { return gate_refactor_eh (); }
3128 unsigned int execute () { return refactor_eh (); }
3130 }; // class pass_refactor_eh
3132 } // anon namespace
3134 gimple_opt_pass *
3135 make_pass_refactor_eh (gcc::context *ctxt)
3137 return new pass_refactor_eh (ctxt);
3140 /* At the end of gimple optimization, we can lower RESX. */
3142 static bool
3143 lower_resx (basic_block bb, gimple stmt, struct pointer_map_t *mnt_map)
3145 int lp_nr;
3146 eh_region src_r, dst_r;
3147 gimple_stmt_iterator gsi;
3148 gimple x;
3149 tree fn, src_nr;
3150 bool ret = false;
3152 lp_nr = lookup_stmt_eh_lp (stmt);
3153 if (lp_nr != 0)
3154 dst_r = get_eh_region_from_lp_number (lp_nr);
3155 else
3156 dst_r = NULL;
3158 src_r = get_eh_region_from_number (gimple_resx_region (stmt));
3159 gsi = gsi_last_bb (bb);
3161 if (src_r == NULL)
3163 /* We can wind up with no source region when pass_cleanup_eh shows
3164 that there are no entries into an eh region and deletes it, but
3165 then the block that contains the resx isn't removed. This can
3166 happen without optimization when the switch statement created by
3167 lower_try_finally_switch isn't simplified to remove the eh case.
3169 Resolve this by expanding the resx node to an abort. */
3171 fn = builtin_decl_implicit (BUILT_IN_TRAP);
3172 x = gimple_build_call (fn, 0);
3173 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3175 while (EDGE_COUNT (bb->succs) > 0)
3176 remove_edge (EDGE_SUCC (bb, 0));
3178 else if (dst_r)
3180 /* When we have a destination region, we resolve this by copying
3181 the excptr and filter values into place, and changing the edge
3182 to immediately after the landing pad. */
3183 edge e;
3185 if (lp_nr < 0)
3187 basic_block new_bb;
3188 void **slot;
3189 tree lab;
3191 /* We are resuming into a MUST_NOT_CALL region. Expand a call to
3192 the failure decl into a new block, if needed. */
3193 gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
3195 slot = pointer_map_contains (mnt_map, dst_r);
3196 if (slot == NULL)
3198 gimple_stmt_iterator gsi2;
3200 new_bb = create_empty_bb (bb);
3201 if (current_loops)
3202 add_bb_to_loop (new_bb, bb->loop_father);
3203 lab = gimple_block_label (new_bb);
3204 gsi2 = gsi_start_bb (new_bb);
3206 fn = dst_r->u.must_not_throw.failure_decl;
3207 x = gimple_build_call (fn, 0);
3208 gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
3209 gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
3211 slot = pointer_map_insert (mnt_map, dst_r);
3212 *slot = lab;
3214 else
3216 lab = (tree) *slot;
3217 new_bb = label_to_block (lab);
3220 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3221 e = make_edge (bb, new_bb, EDGE_FALLTHRU);
3222 e->count = bb->count;
3223 e->probability = REG_BR_PROB_BASE;
3225 else
3227 edge_iterator ei;
3228 tree dst_nr = build_int_cst (integer_type_node, dst_r->index);
3230 fn = builtin_decl_implicit (BUILT_IN_EH_COPY_VALUES);
3231 src_nr = build_int_cst (integer_type_node, src_r->index);
3232 x = gimple_build_call (fn, 2, dst_nr, src_nr);
3233 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3235 /* Update the flags for the outgoing edge. */
3236 e = single_succ_edge (bb);
3237 gcc_assert (e->flags & EDGE_EH);
3238 e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3240 /* If there are no more EH users of the landing pad, delete it. */
3241 FOR_EACH_EDGE (e, ei, e->dest->preds)
3242 if (e->flags & EDGE_EH)
3243 break;
3244 if (e == NULL)
3246 eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
3247 remove_eh_landing_pad (lp);
3251 ret = true;
3253 else
3255 tree var;
3257 /* When we don't have a destination region, this exception escapes
3258 up the call chain. We resolve this by generating a call to the
3259 _Unwind_Resume library function. */
3261 /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
3262 with no arguments for C++ and Java. Check for that. */
3263 if (src_r->use_cxa_end_cleanup)
3265 fn = builtin_decl_implicit (BUILT_IN_CXA_END_CLEANUP);
3266 x = gimple_build_call (fn, 0);
3267 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3269 else
3271 fn = builtin_decl_implicit (BUILT_IN_EH_POINTER);
3272 src_nr = build_int_cst (integer_type_node, src_r->index);
3273 x = gimple_build_call (fn, 1, src_nr);
3274 var = create_tmp_var (ptr_type_node, NULL);
3275 var = make_ssa_name (var, x);
3276 gimple_call_set_lhs (x, var);
3277 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3279 fn = builtin_decl_implicit (BUILT_IN_UNWIND_RESUME);
3280 x = gimple_build_call (fn, 1, var);
3281 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3284 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3287 gsi_remove (&gsi, true);
3289 return ret;
3292 static unsigned
3293 execute_lower_resx (void)
3295 basic_block bb;
3296 struct pointer_map_t *mnt_map;
3297 bool dominance_invalidated = false;
3298 bool any_rewritten = false;
3300 mnt_map = pointer_map_create ();
3302 FOR_EACH_BB (bb)
3304 gimple last = last_stmt (bb);
3305 if (last && is_gimple_resx (last))
3307 dominance_invalidated |= lower_resx (bb, last, mnt_map);
3308 any_rewritten = true;
3312 pointer_map_destroy (mnt_map);
3314 if (dominance_invalidated)
3316 free_dominance_info (CDI_DOMINATORS);
3317 free_dominance_info (CDI_POST_DOMINATORS);
3320 return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3323 static bool
3324 gate_lower_resx (void)
3326 return flag_exceptions != 0;
3329 namespace {
3331 const pass_data pass_data_lower_resx =
3333 GIMPLE_PASS, /* type */
3334 "resx", /* name */
3335 OPTGROUP_NONE, /* optinfo_flags */
3336 true, /* has_gate */
3337 true, /* has_execute */
3338 TV_TREE_EH, /* tv_id */
3339 PROP_gimple_lcf, /* properties_required */
3340 0, /* properties_provided */
3341 0, /* properties_destroyed */
3342 0, /* todo_flags_start */
3343 TODO_verify_flow, /* todo_flags_finish */
3346 class pass_lower_resx : public gimple_opt_pass
3348 public:
3349 pass_lower_resx (gcc::context *ctxt)
3350 : gimple_opt_pass (pass_data_lower_resx, ctxt)
3353 /* opt_pass methods: */
3354 bool gate () { return gate_lower_resx (); }
3355 unsigned int execute () { return execute_lower_resx (); }
3357 }; // class pass_lower_resx
3359 } // anon namespace
3361 gimple_opt_pass *
3362 make_pass_lower_resx (gcc::context *ctxt)
3364 return new pass_lower_resx (ctxt);
3367 /* Try to optimize var = {v} {CLOBBER} stmts followed just by
3368 external throw. */
3370 static void
3371 optimize_clobbers (basic_block bb)
3373 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3374 bool any_clobbers = false;
3375 bool seen_stack_restore = false;
3376 edge_iterator ei;
3377 edge e;
3379 /* Only optimize anything if the bb contains at least one clobber,
3380 ends with resx (checked by caller), optionally contains some
3381 debug stmts or labels, or at most one __builtin_stack_restore
3382 call, and has an incoming EH edge. */
3383 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3385 gimple stmt = gsi_stmt (gsi);
3386 if (is_gimple_debug (stmt))
3387 continue;
3388 if (gimple_clobber_p (stmt))
3390 any_clobbers = true;
3391 continue;
3393 if (!seen_stack_restore
3394 && gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
3396 seen_stack_restore = true;
3397 continue;
3399 if (gimple_code (stmt) == GIMPLE_LABEL)
3400 break;
3401 return;
3403 if (!any_clobbers)
3404 return;
3405 FOR_EACH_EDGE (e, ei, bb->preds)
3406 if (e->flags & EDGE_EH)
3407 break;
3408 if (e == NULL)
3409 return;
3410 gsi = gsi_last_bb (bb);
3411 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3413 gimple stmt = gsi_stmt (gsi);
3414 if (!gimple_clobber_p (stmt))
3415 continue;
3416 unlink_stmt_vdef (stmt);
3417 gsi_remove (&gsi, true);
3418 release_defs (stmt);
3422 /* Try to sink var = {v} {CLOBBER} stmts followed just by
3423 internal throw to successor BB. */
3425 static int
3426 sink_clobbers (basic_block bb)
3428 edge e;
3429 edge_iterator ei;
3430 gimple_stmt_iterator gsi, dgsi;
3431 basic_block succbb;
3432 bool any_clobbers = false;
3433 unsigned todo = 0;
3435 /* Only optimize if BB has a single EH successor and
3436 all predecessor edges are EH too. */
3437 if (!single_succ_p (bb)
3438 || (single_succ_edge (bb)->flags & EDGE_EH) == 0)
3439 return 0;
3441 FOR_EACH_EDGE (e, ei, bb->preds)
3443 if ((e->flags & EDGE_EH) == 0)
3444 return 0;
3447 /* And BB contains only CLOBBER stmts before the final
3448 RESX. */
3449 gsi = gsi_last_bb (bb);
3450 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3452 gimple stmt = gsi_stmt (gsi);
3453 if (is_gimple_debug (stmt))
3454 continue;
3455 if (gimple_code (stmt) == GIMPLE_LABEL)
3456 break;
3457 if (!gimple_clobber_p (stmt))
3458 return 0;
3459 any_clobbers = true;
3461 if (!any_clobbers)
3462 return 0;
3464 edge succe = single_succ_edge (bb);
3465 succbb = succe->dest;
3467 /* See if there is a virtual PHI node to take an updated virtual
3468 operand from. */
3469 gimple vphi = NULL;
3470 tree vuse = NULL_TREE;
3471 for (gsi = gsi_start_phis (succbb); !gsi_end_p (gsi); gsi_next (&gsi))
3473 tree res = gimple_phi_result (gsi_stmt (gsi));
3474 if (virtual_operand_p (res))
3476 vphi = gsi_stmt (gsi);
3477 vuse = res;
3478 break;
3482 dgsi = gsi_after_labels (succbb);
3483 gsi = gsi_last_bb (bb);
3484 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3486 gimple stmt = gsi_stmt (gsi);
3487 tree lhs;
3488 if (is_gimple_debug (stmt))
3489 continue;
3490 if (gimple_code (stmt) == GIMPLE_LABEL)
3491 break;
3492 lhs = gimple_assign_lhs (stmt);
3493 /* Unfortunately we don't have dominance info updated at this
3494 point, so checking if
3495 dominated_by_p (CDI_DOMINATORS, succbb,
3496 gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (lhs, 0)))
3497 would be too costly. Thus, avoid sinking any clobbers that
3498 refer to non-(D) SSA_NAMEs. */
3499 if (TREE_CODE (lhs) == MEM_REF
3500 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
3501 && !SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0)))
3503 unlink_stmt_vdef (stmt);
3504 gsi_remove (&gsi, true);
3505 release_defs (stmt);
3506 continue;
3509 /* As we do not change stmt order when sinking across a
3510 forwarder edge we can keep virtual operands in place. */
3511 gsi_remove (&gsi, false);
3512 gsi_insert_before (&dgsi, stmt, GSI_NEW_STMT);
3514 /* But adjust virtual operands if we sunk across a PHI node. */
3515 if (vuse)
3517 gimple use_stmt;
3518 imm_use_iterator iter;
3519 use_operand_p use_p;
3520 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vuse)
3521 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3522 SET_USE (use_p, gimple_vdef (stmt));
3523 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse))
3525 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_vdef (stmt)) = 1;
3526 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 0;
3528 /* Adjust the incoming virtual operand. */
3529 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (vphi, succe), gimple_vuse (stmt));
3530 SET_USE (gimple_vuse_op (stmt), vuse);
3532 /* If there isn't a single predecessor but no virtual PHI node
3533 arrange for virtual operands to be renamed. */
3534 else if (gimple_vuse_op (stmt) != NULL_USE_OPERAND_P
3535 && !single_pred_p (succbb))
3537 /* In this case there will be no use of the VDEF of this stmt.
3538 ??? Unless this is a secondary opportunity and we have not
3539 removed unreachable blocks yet, so we cannot assert this.
3540 Which also means we will end up renaming too many times. */
3541 SET_USE (gimple_vuse_op (stmt), gimple_vop (cfun));
3542 mark_virtual_operands_for_renaming (cfun);
3543 todo |= TODO_update_ssa_only_virtuals;
3547 return todo;
3550 /* At the end of inlining, we can lower EH_DISPATCH. Return true when
3551 we have found some duplicate labels and removed some edges. */
3553 static bool
3554 lower_eh_dispatch (basic_block src, gimple stmt)
3556 gimple_stmt_iterator gsi;
3557 int region_nr;
3558 eh_region r;
3559 tree filter, fn;
3560 gimple x;
3561 bool redirected = false;
3563 region_nr = gimple_eh_dispatch_region (stmt);
3564 r = get_eh_region_from_number (region_nr);
3566 gsi = gsi_last_bb (src);
3568 switch (r->type)
3570 case ERT_TRY:
3572 vec<tree> labels = vNULL;
3573 tree default_label = NULL;
3574 eh_catch c;
3575 edge_iterator ei;
3576 edge e;
3577 struct pointer_set_t *seen_values = pointer_set_create ();
3579 /* Collect the labels for a switch. Zero the post_landing_pad
3580 field becase we'll no longer have anything keeping these labels
3581 in existence and the optimizer will be free to merge these
3582 blocks at will. */
3583 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3585 tree tp_node, flt_node, lab = c->label;
3586 bool have_label = false;
3588 c->label = NULL;
3589 tp_node = c->type_list;
3590 flt_node = c->filter_list;
3592 if (tp_node == NULL)
3594 default_label = lab;
3595 break;
3599 /* Filter out duplicate labels that arise when this handler
3600 is shadowed by an earlier one. When no labels are
3601 attached to the handler anymore, we remove
3602 the corresponding edge and then we delete unreachable
3603 blocks at the end of this pass. */
3604 if (! pointer_set_contains (seen_values, TREE_VALUE (flt_node)))
3606 tree t = build_case_label (TREE_VALUE (flt_node),
3607 NULL, lab);
3608 labels.safe_push (t);
3609 pointer_set_insert (seen_values, TREE_VALUE (flt_node));
3610 have_label = true;
3613 tp_node = TREE_CHAIN (tp_node);
3614 flt_node = TREE_CHAIN (flt_node);
3616 while (tp_node);
3617 if (! have_label)
3619 remove_edge (find_edge (src, label_to_block (lab)));
3620 redirected = true;
3624 /* Clean up the edge flags. */
3625 FOR_EACH_EDGE (e, ei, src->succs)
3627 if (e->flags & EDGE_FALLTHRU)
3629 /* If there was no catch-all, use the fallthru edge. */
3630 if (default_label == NULL)
3631 default_label = gimple_block_label (e->dest);
3632 e->flags &= ~EDGE_FALLTHRU;
3635 gcc_assert (default_label != NULL);
3637 /* Don't generate a switch if there's only a default case.
3638 This is common in the form of try { A; } catch (...) { B; }. */
3639 if (!labels.exists ())
3641 e = single_succ_edge (src);
3642 e->flags |= EDGE_FALLTHRU;
3644 else
3646 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3647 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3648 region_nr));
3649 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)), NULL);
3650 filter = make_ssa_name (filter, x);
3651 gimple_call_set_lhs (x, filter);
3652 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3654 /* Turn the default label into a default case. */
3655 default_label = build_case_label (NULL, NULL, default_label);
3656 sort_case_labels (labels);
3658 x = gimple_build_switch (filter, default_label, labels);
3659 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3661 labels.release ();
3663 pointer_set_destroy (seen_values);
3665 break;
3667 case ERT_ALLOWED_EXCEPTIONS:
3669 edge b_e = BRANCH_EDGE (src);
3670 edge f_e = FALLTHRU_EDGE (src);
3672 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3673 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3674 region_nr));
3675 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)), NULL);
3676 filter = make_ssa_name (filter, x);
3677 gimple_call_set_lhs (x, filter);
3678 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3680 r->u.allowed.label = NULL;
3681 x = gimple_build_cond (EQ_EXPR, filter,
3682 build_int_cst (TREE_TYPE (filter),
3683 r->u.allowed.filter),
3684 NULL_TREE, NULL_TREE);
3685 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3687 b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3688 f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3690 break;
3692 default:
3693 gcc_unreachable ();
3696 /* Replace the EH_DISPATCH with the SWITCH or COND generated above. */
3697 gsi_remove (&gsi, true);
3698 return redirected;
3701 static unsigned
3702 execute_lower_eh_dispatch (void)
3704 basic_block bb;
3705 int flags = 0;
3706 bool redirected = false;
3708 assign_filter_values ();
3710 FOR_EACH_BB (bb)
3712 gimple last = last_stmt (bb);
3713 if (last == NULL)
3714 continue;
3715 if (gimple_code (last) == GIMPLE_EH_DISPATCH)
3717 redirected |= lower_eh_dispatch (bb, last);
3718 flags |= TODO_update_ssa_only_virtuals;
3720 else if (gimple_code (last) == GIMPLE_RESX)
3722 if (stmt_can_throw_external (last))
3723 optimize_clobbers (bb);
3724 else
3725 flags |= sink_clobbers (bb);
3729 if (redirected)
3730 delete_unreachable_blocks ();
3731 return flags;
3734 static bool
3735 gate_lower_eh_dispatch (void)
3737 return cfun->eh->region_tree != NULL;
3740 namespace {
3742 const pass_data pass_data_lower_eh_dispatch =
3744 GIMPLE_PASS, /* type */
3745 "ehdisp", /* name */
3746 OPTGROUP_NONE, /* optinfo_flags */
3747 true, /* has_gate */
3748 true, /* has_execute */
3749 TV_TREE_EH, /* tv_id */
3750 PROP_gimple_lcf, /* properties_required */
3751 0, /* properties_provided */
3752 0, /* properties_destroyed */
3753 0, /* todo_flags_start */
3754 TODO_verify_flow, /* todo_flags_finish */
3757 class pass_lower_eh_dispatch : public gimple_opt_pass
3759 public:
3760 pass_lower_eh_dispatch (gcc::context *ctxt)
3761 : gimple_opt_pass (pass_data_lower_eh_dispatch, ctxt)
3764 /* opt_pass methods: */
3765 bool gate () { return gate_lower_eh_dispatch (); }
3766 unsigned int execute () { return execute_lower_eh_dispatch (); }
3768 }; // class pass_lower_eh_dispatch
3770 } // anon namespace
3772 gimple_opt_pass *
3773 make_pass_lower_eh_dispatch (gcc::context *ctxt)
3775 return new pass_lower_eh_dispatch (ctxt);
3778 /* Walk statements, see what regions and, optionally, landing pads
3779 are really referenced.
3781 Returns in R_REACHABLEP an sbitmap with bits set for reachable regions,
3782 and in LP_REACHABLE an sbitmap with bits set for reachable landing pads.
3784 Passing NULL for LP_REACHABLE is valid, in this case only reachable
3785 regions are marked.
3787 The caller is responsible for freeing the returned sbitmaps. */
3789 static void
3790 mark_reachable_handlers (sbitmap *r_reachablep, sbitmap *lp_reachablep)
3792 sbitmap r_reachable, lp_reachable;
3793 basic_block bb;
3794 bool mark_landing_pads = (lp_reachablep != NULL);
3795 gcc_checking_assert (r_reachablep != NULL);
3797 r_reachable = sbitmap_alloc (cfun->eh->region_array->length ());
3798 bitmap_clear (r_reachable);
3799 *r_reachablep = r_reachable;
3801 if (mark_landing_pads)
3803 lp_reachable = sbitmap_alloc (cfun->eh->lp_array->length ());
3804 bitmap_clear (lp_reachable);
3805 *lp_reachablep = lp_reachable;
3807 else
3808 lp_reachable = NULL;
3810 FOR_EACH_BB (bb)
3812 gimple_stmt_iterator gsi;
3814 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3816 gimple stmt = gsi_stmt (gsi);
3818 if (mark_landing_pads)
3820 int lp_nr = lookup_stmt_eh_lp (stmt);
3822 /* Negative LP numbers are MUST_NOT_THROW regions which
3823 are not considered BB enders. */
3824 if (lp_nr < 0)
3825 bitmap_set_bit (r_reachable, -lp_nr);
3827 /* Positive LP numbers are real landing pads, and BB enders. */
3828 else if (lp_nr > 0)
3830 gcc_assert (gsi_one_before_end_p (gsi));
3831 eh_region region = get_eh_region_from_lp_number (lp_nr);
3832 bitmap_set_bit (r_reachable, region->index);
3833 bitmap_set_bit (lp_reachable, lp_nr);
3837 /* Avoid removing regions referenced from RESX/EH_DISPATCH. */
3838 switch (gimple_code (stmt))
3840 case GIMPLE_RESX:
3841 bitmap_set_bit (r_reachable, gimple_resx_region (stmt));
3842 break;
3843 case GIMPLE_EH_DISPATCH:
3844 bitmap_set_bit (r_reachable, gimple_eh_dispatch_region (stmt));
3845 break;
3846 default:
3847 break;
3853 /* Remove unreachable handlers and unreachable landing pads. */
3855 static void
3856 remove_unreachable_handlers (void)
3858 sbitmap r_reachable, lp_reachable;
3859 eh_region region;
3860 eh_landing_pad lp;
3861 unsigned i;
3863 mark_reachable_handlers (&r_reachable, &lp_reachable);
3865 if (dump_file)
3867 fprintf (dump_file, "Before removal of unreachable regions:\n");
3868 dump_eh_tree (dump_file, cfun);
3869 fprintf (dump_file, "Reachable regions: ");
3870 dump_bitmap_file (dump_file, r_reachable);
3871 fprintf (dump_file, "Reachable landing pads: ");
3872 dump_bitmap_file (dump_file, lp_reachable);
3875 if (dump_file)
3877 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3878 if (region && !bitmap_bit_p (r_reachable, region->index))
3879 fprintf (dump_file,
3880 "Removing unreachable region %d\n",
3881 region->index);
3884 remove_unreachable_eh_regions (r_reachable);
3886 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3887 if (lp && !bitmap_bit_p (lp_reachable, lp->index))
3889 if (dump_file)
3890 fprintf (dump_file,
3891 "Removing unreachable landing pad %d\n",
3892 lp->index);
3893 remove_eh_landing_pad (lp);
3896 if (dump_file)
3898 fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3899 dump_eh_tree (dump_file, cfun);
3900 fprintf (dump_file, "\n\n");
3903 sbitmap_free (r_reachable);
3904 sbitmap_free (lp_reachable);
3906 #ifdef ENABLE_CHECKING
3907 verify_eh_tree (cfun);
3908 #endif
3911 /* Remove unreachable handlers if any landing pads have been removed after
3912 last ehcleanup pass (due to gimple_purge_dead_eh_edges). */
3914 void
3915 maybe_remove_unreachable_handlers (void)
3917 eh_landing_pad lp;
3918 unsigned i;
3920 if (cfun->eh == NULL)
3921 return;
3923 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3924 if (lp && lp->post_landing_pad)
3926 if (label_to_block (lp->post_landing_pad) == NULL)
3928 remove_unreachable_handlers ();
3929 return;
3934 /* Remove regions that do not have landing pads. This assumes
3935 that remove_unreachable_handlers has already been run, and
3936 that we've just manipulated the landing pads since then.
3938 Preserve regions with landing pads and regions that prevent
3939 exceptions from propagating further, even if these regions
3940 are not reachable. */
3942 static void
3943 remove_unreachable_handlers_no_lp (void)
3945 eh_region region;
3946 sbitmap r_reachable;
3947 unsigned i;
3949 mark_reachable_handlers (&r_reachable, /*lp_reachablep=*/NULL);
3951 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3953 if (! region)
3954 continue;
3956 if (region->landing_pads != NULL
3957 || region->type == ERT_MUST_NOT_THROW)
3958 bitmap_set_bit (r_reachable, region->index);
3960 if (dump_file
3961 && !bitmap_bit_p (r_reachable, region->index))
3962 fprintf (dump_file,
3963 "Removing unreachable region %d\n",
3964 region->index);
3967 remove_unreachable_eh_regions (r_reachable);
3969 sbitmap_free (r_reachable);
3972 /* Undo critical edge splitting on an EH landing pad. Earlier, we
3973 optimisticaly split all sorts of edges, including EH edges. The
3974 optimization passes in between may not have needed them; if not,
3975 we should undo the split.
3977 Recognize this case by having one EH edge incoming to the BB and
3978 one normal edge outgoing; BB should be empty apart from the
3979 post_landing_pad label.
3981 Note that this is slightly different from the empty handler case
3982 handled by cleanup_empty_eh, in that the actual handler may yet
3983 have actual code but the landing pad has been separated from the
3984 handler. As such, cleanup_empty_eh relies on this transformation
3985 having been done first. */
3987 static bool
3988 unsplit_eh (eh_landing_pad lp)
3990 basic_block bb = label_to_block (lp->post_landing_pad);
3991 gimple_stmt_iterator gsi;
3992 edge e_in, e_out;
3994 /* Quickly check the edge counts on BB for singularity. */
3995 if (!single_pred_p (bb) || !single_succ_p (bb))
3996 return false;
3997 e_in = single_pred_edge (bb);
3998 e_out = single_succ_edge (bb);
4000 /* Input edge must be EH and output edge must be normal. */
4001 if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
4002 return false;
4004 /* The block must be empty except for the labels and debug insns. */
4005 gsi = gsi_after_labels (bb);
4006 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4007 gsi_next_nondebug (&gsi);
4008 if (!gsi_end_p (gsi))
4009 return false;
4011 /* The destination block must not already have a landing pad
4012 for a different region. */
4013 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4015 gimple stmt = gsi_stmt (gsi);
4016 tree lab;
4017 int lp_nr;
4019 if (gimple_code (stmt) != GIMPLE_LABEL)
4020 break;
4021 lab = gimple_label_label (stmt);
4022 lp_nr = EH_LANDING_PAD_NR (lab);
4023 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4024 return false;
4027 /* The new destination block must not already be a destination of
4028 the source block, lest we merge fallthru and eh edges and get
4029 all sorts of confused. */
4030 if (find_edge (e_in->src, e_out->dest))
4031 return false;
4033 /* ??? We can get degenerate phis due to cfg cleanups. I would have
4034 thought this should have been cleaned up by a phicprop pass, but
4035 that doesn't appear to handle virtuals. Propagate by hand. */
4036 if (!gimple_seq_empty_p (phi_nodes (bb)))
4038 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); )
4040 gimple use_stmt, phi = gsi_stmt (gsi);
4041 tree lhs = gimple_phi_result (phi);
4042 tree rhs = gimple_phi_arg_def (phi, 0);
4043 use_operand_p use_p;
4044 imm_use_iterator iter;
4046 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4048 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4049 SET_USE (use_p, rhs);
4052 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4053 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
4055 remove_phi_node (&gsi, true);
4059 if (dump_file && (dump_flags & TDF_DETAILS))
4060 fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
4061 lp->index, e_out->dest->index);
4063 /* Redirect the edge. Since redirect_eh_edge_1 expects to be moving
4064 a successor edge, humor it. But do the real CFG change with the
4065 predecessor of E_OUT in order to preserve the ordering of arguments
4066 to the PHI nodes in E_OUT->DEST. */
4067 redirect_eh_edge_1 (e_in, e_out->dest, false);
4068 redirect_edge_pred (e_out, e_in->src);
4069 e_out->flags = e_in->flags;
4070 e_out->probability = e_in->probability;
4071 e_out->count = e_in->count;
4072 remove_edge (e_in);
4074 return true;
4077 /* Examine each landing pad block and see if it matches unsplit_eh. */
4079 static bool
4080 unsplit_all_eh (void)
4082 bool changed = false;
4083 eh_landing_pad lp;
4084 int i;
4086 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4087 if (lp)
4088 changed |= unsplit_eh (lp);
4090 return changed;
4093 /* A subroutine of cleanup_empty_eh. Redirect all EH edges incoming
4094 to OLD_BB to NEW_BB; return true on success, false on failure.
4096 OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
4097 PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
4098 Virtual PHIs may be deleted and marked for renaming. */
4100 static bool
4101 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
4102 edge old_bb_out, bool change_region)
4104 gimple_stmt_iterator ngsi, ogsi;
4105 edge_iterator ei;
4106 edge e;
4107 bitmap ophi_handled;
4109 /* The destination block must not be a regular successor for any
4110 of the preds of the landing pad. Thus, avoid turning
4111 <..>
4112 | \ EH
4113 | <..>
4115 <..>
4116 into
4117 <..>
4118 | | EH
4119 <..>
4120 which CFG verification would choke on. See PR45172 and PR51089. */
4121 FOR_EACH_EDGE (e, ei, old_bb->preds)
4122 if (find_edge (e->src, new_bb))
4123 return false;
4125 FOR_EACH_EDGE (e, ei, old_bb->preds)
4126 redirect_edge_var_map_clear (e);
4128 ophi_handled = BITMAP_ALLOC (NULL);
4130 /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
4131 for the edges we're going to move. */
4132 for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
4134 gimple ophi, nphi = gsi_stmt (ngsi);
4135 tree nresult, nop;
4137 nresult = gimple_phi_result (nphi);
4138 nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
4140 /* Find the corresponding PHI in OLD_BB so we can forward-propagate
4141 the source ssa_name. */
4142 ophi = NULL;
4143 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4145 ophi = gsi_stmt (ogsi);
4146 if (gimple_phi_result (ophi) == nop)
4147 break;
4148 ophi = NULL;
4151 /* If we did find the corresponding PHI, copy those inputs. */
4152 if (ophi)
4154 /* If NOP is used somewhere else beyond phis in new_bb, give up. */
4155 if (!has_single_use (nop))
4157 imm_use_iterator imm_iter;
4158 use_operand_p use_p;
4160 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, nop)
4162 if (!gimple_debug_bind_p (USE_STMT (use_p))
4163 && (gimple_code (USE_STMT (use_p)) != GIMPLE_PHI
4164 || gimple_bb (USE_STMT (use_p)) != new_bb))
4165 goto fail;
4168 bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
4169 FOR_EACH_EDGE (e, ei, old_bb->preds)
4171 location_t oloc;
4172 tree oop;
4174 if ((e->flags & EDGE_EH) == 0)
4175 continue;
4176 oop = gimple_phi_arg_def (ophi, e->dest_idx);
4177 oloc = gimple_phi_arg_location (ophi, e->dest_idx);
4178 redirect_edge_var_map_add (e, nresult, oop, oloc);
4181 /* If we didn't find the PHI, if it's a real variable or a VOP, we know
4182 from the fact that OLD_BB is tree_empty_eh_handler_p that the
4183 variable is unchanged from input to the block and we can simply
4184 re-use the input to NEW_BB from the OLD_BB_OUT edge. */
4185 else
4187 location_t nloc
4188 = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
4189 FOR_EACH_EDGE (e, ei, old_bb->preds)
4190 redirect_edge_var_map_add (e, nresult, nop, nloc);
4194 /* Second, verify that all PHIs from OLD_BB have been handled. If not,
4195 we don't know what values from the other edges into NEW_BB to use. */
4196 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4198 gimple ophi = gsi_stmt (ogsi);
4199 tree oresult = gimple_phi_result (ophi);
4200 if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
4201 goto fail;
4204 /* Finally, move the edges and update the PHIs. */
4205 for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
4206 if (e->flags & EDGE_EH)
4208 /* ??? CFG manipluation routines do not try to update loop
4209 form on edge redirection. Do so manually here for now. */
4210 /* If we redirect a loop entry or latch edge that will either create
4211 a multiple entry loop or rotate the loop. If the loops merge
4212 we may have created a loop with multiple latches.
4213 All of this isn't easily fixed thus cancel the affected loop
4214 and mark the other loop as possibly having multiple latches. */
4215 if (current_loops
4216 && e->dest == e->dest->loop_father->header)
4218 e->dest->loop_father->header = NULL;
4219 e->dest->loop_father->latch = NULL;
4220 new_bb->loop_father->latch = NULL;
4221 loops_state_set (LOOPS_NEED_FIXUP|LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
4223 redirect_eh_edge_1 (e, new_bb, change_region);
4224 redirect_edge_succ (e, new_bb);
4225 flush_pending_stmts (e);
4227 else
4228 ei_next (&ei);
4230 BITMAP_FREE (ophi_handled);
4231 return true;
4233 fail:
4234 FOR_EACH_EDGE (e, ei, old_bb->preds)
4235 redirect_edge_var_map_clear (e);
4236 BITMAP_FREE (ophi_handled);
4237 return false;
4240 /* A subroutine of cleanup_empty_eh. Move a landing pad LP from its
4241 old region to NEW_REGION at BB. */
4243 static void
4244 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
4245 eh_landing_pad lp, eh_region new_region)
4247 gimple_stmt_iterator gsi;
4248 eh_landing_pad *pp;
4250 for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
4251 continue;
4252 *pp = lp->next_lp;
4254 lp->region = new_region;
4255 lp->next_lp = new_region->landing_pads;
4256 new_region->landing_pads = lp;
4258 /* Delete the RESX that was matched within the empty handler block. */
4259 gsi = gsi_last_bb (bb);
4260 unlink_stmt_vdef (gsi_stmt (gsi));
4261 gsi_remove (&gsi, true);
4263 /* Clean up E_OUT for the fallthru. */
4264 e_out->flags = (e_out->flags & ~EDGE_EH) | EDGE_FALLTHRU;
4265 e_out->probability = REG_BR_PROB_BASE;
4268 /* A subroutine of cleanup_empty_eh. Handle more complex cases of
4269 unsplitting than unsplit_eh was prepared to handle, e.g. when
4270 multiple incoming edges and phis are involved. */
4272 static bool
4273 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
4275 gimple_stmt_iterator gsi;
4276 tree lab;
4278 /* We really ought not have totally lost everything following
4279 a landing pad label. Given that BB is empty, there had better
4280 be a successor. */
4281 gcc_assert (e_out != NULL);
4283 /* The destination block must not already have a landing pad
4284 for a different region. */
4285 lab = NULL;
4286 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4288 gimple stmt = gsi_stmt (gsi);
4289 int lp_nr;
4291 if (gimple_code (stmt) != GIMPLE_LABEL)
4292 break;
4293 lab = gimple_label_label (stmt);
4294 lp_nr = EH_LANDING_PAD_NR (lab);
4295 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4296 return false;
4299 /* Attempt to move the PHIs into the successor block. */
4300 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
4302 if (dump_file && (dump_flags & TDF_DETAILS))
4303 fprintf (dump_file,
4304 "Unsplit EH landing pad %d to block %i "
4305 "(via cleanup_empty_eh).\n",
4306 lp->index, e_out->dest->index);
4307 return true;
4310 return false;
4313 /* Return true if edge E_FIRST is part of an empty infinite loop
4314 or leads to such a loop through a series of single successor
4315 empty bbs. */
4317 static bool
4318 infinite_empty_loop_p (edge e_first)
4320 bool inf_loop = false;
4321 edge e;
4323 if (e_first->dest == e_first->src)
4324 return true;
4326 e_first->src->aux = (void *) 1;
4327 for (e = e_first; single_succ_p (e->dest); e = single_succ_edge (e->dest))
4329 gimple_stmt_iterator gsi;
4330 if (e->dest->aux)
4332 inf_loop = true;
4333 break;
4335 e->dest->aux = (void *) 1;
4336 gsi = gsi_after_labels (e->dest);
4337 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4338 gsi_next_nondebug (&gsi);
4339 if (!gsi_end_p (gsi))
4340 break;
4342 e_first->src->aux = NULL;
4343 for (e = e_first; e->dest->aux; e = single_succ_edge (e->dest))
4344 e->dest->aux = NULL;
4346 return inf_loop;
4349 /* Examine the block associated with LP to determine if it's an empty
4350 handler for its EH region. If so, attempt to redirect EH edges to
4351 an outer region. Return true the CFG was updated in any way. This
4352 is similar to jump forwarding, just across EH edges. */
4354 static bool
4355 cleanup_empty_eh (eh_landing_pad lp)
4357 basic_block bb = label_to_block (lp->post_landing_pad);
4358 gimple_stmt_iterator gsi;
4359 gimple resx;
4360 eh_region new_region;
4361 edge_iterator ei;
4362 edge e, e_out;
4363 bool has_non_eh_pred;
4364 bool ret = false;
4365 int new_lp_nr;
4367 /* There can be zero or one edges out of BB. This is the quickest test. */
4368 switch (EDGE_COUNT (bb->succs))
4370 case 0:
4371 e_out = NULL;
4372 break;
4373 case 1:
4374 e_out = single_succ_edge (bb);
4375 break;
4376 default:
4377 return false;
4380 resx = last_stmt (bb);
4381 if (resx && is_gimple_resx (resx))
4383 if (stmt_can_throw_external (resx))
4384 optimize_clobbers (bb);
4385 else if (sink_clobbers (bb))
4386 ret = true;
4389 gsi = gsi_after_labels (bb);
4391 /* Make sure to skip debug statements. */
4392 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4393 gsi_next_nondebug (&gsi);
4395 /* If the block is totally empty, look for more unsplitting cases. */
4396 if (gsi_end_p (gsi))
4398 /* For the degenerate case of an infinite loop bail out. */
4399 if (infinite_empty_loop_p (e_out))
4400 return ret;
4402 return ret | cleanup_empty_eh_unsplit (bb, e_out, lp);
4405 /* The block should consist only of a single RESX statement, modulo a
4406 preceding call to __builtin_stack_restore if there is no outgoing
4407 edge, since the call can be eliminated in this case. */
4408 resx = gsi_stmt (gsi);
4409 if (!e_out && gimple_call_builtin_p (resx, BUILT_IN_STACK_RESTORE))
4411 gsi_next (&gsi);
4412 resx = gsi_stmt (gsi);
4414 if (!is_gimple_resx (resx))
4415 return ret;
4416 gcc_assert (gsi_one_before_end_p (gsi));
4418 /* Determine if there are non-EH edges, or resx edges into the handler. */
4419 has_non_eh_pred = false;
4420 FOR_EACH_EDGE (e, ei, bb->preds)
4421 if (!(e->flags & EDGE_EH))
4422 has_non_eh_pred = true;
4424 /* Find the handler that's outer of the empty handler by looking at
4425 where the RESX instruction was vectored. */
4426 new_lp_nr = lookup_stmt_eh_lp (resx);
4427 new_region = get_eh_region_from_lp_number (new_lp_nr);
4429 /* If there's no destination region within the current function,
4430 redirection is trivial via removing the throwing statements from
4431 the EH region, removing the EH edges, and allowing the block
4432 to go unreachable. */
4433 if (new_region == NULL)
4435 gcc_assert (e_out == NULL);
4436 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4437 if (e->flags & EDGE_EH)
4439 gimple stmt = last_stmt (e->src);
4440 remove_stmt_from_eh_lp (stmt);
4441 remove_edge (e);
4443 else
4444 ei_next (&ei);
4445 goto succeed;
4448 /* If the destination region is a MUST_NOT_THROW, allow the runtime
4449 to handle the abort and allow the blocks to go unreachable. */
4450 if (new_region->type == ERT_MUST_NOT_THROW)
4452 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4453 if (e->flags & EDGE_EH)
4455 gimple stmt = last_stmt (e->src);
4456 remove_stmt_from_eh_lp (stmt);
4457 add_stmt_to_eh_lp (stmt, new_lp_nr);
4458 remove_edge (e);
4460 else
4461 ei_next (&ei);
4462 goto succeed;
4465 /* Try to redirect the EH edges and merge the PHIs into the destination
4466 landing pad block. If the merge succeeds, we'll already have redirected
4467 all the EH edges. The handler itself will go unreachable if there were
4468 no normal edges. */
4469 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
4470 goto succeed;
4472 /* Finally, if all input edges are EH edges, then we can (potentially)
4473 reduce the number of transfers from the runtime by moving the landing
4474 pad from the original region to the new region. This is a win when
4475 we remove the last CLEANUP region along a particular exception
4476 propagation path. Since nothing changes except for the region with
4477 which the landing pad is associated, the PHI nodes do not need to be
4478 adjusted at all. */
4479 if (!has_non_eh_pred)
4481 cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
4482 if (dump_file && (dump_flags & TDF_DETAILS))
4483 fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
4484 lp->index, new_region->index);
4486 /* ??? The CFG didn't change, but we may have rendered the
4487 old EH region unreachable. Trigger a cleanup there. */
4488 return true;
4491 return ret;
4493 succeed:
4494 if (dump_file && (dump_flags & TDF_DETAILS))
4495 fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
4496 remove_eh_landing_pad (lp);
4497 return true;
4500 /* Do a post-order traversal of the EH region tree. Examine each
4501 post_landing_pad block and see if we can eliminate it as empty. */
4503 static bool
4504 cleanup_all_empty_eh (void)
4506 bool changed = false;
4507 eh_landing_pad lp;
4508 int i;
4510 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4511 if (lp)
4512 changed |= cleanup_empty_eh (lp);
4514 return changed;
4517 /* Perform cleanups and lowering of exception handling
4518 1) cleanups regions with handlers doing nothing are optimized out
4519 2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
4520 3) Info about regions that are containing instructions, and regions
4521 reachable via local EH edges is collected
4522 4) Eh tree is pruned for regions no longer necessary.
4524 TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
4525 Unify those that have the same failure decl and locus.
4528 static unsigned int
4529 execute_cleanup_eh_1 (void)
4531 /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
4532 looking up unreachable landing pads. */
4533 remove_unreachable_handlers ();
4535 /* Watch out for the region tree vanishing due to all unreachable. */
4536 if (cfun->eh->region_tree && optimize)
4538 bool changed = false;
4540 changed |= unsplit_all_eh ();
4541 changed |= cleanup_all_empty_eh ();
4543 if (changed)
4545 free_dominance_info (CDI_DOMINATORS);
4546 free_dominance_info (CDI_POST_DOMINATORS);
4548 /* We delayed all basic block deletion, as we may have performed
4549 cleanups on EH edges while non-EH edges were still present. */
4550 delete_unreachable_blocks ();
4552 /* We manipulated the landing pads. Remove any region that no
4553 longer has a landing pad. */
4554 remove_unreachable_handlers_no_lp ();
4556 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4560 return 0;
4563 static unsigned int
4564 execute_cleanup_eh (void)
4566 int ret = execute_cleanup_eh_1 ();
4568 /* If the function no longer needs an EH personality routine
4569 clear it. This exposes cross-language inlining opportunities
4570 and avoids references to a never defined personality routine. */
4571 if (DECL_FUNCTION_PERSONALITY (current_function_decl)
4572 && function_needs_eh_personality (cfun) != eh_personality_lang)
4573 DECL_FUNCTION_PERSONALITY (current_function_decl) = NULL_TREE;
4575 return ret;
4578 static bool
4579 gate_cleanup_eh (void)
4581 return cfun->eh != NULL && cfun->eh->region_tree != NULL;
4584 namespace {
4586 const pass_data pass_data_cleanup_eh =
4588 GIMPLE_PASS, /* type */
4589 "ehcleanup", /* name */
4590 OPTGROUP_NONE, /* optinfo_flags */
4591 true, /* has_gate */
4592 true, /* has_execute */
4593 TV_TREE_EH, /* tv_id */
4594 PROP_gimple_lcf, /* properties_required */
4595 0, /* properties_provided */
4596 0, /* properties_destroyed */
4597 0, /* todo_flags_start */
4598 TODO_verify_ssa, /* todo_flags_finish */
4601 class pass_cleanup_eh : public gimple_opt_pass
4603 public:
4604 pass_cleanup_eh (gcc::context *ctxt)
4605 : gimple_opt_pass (pass_data_cleanup_eh, ctxt)
4608 /* opt_pass methods: */
4609 opt_pass * clone () { return new pass_cleanup_eh (m_ctxt); }
4610 bool gate () { return gate_cleanup_eh (); }
4611 unsigned int execute () { return execute_cleanup_eh (); }
4613 }; // class pass_cleanup_eh
4615 } // anon namespace
4617 gimple_opt_pass *
4618 make_pass_cleanup_eh (gcc::context *ctxt)
4620 return new pass_cleanup_eh (ctxt);
4623 /* Verify that BB containing STMT as the last statement, has precisely the
4624 edge that make_eh_edges would create. */
4626 DEBUG_FUNCTION bool
4627 verify_eh_edges (gimple stmt)
4629 basic_block bb = gimple_bb (stmt);
4630 eh_landing_pad lp = NULL;
4631 int lp_nr;
4632 edge_iterator ei;
4633 edge e, eh_edge;
4635 lp_nr = lookup_stmt_eh_lp (stmt);
4636 if (lp_nr > 0)
4637 lp = get_eh_landing_pad_from_number (lp_nr);
4639 eh_edge = NULL;
4640 FOR_EACH_EDGE (e, ei, bb->succs)
4642 if (e->flags & EDGE_EH)
4644 if (eh_edge)
4646 error ("BB %i has multiple EH edges", bb->index);
4647 return true;
4649 else
4650 eh_edge = e;
4654 if (lp == NULL)
4656 if (eh_edge)
4658 error ("BB %i can not throw but has an EH edge", bb->index);
4659 return true;
4661 return false;
4664 if (!stmt_could_throw_p (stmt))
4666 error ("BB %i last statement has incorrectly set lp", bb->index);
4667 return true;
4670 if (eh_edge == NULL)
4672 error ("BB %i is missing an EH edge", bb->index);
4673 return true;
4676 if (eh_edge->dest != label_to_block (lp->post_landing_pad))
4678 error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
4679 return true;
4682 return false;
4685 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically. */
4687 DEBUG_FUNCTION bool
4688 verify_eh_dispatch_edge (gimple stmt)
4690 eh_region r;
4691 eh_catch c;
4692 basic_block src, dst;
4693 bool want_fallthru = true;
4694 edge_iterator ei;
4695 edge e, fall_edge;
4697 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
4698 src = gimple_bb (stmt);
4700 FOR_EACH_EDGE (e, ei, src->succs)
4701 gcc_assert (e->aux == NULL);
4703 switch (r->type)
4705 case ERT_TRY:
4706 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
4708 dst = label_to_block (c->label);
4709 e = find_edge (src, dst);
4710 if (e == NULL)
4712 error ("BB %i is missing an edge", src->index);
4713 return true;
4715 e->aux = (void *)e;
4717 /* A catch-all handler doesn't have a fallthru. */
4718 if (c->type_list == NULL)
4720 want_fallthru = false;
4721 break;
4724 break;
4726 case ERT_ALLOWED_EXCEPTIONS:
4727 dst = label_to_block (r->u.allowed.label);
4728 e = find_edge (src, dst);
4729 if (e == NULL)
4731 error ("BB %i is missing an edge", src->index);
4732 return true;
4734 e->aux = (void *)e;
4735 break;
4737 default:
4738 gcc_unreachable ();
4741 fall_edge = NULL;
4742 FOR_EACH_EDGE (e, ei, src->succs)
4744 if (e->flags & EDGE_FALLTHRU)
4746 if (fall_edge != NULL)
4748 error ("BB %i too many fallthru edges", src->index);
4749 return true;
4751 fall_edge = e;
4753 else if (e->aux)
4754 e->aux = NULL;
4755 else
4757 error ("BB %i has incorrect edge", src->index);
4758 return true;
4761 if ((fall_edge != NULL) ^ want_fallthru)
4763 error ("BB %i has incorrect fallthru edge", src->index);
4764 return true;
4767 return false;